PackageManagerService.java revision fae8a528f1d4a103c644b9d7da6eff3d55cd0b67
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
26import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendElement;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.annotation.UserIdInt;
121import android.app.ActivityManager;
122import android.app.ActivityManagerInternal;
123import android.app.AppOpsManager;
124import android.app.IActivityManager;
125import android.app.ResourcesManager;
126import android.app.admin.IDevicePolicyManager;
127import android.app.admin.SecurityLog;
128import android.app.backup.IBackupManager;
129import android.content.BroadcastReceiver;
130import android.content.ComponentName;
131import android.content.ContentResolver;
132import android.content.Context;
133import android.content.IIntentReceiver;
134import android.content.Intent;
135import android.content.IntentFilter;
136import android.content.IntentSender;
137import android.content.IntentSender.SendIntentException;
138import android.content.ServiceConnection;
139import android.content.pm.ActivityInfo;
140import android.content.pm.ApplicationInfo;
141import android.content.pm.AppsQueryHelper;
142import android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManagerInternal.PackageListObserver;
173import android.content.pm.PackageParser;
174import android.content.pm.PackageParser.ActivityIntentInfo;
175import android.content.pm.PackageParser.Package;
176import android.content.pm.PackageParser.PackageLite;
177import android.content.pm.PackageParser.PackageParserException;
178import android.content.pm.PackageParser.ParseFlags;
179import android.content.pm.PackageParser.ServiceIntentInfo;
180import android.content.pm.PackageParser.SigningDetails;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.SELinuxUtil;
190import android.content.pm.ServiceInfo;
191import android.content.pm.SharedLibraryInfo;
192import android.content.pm.Signature;
193import android.content.pm.UserInfo;
194import android.content.pm.VerifierDeviceIdentity;
195import android.content.pm.VerifierInfo;
196import android.content.pm.VersionedPackage;
197import android.content.pm.dex.ArtManager;
198import android.content.pm.dex.DexMetadataHelper;
199import android.content.pm.dex.IArtManager;
200import android.content.res.Resources;
201import android.database.ContentObserver;
202import android.graphics.Bitmap;
203import android.hardware.display.DisplayManager;
204import android.net.Uri;
205import android.os.AsyncTask;
206import android.os.Binder;
207import android.os.Build;
208import android.os.Bundle;
209import android.os.Debug;
210import android.os.Environment;
211import android.os.Environment.UserEnvironment;
212import android.os.FileUtils;
213import android.os.Handler;
214import android.os.IBinder;
215import android.os.Looper;
216import android.os.Message;
217import android.os.Parcel;
218import android.os.ParcelFileDescriptor;
219import android.os.PatternMatcher;
220import android.os.PersistableBundle;
221import android.os.Process;
222import android.os.RemoteCallbackList;
223import android.os.RemoteException;
224import android.os.ResultReceiver;
225import android.os.SELinux;
226import android.os.ServiceManager;
227import android.os.ShellCallback;
228import android.os.SystemClock;
229import android.os.SystemProperties;
230import android.os.Trace;
231import android.os.UserHandle;
232import android.os.UserManager;
233import android.os.UserManagerInternal;
234import android.os.storage.IStorageManager;
235import android.os.storage.StorageEventListener;
236import android.os.storage.StorageManager;
237import android.os.storage.StorageManagerInternal;
238import android.os.storage.VolumeInfo;
239import android.os.storage.VolumeRecord;
240import android.provider.Settings.Global;
241import android.provider.Settings.Secure;
242import android.security.KeyStore;
243import android.security.SystemKeyStore;
244import android.service.pm.PackageServiceDumpProto;
245import android.system.ErrnoException;
246import android.system.Os;
247import android.text.TextUtils;
248import android.text.format.DateUtils;
249import android.util.ArrayMap;
250import android.util.ArraySet;
251import android.util.Base64;
252import android.util.ByteStringUtils;
253import android.util.DisplayMetrics;
254import android.util.EventLog;
255import android.util.ExceptionUtils;
256import android.util.Log;
257import android.util.LogPrinter;
258import android.util.LongSparseArray;
259import android.util.LongSparseLongArray;
260import android.util.MathUtils;
261import android.util.PackageUtils;
262import android.util.Pair;
263import android.util.PrintStreamPrinter;
264import android.util.Slog;
265import android.util.SparseArray;
266import android.util.SparseBooleanArray;
267import android.util.SparseIntArray;
268import android.util.TimingsTraceLog;
269import android.util.Xml;
270import android.util.jar.StrictJarFile;
271import android.util.proto.ProtoOutputStream;
272import android.view.Display;
273
274import com.android.internal.R;
275import com.android.internal.annotations.GuardedBy;
276import com.android.internal.app.IMediaContainerService;
277import com.android.internal.app.ResolverActivity;
278import com.android.internal.app.SuspendedAppActivity;
279import com.android.internal.content.NativeLibraryHelper;
280import com.android.internal.content.PackageHelper;
281import com.android.internal.logging.MetricsLogger;
282import com.android.internal.os.IParcelFileDescriptorFactory;
283import com.android.internal.os.SomeArgs;
284import com.android.internal.os.Zygote;
285import com.android.internal.telephony.CarrierAppUtils;
286import com.android.internal.util.ArrayUtils;
287import com.android.internal.util.ConcurrentUtils;
288import com.android.internal.util.DumpUtils;
289import com.android.internal.util.FastXmlSerializer;
290import com.android.internal.util.IndentingPrintWriter;
291import com.android.internal.util.Preconditions;
292import com.android.internal.util.XmlUtils;
293import com.android.server.AttributeCache;
294import com.android.server.DeviceIdleController;
295import com.android.server.EventLogTags;
296import com.android.server.FgThread;
297import com.android.server.IntentResolver;
298import com.android.server.LocalServices;
299import com.android.server.LockGuard;
300import com.android.server.ServiceThread;
301import com.android.server.SystemConfig;
302import com.android.server.SystemServerInitThreadPool;
303import com.android.server.Watchdog;
304import com.android.server.net.NetworkPolicyManagerInternal;
305import com.android.server.pm.Installer.InstallerException;
306import com.android.server.pm.Settings.DatabaseVersion;
307import com.android.server.pm.Settings.VersionInfo;
308import com.android.server.pm.dex.ArtManagerService;
309import com.android.server.pm.dex.DexLogger;
310import com.android.server.pm.dex.DexManager;
311import com.android.server.pm.dex.DexoptOptions;
312import com.android.server.pm.dex.PackageDexUsage;
313import com.android.server.pm.permission.BasePermission;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
315import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
316import com.android.server.pm.permission.PermissionManagerInternal;
317import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
318import com.android.server.pm.permission.PermissionManagerService;
319import com.android.server.pm.permission.PermissionsState;
320import com.android.server.pm.permission.PermissionsState.PermissionState;
321import com.android.server.security.VerityUtils;
322import com.android.server.storage.DeviceStorageMonitorInternal;
323
324import dalvik.system.CloseGuard;
325import dalvik.system.VMRuntime;
326
327import libcore.io.IoUtils;
328
329import org.xmlpull.v1.XmlPullParser;
330import org.xmlpull.v1.XmlPullParserException;
331import org.xmlpull.v1.XmlSerializer;
332
333import java.io.BufferedOutputStream;
334import java.io.ByteArrayInputStream;
335import java.io.ByteArrayOutputStream;
336import java.io.File;
337import java.io.FileDescriptor;
338import java.io.FileInputStream;
339import java.io.FileOutputStream;
340import java.io.FilenameFilter;
341import java.io.IOException;
342import java.io.PrintWriter;
343import java.lang.annotation.Retention;
344import java.lang.annotation.RetentionPolicy;
345import java.nio.charset.StandardCharsets;
346import java.security.DigestException;
347import java.security.DigestInputStream;
348import java.security.MessageDigest;
349import java.security.NoSuchAlgorithmException;
350import java.security.PublicKey;
351import java.security.SecureRandom;
352import java.security.cert.CertificateException;
353import java.util.ArrayList;
354import java.util.Arrays;
355import java.util.Collection;
356import java.util.Collections;
357import java.util.Comparator;
358import java.util.HashMap;
359import java.util.HashSet;
360import java.util.Iterator;
361import java.util.LinkedHashSet;
362import java.util.List;
363import java.util.Map;
364import java.util.Objects;
365import java.util.Set;
366import java.util.concurrent.CountDownLatch;
367import java.util.concurrent.Future;
368import java.util.concurrent.TimeUnit;
369import java.util.concurrent.atomic.AtomicBoolean;
370import java.util.concurrent.atomic.AtomicInteger;
371
372/**
373 * Keep track of all those APKs everywhere.
374 * <p>
375 * Internally there are two important locks:
376 * <ul>
377 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
378 * and other related state. It is a fine-grained lock that should only be held
379 * momentarily, as it's one of the most contended locks in the system.
380 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
381 * operations typically involve heavy lifting of application data on disk. Since
382 * {@code installd} is single-threaded, and it's operations can often be slow,
383 * this lock should never be acquired while already holding {@link #mPackages}.
384 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
385 * holding {@link #mInstallLock}.
386 * </ul>
387 * Many internal methods rely on the caller to hold the appropriate locks, and
388 * this contract is expressed through method name suffixes:
389 * <ul>
390 * <li>fooLI(): the caller must hold {@link #mInstallLock}
391 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
392 * being modified must be frozen
393 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
394 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
395 * </ul>
396 * <p>
397 * Because this class is very central to the platform's security; please run all
398 * CTS and unit tests whenever making modifications:
399 *
400 * <pre>
401 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
402 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
403 * </pre>
404 */
405public class PackageManagerService extends IPackageManager.Stub
406        implements PackageSender {
407    static final String TAG = "PackageManager";
408    public static final boolean DEBUG_SETTINGS = false;
409    static final boolean DEBUG_PREFERRED = false;
410    static final boolean DEBUG_UPGRADE = false;
411    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
412    private static final boolean DEBUG_BACKUP = false;
413    public static final boolean DEBUG_INSTALL = false;
414    public static final boolean DEBUG_REMOVE = true;
415    private static final boolean DEBUG_BROADCASTS = false;
416    private static final boolean DEBUG_SHOW_INFO = false;
417    private static final boolean DEBUG_PACKAGE_INFO = false;
418    private static final boolean DEBUG_INTENT_MATCHING = false;
419    public static final boolean DEBUG_PACKAGE_SCANNING = false;
420    private static final boolean DEBUG_VERIFY = false;
421    private static final boolean DEBUG_FILTERS = false;
422    public static final boolean DEBUG_PERMISSIONS = false;
423    private static final boolean DEBUG_SHARED_LIBRARIES = false;
424    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
425
426    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
427    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
428    // user, but by default initialize to this.
429    public static final boolean DEBUG_DEXOPT = false;
430
431    private static final boolean DEBUG_ABI_SELECTION = false;
432    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
433    private static final boolean DEBUG_TRIAGED_MISSING = false;
434    private static final boolean DEBUG_APP_DATA = false;
435
436    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
437    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
438
439    private static final boolean HIDE_EPHEMERAL_APIS = false;
440
441    private static final boolean ENABLE_FREE_CACHE_V2 =
442            SystemProperties.getBoolean("fw.free_cache_v2", true);
443
444    private static final int RADIO_UID = Process.PHONE_UID;
445    private static final int LOG_UID = Process.LOG_UID;
446    private static final int NFC_UID = Process.NFC_UID;
447    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
448    private static final int SHELL_UID = Process.SHELL_UID;
449    private static final int SE_UID = Process.SE_UID;
450
451    // Suffix used during package installation when copying/moving
452    // package apks to install directory.
453    private static final String INSTALL_PACKAGE_SUFFIX = "-";
454
455    static final int SCAN_NO_DEX = 1<<0;
456    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
457    static final int SCAN_NEW_INSTALL = 1<<2;
458    static final int SCAN_UPDATE_TIME = 1<<3;
459    static final int SCAN_BOOTING = 1<<4;
460    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
461    static final int SCAN_REQUIRE_KNOWN = 1<<7;
462    static final int SCAN_MOVE = 1<<8;
463    static final int SCAN_INITIAL = 1<<9;
464    static final int SCAN_CHECK_ONLY = 1<<10;
465    static final int SCAN_DONT_KILL_APP = 1<<11;
466    static final int SCAN_IGNORE_FROZEN = 1<<12;
467    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
468    static final int SCAN_AS_INSTANT_APP = 1<<14;
469    static final int SCAN_AS_FULL_APP = 1<<15;
470    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
471    static final int SCAN_AS_SYSTEM = 1<<17;
472    static final int SCAN_AS_PRIVILEGED = 1<<18;
473    static final int SCAN_AS_OEM = 1<<19;
474    static final int SCAN_AS_VENDOR = 1<<20;
475    static final int SCAN_AS_PRODUCT = 1<<21;
476
477    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
478            SCAN_NO_DEX,
479            SCAN_UPDATE_SIGNATURE,
480            SCAN_NEW_INSTALL,
481            SCAN_UPDATE_TIME,
482            SCAN_BOOTING,
483            SCAN_DELETE_DATA_ON_FAILURES,
484            SCAN_REQUIRE_KNOWN,
485            SCAN_MOVE,
486            SCAN_INITIAL,
487            SCAN_CHECK_ONLY,
488            SCAN_DONT_KILL_APP,
489            SCAN_IGNORE_FROZEN,
490            SCAN_FIRST_BOOT_OR_UPGRADE,
491            SCAN_AS_INSTANT_APP,
492            SCAN_AS_FULL_APP,
493            SCAN_AS_VIRTUAL_PRELOAD,
494    })
495    @Retention(RetentionPolicy.SOURCE)
496    public @interface ScanFlags {}
497
498    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
499    /** Extension of the compressed packages */
500    public final static String COMPRESSED_EXTENSION = ".gz";
501    /** Suffix of stub packages on the system partition */
502    public final static String STUB_SUFFIX = "-Stub";
503
504    private static final int[] EMPTY_INT_ARRAY = new int[0];
505
506    private static final int TYPE_UNKNOWN = 0;
507    private static final int TYPE_ACTIVITY = 1;
508    private static final int TYPE_RECEIVER = 2;
509    private static final int TYPE_SERVICE = 3;
510    private static final int TYPE_PROVIDER = 4;
511    @IntDef(prefix = { "TYPE_" }, value = {
512            TYPE_UNKNOWN,
513            TYPE_ACTIVITY,
514            TYPE_RECEIVER,
515            TYPE_SERVICE,
516            TYPE_PROVIDER,
517    })
518    @Retention(RetentionPolicy.SOURCE)
519    public @interface ComponentType {}
520
521    /**
522     * Timeout (in milliseconds) after which the watchdog should declare that
523     * our handler thread is wedged.  The usual default for such things is one
524     * minute but we sometimes do very lengthy I/O operations on this thread,
525     * such as installing multi-gigabyte applications, so ours needs to be longer.
526     */
527    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
528
529    /**
530     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
531     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
532     * settings entry if available, otherwise we use the hardcoded default.  If it's been
533     * more than this long since the last fstrim, we force one during the boot sequence.
534     *
535     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
536     * one gets run at the next available charging+idle time.  This final mandatory
537     * no-fstrim check kicks in only of the other scheduling criteria is never met.
538     */
539    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
540
541    /**
542     * Whether verification is enabled by default.
543     */
544    private static final boolean DEFAULT_VERIFY_ENABLE = true;
545
546    /**
547     * The default maximum time to wait for the verification agent to return in
548     * milliseconds.
549     */
550    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
551
552    /**
553     * The default response for package verification timeout.
554     *
555     * This can be either PackageManager.VERIFICATION_ALLOW or
556     * PackageManager.VERIFICATION_REJECT.
557     */
558    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
559
560    public static final String PLATFORM_PACKAGE_NAME = "android";
561
562    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
563
564    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
565            DEFAULT_CONTAINER_PACKAGE,
566            "com.android.defcontainer.DefaultContainerService");
567
568    private static final String KILL_APP_REASON_GIDS_CHANGED =
569            "permission grant or revoke changed gids";
570
571    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
572            "permissions revoked";
573
574    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
575
576    private static final String PACKAGE_SCHEME = "package";
577
578    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
579
580    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
581
582    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
583
584    /** Canonical intent used to identify what counts as a "web browser" app */
585    private static final Intent sBrowserIntent;
586    static {
587        sBrowserIntent = new Intent();
588        sBrowserIntent.setAction(Intent.ACTION_VIEW);
589        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
590        sBrowserIntent.setData(Uri.parse("http:"));
591        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
592    }
593
594    /**
595     * The set of all protected actions [i.e. those actions for which a high priority
596     * intent filter is disallowed].
597     */
598    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
599    static {
600        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
601        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
602        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
603        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
604    }
605
606    // Compilation reasons.
607    public static final int REASON_UNKNOWN = -1;
608    public static final int REASON_FIRST_BOOT = 0;
609    public static final int REASON_BOOT = 1;
610    public static final int REASON_INSTALL = 2;
611    public static final int REASON_BACKGROUND_DEXOPT = 3;
612    public static final int REASON_AB_OTA = 4;
613    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
614    public static final int REASON_SHARED = 6;
615
616    public static final int REASON_LAST = REASON_SHARED;
617
618    /**
619     * Version number for the package parser cache. Increment this whenever the format or
620     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
621     */
622    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
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    /**
642     * Messages for {@link #mHandler} that need to wait for system ready before
643     * being dispatched.
644     */
645    private ArrayList<Message> mPostSystemReadyMessages;
646
647    final int mSdkVersion = Build.VERSION.SDK_INT;
648
649    final Context mContext;
650    final boolean mFactoryTest;
651    final boolean mOnlyCore;
652    final DisplayMetrics mMetrics;
653    final int mDefParseFlags;
654    final String[] mSeparateProcesses;
655    final boolean mIsUpgrade;
656    final boolean mIsPreNUpgrade;
657    final boolean mIsPreNMR1Upgrade;
658
659    // Have we told the Activity Manager to whitelist the default container service by uid yet?
660    @GuardedBy("mPackages")
661    boolean mDefaultContainerWhitelisted = false;
662
663    @GuardedBy("mPackages")
664    private boolean mDexOptDialogShown;
665
666    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
667    // LOCK HELD.  Can be called with mInstallLock held.
668    @GuardedBy("mInstallLock")
669    final Installer mInstaller;
670
671    /** Directory where installed applications are stored */
672    private static final File sAppInstallDir =
673            new File(Environment.getDataDirectory(), "app");
674    /** Directory where installed application's 32-bit native libraries are copied. */
675    private static final File sAppLib32InstallDir =
676            new File(Environment.getDataDirectory(), "app-lib");
677    /** Directory where code and non-resource assets of forward-locked applications are stored */
678    private static final File sDrmAppPrivateInstallDir =
679            new File(Environment.getDataDirectory(), "app-private");
680
681    // ----------------------------------------------------------------
682
683    // Lock for state used when installing and doing other long running
684    // operations.  Methods that must be called with this lock held have
685    // the suffix "LI".
686    final Object mInstallLock = new Object();
687
688    // ----------------------------------------------------------------
689
690    // Keys are String (package name), values are Package.  This also serves
691    // as the lock for the global state.  Methods that must be called with
692    // this lock held have the prefix "LP".
693    @GuardedBy("mPackages")
694    final ArrayMap<String, PackageParser.Package> mPackages =
695            new ArrayMap<String, PackageParser.Package>();
696
697    final ArrayMap<String, Set<String>> mKnownCodebase =
698            new ArrayMap<String, Set<String>>();
699
700    // Keys are isolated uids and values are the uid of the application
701    // that created the isolated proccess.
702    @GuardedBy("mPackages")
703    final SparseIntArray mIsolatedOwners = new SparseIntArray();
704
705    /**
706     * Tracks new system packages [received in an OTA] that we expect to
707     * find updated user-installed versions. Keys are package name, values
708     * are package location.
709     */
710    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
711    /**
712     * Tracks high priority intent filters for protected actions. During boot, certain
713     * filter actions are protected and should never be allowed to have a high priority
714     * intent filter for them. However, there is one, and only one exception -- the
715     * setup wizard. It must be able to define a high priority intent filter for these
716     * actions to ensure there are no escapes from the wizard. We need to delay processing
717     * of these during boot as we need to look at all of the system packages in order
718     * to know which component is the setup wizard.
719     */
720    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
721    /**
722     * Whether or not processing protected filters should be deferred.
723     */
724    private boolean mDeferProtectedFilters = true;
725
726    /**
727     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
728     */
729    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
730    /**
731     * Whether or not system app permissions should be promoted from install to runtime.
732     */
733    boolean mPromoteSystemApps;
734
735    @GuardedBy("mPackages")
736    final Settings mSettings;
737
738    /**
739     * Set of package names that are currently "frozen", which means active
740     * surgery is being done on the code/data for that package. The platform
741     * will refuse to launch frozen packages to avoid race conditions.
742     *
743     * @see PackageFreezer
744     */
745    @GuardedBy("mPackages")
746    final ArraySet<String> mFrozenPackages = new ArraySet<>();
747
748    final ProtectedPackages mProtectedPackages;
749
750    @GuardedBy("mLoadedVolumes")
751    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
752
753    boolean mFirstBoot;
754
755    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
756
757    @GuardedBy("mAvailableFeatures")
758    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
759
760    private final InstantAppRegistry mInstantAppRegistry;
761
762    @GuardedBy("mPackages")
763    int mChangedPackagesSequenceNumber;
764    /**
765     * List of changed [installed, removed or updated] packages.
766     * mapping from user id -> sequence number -> package name
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
770    /**
771     * The sequence number of the last change to a package.
772     * mapping from user id -> package name -> sequence number
773     */
774    @GuardedBy("mPackages")
775    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
776
777    @GuardedBy("mPackages")
778    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
779
780    class PackageParserCallback implements PackageParser.Callback {
781        @Override public final boolean hasFeature(String feature) {
782            return PackageManagerService.this.hasSystemFeature(feature, 0);
783        }
784
785        final List<PackageParser.Package> getStaticOverlayPackages(
786                Collection<PackageParser.Package> allPackages, String targetPackageName) {
787            if ("android".equals(targetPackageName)) {
788                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
789                // native AssetManager.
790                return null;
791            }
792
793            List<PackageParser.Package> overlayPackages = null;
794            for (PackageParser.Package p : allPackages) {
795                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
796                    if (overlayPackages == null) {
797                        overlayPackages = new ArrayList<PackageParser.Package>();
798                    }
799                    overlayPackages.add(p);
800                }
801            }
802            if (overlayPackages != null) {
803                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
804                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
805                        return p1.mOverlayPriority - p2.mOverlayPriority;
806                    }
807                };
808                Collections.sort(overlayPackages, cmp);
809            }
810            return overlayPackages;
811        }
812
813        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
814                String targetPath) {
815            if (overlayPackages == null || overlayPackages.isEmpty()) {
816                return null;
817            }
818            List<String> overlayPathList = null;
819            for (PackageParser.Package overlayPackage : overlayPackages) {
820                if (targetPath == null) {
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                    continue;
826                }
827
828                try {
829                    // Creates idmaps for system to parse correctly the Android manifest of the
830                    // target package.
831                    //
832                    // OverlayManagerService will update each of them with a correct gid from its
833                    // target package app id.
834                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
835                            UserHandle.getSharedAppGid(
836                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
837                    if (overlayPathList == null) {
838                        overlayPathList = new ArrayList<String>();
839                    }
840                    overlayPathList.add(overlayPackage.baseCodePath);
841                } catch (InstallerException e) {
842                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
843                            overlayPackage.baseCodePath);
844                }
845            }
846            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
847        }
848
849        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            List<PackageParser.Package> overlayPackages;
851            synchronized (mInstallLock) {
852                synchronized (mPackages) {
853                    overlayPackages = getStaticOverlayPackages(
854                            mPackages.values(), targetPackageName);
855                }
856                // It is safe to keep overlayPackages without holding mPackages because static overlay
857                // packages can't be uninstalled or disabled.
858                return getStaticOverlayPaths(overlayPackages, targetPath);
859            }
860        }
861
862        @Override public final String[] getOverlayApks(String targetPackageName) {
863            return getStaticOverlayPaths(targetPackageName, null);
864        }
865
866        @Override public final String[] getOverlayPaths(String targetPackageName,
867                String targetPath) {
868            return getStaticOverlayPaths(targetPackageName, targetPath);
869        }
870    }
871
872    class ParallelPackageParserCallback extends PackageParserCallback {
873        List<PackageParser.Package> mOverlayPackages = null;
874
875        void findStaticOverlayPackages() {
876            synchronized (mPackages) {
877                for (PackageParser.Package p : mPackages.values()) {
878                    if (p.mOverlayIsStatic) {
879                        if (mOverlayPackages == null) {
880                            mOverlayPackages = new ArrayList<PackageParser.Package>();
881                        }
882                        mOverlayPackages.add(p);
883                    }
884                }
885            }
886        }
887
888        @Override
889        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
890            // We can trust mOverlayPackages without holding mPackages because package uninstall
891            // can't happen while running parallel parsing.
892            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
893            // because mInstallLock is held before running parallel parsing.
894            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
895            return mOverlayPackages == null ? null :
896                    getStaticOverlayPaths(
897                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
898                            targetPath);
899        }
900    }
901
902    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
903    final ParallelPackageParserCallback mParallelPackageParserCallback =
904            new ParallelPackageParserCallback();
905
906    public static final class SharedLibraryEntry {
907        public final @Nullable String path;
908        public final @Nullable String apk;
909        public final @NonNull SharedLibraryInfo info;
910
911        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
912                String declaringPackageName, long declaringPackageVersionCode) {
913            path = _path;
914            apk = _apk;
915            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
916                    declaringPackageName, declaringPackageVersionCode), null);
917        }
918    }
919
920    // Currently known shared libraries.
921    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
922    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
923            new ArrayMap<>();
924
925    // All available activities, for your resolving pleasure.
926    final ActivityIntentResolver mActivities =
927            new ActivityIntentResolver();
928
929    // All available receivers, for your resolving pleasure.
930    final ActivityIntentResolver mReceivers =
931            new ActivityIntentResolver();
932
933    // All available services, for your resolving pleasure.
934    final ServiceIntentResolver mServices = new ServiceIntentResolver();
935
936    // All available providers, for your resolving pleasure.
937    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
938
939    // Mapping from provider base names (first directory in content URI codePath)
940    // to the provider information.
941    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
942            new ArrayMap<String, PackageParser.Provider>();
943
944    // Mapping from instrumentation class names to info about them.
945    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
946            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
947
948    // Packages whose data we have transfered into another package, thus
949    // should no longer exist.
950    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
951
952    // Broadcast actions that are only available to the system.
953    @GuardedBy("mProtectedBroadcasts")
954    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
955
956    /** List of packages waiting for verification. */
957    final SparseArray<PackageVerificationState> mPendingVerification
958            = new SparseArray<PackageVerificationState>();
959
960    final PackageInstallerService mInstallerService;
961
962    final ArtManagerService mArtManagerService;
963
964    private final PackageDexOptimizer mPackageDexOptimizer;
965    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
966    // is used by other apps).
967    private final DexManager mDexManager;
968
969    private AtomicInteger mNextMoveId = new AtomicInteger();
970    private final MoveCallbacks mMoveCallbacks;
971
972    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
973
974    // Cache of users who need badging.
975    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
976
977    /** Token for keys in mPendingVerification. */
978    private int mPendingVerificationToken = 0;
979
980    volatile boolean mSystemReady;
981    volatile boolean mSafeMode;
982    volatile boolean mHasSystemUidErrors;
983    private volatile boolean mWebInstantAppsDisabled;
984
985    ApplicationInfo mAndroidApplication;
986    final ActivityInfo mResolveActivity = new ActivityInfo();
987    final ResolveInfo mResolveInfo = new ResolveInfo();
988    ComponentName mResolveComponentName;
989    PackageParser.Package mPlatformPackage;
990    ComponentName mCustomResolverComponentName;
991
992    boolean mResolverReplaced = false;
993
994    private final @Nullable ComponentName mIntentFilterVerifierComponent;
995    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
996
997    private int mIntentFilterVerificationToken = 0;
998
999    /** The service connection to the ephemeral resolver */
1000    final InstantAppResolverConnection mInstantAppResolverConnection;
1001    /** Component used to show resolver settings for Instant Apps */
1002    final ComponentName mInstantAppResolverSettingsComponent;
1003
1004    /** Activity used to install instant applications */
1005    ActivityInfo mInstantAppInstallerActivity;
1006    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1007
1008    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1009            = new SparseArray<IntentFilterVerificationState>();
1010
1011    // TODO remove this and go through mPermissonManager directly
1012    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1013    private final PermissionManagerInternal mPermissionManager;
1014
1015    // List of packages names to keep cached, even if they are uninstalled for all users
1016    private List<String> mKeepUninstalledPackages;
1017
1018    private UserManagerInternal mUserManagerInternal;
1019    private ActivityManagerInternal mActivityManagerInternal;
1020
1021    private DeviceIdleController.LocalService mDeviceIdleController;
1022
1023    private File mCacheDir;
1024
1025    private Future<?> mPrepareAppDataFuture;
1026
1027    private static class IFVerificationParams {
1028        PackageParser.Package pkg;
1029        boolean replacing;
1030        int userId;
1031        int verifierUid;
1032
1033        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1034                int _userId, int _verifierUid) {
1035            pkg = _pkg;
1036            replacing = _replacing;
1037            userId = _userId;
1038            replacing = _replacing;
1039            verifierUid = _verifierUid;
1040        }
1041    }
1042
1043    private interface IntentFilterVerifier<T extends IntentFilter> {
1044        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1045                                               T filter, String packageName);
1046        void startVerifications(int userId);
1047        void receiveVerificationResponse(int verificationId);
1048    }
1049
1050    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1051        private Context mContext;
1052        private ComponentName mIntentFilterVerifierComponent;
1053        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1054
1055        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1056            mContext = context;
1057            mIntentFilterVerifierComponent = verifierComponent;
1058        }
1059
1060        private String getDefaultScheme() {
1061            return IntentFilter.SCHEME_HTTPS;
1062        }
1063
1064        @Override
1065        public void startVerifications(int userId) {
1066            // Launch verifications requests
1067            int count = mCurrentIntentFilterVerifications.size();
1068            for (int n=0; n<count; n++) {
1069                int verificationId = mCurrentIntentFilterVerifications.get(n);
1070                final IntentFilterVerificationState ivs =
1071                        mIntentFilterVerificationStates.get(verificationId);
1072
1073                String packageName = ivs.getPackageName();
1074
1075                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1076                final int filterCount = filters.size();
1077                ArraySet<String> domainsSet = new ArraySet<>();
1078                for (int m=0; m<filterCount; m++) {
1079                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1080                    domainsSet.addAll(filter.getHostsList());
1081                }
1082                synchronized (mPackages) {
1083                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1084                            packageName, domainsSet) != null) {
1085                        scheduleWriteSettingsLocked();
1086                    }
1087                }
1088                sendVerificationRequest(verificationId, ivs);
1089            }
1090            mCurrentIntentFilterVerifications.clear();
1091        }
1092
1093        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1094            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1097                    verificationId);
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1100                    getDefaultScheme());
1101            verificationIntent.putExtra(
1102                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1103                    ivs.getHostsString());
1104            verificationIntent.putExtra(
1105                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1106                    ivs.getPackageName());
1107            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1108            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1109
1110            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1111            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1112                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1113                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1114
1115            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1116            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1117                    "Sending IntentFilter verification broadcast");
1118        }
1119
1120        public void receiveVerificationResponse(int verificationId) {
1121            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1122
1123            final boolean verified = ivs.isVerified();
1124
1125            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1126            final int count = filters.size();
1127            if (DEBUG_DOMAIN_VERIFICATION) {
1128                Slog.i(TAG, "Received verification response " + verificationId
1129                        + " for " + count + " filters, verified=" + verified);
1130            }
1131            for (int n=0; n<count; n++) {
1132                PackageParser.ActivityIntentInfo filter = filters.get(n);
1133                filter.setVerified(verified);
1134
1135                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1136                        + " verified with result:" + verified + " and hosts:"
1137                        + ivs.getHostsString());
1138            }
1139
1140            mIntentFilterVerificationStates.remove(verificationId);
1141
1142            final String packageName = ivs.getPackageName();
1143            IntentFilterVerificationInfo ivi = null;
1144
1145            synchronized (mPackages) {
1146                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1147            }
1148            if (ivi == null) {
1149                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1150                        + verificationId + " packageName:" + packageName);
1151                return;
1152            }
1153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1154                    "Updating IntentFilterVerificationInfo for package " + packageName
1155                            +" verificationId:" + verificationId);
1156
1157            synchronized (mPackages) {
1158                if (verified) {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1160                } else {
1161                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1162                }
1163                scheduleWriteSettingsLocked();
1164
1165                final int userId = ivs.getUserId();
1166                if (userId != UserHandle.USER_ALL) {
1167                    final int userStatus =
1168                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1169
1170                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1171                    boolean needUpdate = false;
1172
1173                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1174                    // already been set by the User thru the Disambiguation dialog
1175                    switch (userStatus) {
1176                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1177                            if (verified) {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1179                            } else {
1180                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1181                            }
1182                            needUpdate = true;
1183                            break;
1184
1185                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1186                            if (verified) {
1187                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1188                                needUpdate = true;
1189                            }
1190                            break;
1191
1192                        default:
1193                            // Nothing to do
1194                    }
1195
1196                    if (needUpdate) {
1197                        mSettings.updateIntentFilterVerificationStatusLPw(
1198                                packageName, updatedStatus, userId);
1199                        scheduleWritePackageRestrictionsLocked(userId);
1200                    }
1201                }
1202            }
1203        }
1204
1205        @Override
1206        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1207                    ActivityIntentInfo filter, String packageName) {
1208            if (!hasValidDomains(filter)) {
1209                return false;
1210            }
1211            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1212            if (ivs == null) {
1213                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1214                        packageName);
1215            }
1216            if (DEBUG_DOMAIN_VERIFICATION) {
1217                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1218            }
1219            ivs.addFilter(filter);
1220            return true;
1221        }
1222
1223        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1224                int userId, int verificationId, String packageName) {
1225            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1226                    verifierUid, userId, packageName);
1227            ivs.setPendingState();
1228            synchronized (mPackages) {
1229                mIntentFilterVerificationStates.append(verificationId, ivs);
1230                mCurrentIntentFilterVerifications.add(verificationId);
1231            }
1232            return ivs;
1233        }
1234    }
1235
1236    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1237        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1238                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1239                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1240    }
1241
1242    // Set of pending broadcasts for aggregating enable/disable of components.
1243    static class PendingPackageBroadcasts {
1244        // for each user id, a map of <package name -> components within that package>
1245        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1246
1247        public PendingPackageBroadcasts() {
1248            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1249        }
1250
1251        public ArrayList<String> get(int userId, String packageName) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            return packages.get(packageName);
1254        }
1255
1256        public void put(int userId, String packageName, ArrayList<String> components) {
1257            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1258            packages.put(packageName, components);
1259        }
1260
1261        public void remove(int userId, String packageName) {
1262            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1263            if (packages != null) {
1264                packages.remove(packageName);
1265            }
1266        }
1267
1268        public void remove(int userId) {
1269            mUidMap.remove(userId);
1270        }
1271
1272        public int userIdCount() {
1273            return mUidMap.size();
1274        }
1275
1276        public int userIdAt(int n) {
1277            return mUidMap.keyAt(n);
1278        }
1279
1280        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1281            return mUidMap.get(userId);
1282        }
1283
1284        public int size() {
1285            // total number of pending broadcast entries across all userIds
1286            int num = 0;
1287            for (int i = 0; i< mUidMap.size(); i++) {
1288                num += mUidMap.valueAt(i).size();
1289            }
1290            return num;
1291        }
1292
1293        public void clear() {
1294            mUidMap.clear();
1295        }
1296
1297        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1298            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1299            if (map == null) {
1300                map = new ArrayMap<String, ArrayList<String>>();
1301                mUidMap.put(userId, map);
1302            }
1303            return map;
1304        }
1305    }
1306    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1307
1308    // Service Connection to remote media container service to copy
1309    // package uri's from external media onto secure containers
1310    // or internal storage.
1311    private IMediaContainerService mContainerService = null;
1312
1313    static final int SEND_PENDING_BROADCAST = 1;
1314    static final int MCS_BOUND = 3;
1315    static final int END_COPY = 4;
1316    static final int INIT_COPY = 5;
1317    static final int MCS_UNBIND = 6;
1318    static final int START_CLEANING_PACKAGE = 7;
1319    static final int FIND_INSTALL_LOC = 8;
1320    static final int POST_INSTALL = 9;
1321    static final int MCS_RECONNECT = 10;
1322    static final int MCS_GIVE_UP = 11;
1323    static final int WRITE_SETTINGS = 13;
1324    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1325    static final int PACKAGE_VERIFIED = 15;
1326    static final int CHECK_PENDING_VERIFICATION = 16;
1327    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1328    static final int INTENT_FILTER_VERIFIED = 18;
1329    static final int WRITE_PACKAGE_LIST = 19;
1330    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1331    static final int DEF_CONTAINER_BIND = 21;
1332
1333    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1334
1335    // Delay time in millisecs
1336    static final int BROADCAST_DELAY = 10 * 1000;
1337
1338    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1339            2 * 60 * 60 * 1000L; /* two hours */
1340
1341    static UserManagerService sUserManager;
1342
1343    // Stores a list of users whose package restrictions file needs to be updated
1344    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1345
1346    final private DefaultContainerConnection mDefContainerConn =
1347            new DefaultContainerConnection();
1348    class DefaultContainerConnection implements ServiceConnection {
1349        public void onServiceConnected(ComponentName name, IBinder service) {
1350            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1351            final IMediaContainerService imcs = IMediaContainerService.Stub
1352                    .asInterface(Binder.allowBlocking(service));
1353            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1354        }
1355
1356        public void onServiceDisconnected(ComponentName name) {
1357            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1358        }
1359    }
1360
1361    // Recordkeeping of restore-after-install operations that are currently in flight
1362    // between the Package Manager and the Backup Manager
1363    static class PostInstallData {
1364        public InstallArgs args;
1365        public PackageInstalledInfo res;
1366
1367        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1368            args = _a;
1369            res = _r;
1370        }
1371    }
1372
1373    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1374    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1375
1376    // XML tags for backup/restore of various bits of state
1377    private static final String TAG_PREFERRED_BACKUP = "pa";
1378    private static final String TAG_DEFAULT_APPS = "da";
1379    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1380
1381    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1382    private static final String TAG_ALL_GRANTS = "rt-grants";
1383    private static final String TAG_GRANT = "grant";
1384    private static final String ATTR_PACKAGE_NAME = "pkg";
1385
1386    private static final String TAG_PERMISSION = "perm";
1387    private static final String ATTR_PERMISSION_NAME = "name";
1388    private static final String ATTR_IS_GRANTED = "g";
1389    private static final String ATTR_USER_SET = "set";
1390    private static final String ATTR_USER_FIXED = "fixed";
1391    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1392
1393    // System/policy permission grants are not backed up
1394    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_POLICY_FIXED
1396            | FLAG_PERMISSION_SYSTEM_FIXED
1397            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1398
1399    // And we back up these user-adjusted states
1400    private static final int USER_RUNTIME_GRANT_MASK =
1401            FLAG_PERMISSION_USER_SET
1402            | FLAG_PERMISSION_USER_FIXED
1403            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1404
1405    final @Nullable String mRequiredVerifierPackage;
1406    final @NonNull String mRequiredInstallerPackage;
1407    final @NonNull String mRequiredUninstallerPackage;
1408    final @Nullable String mSetupWizardPackage;
1409    final @Nullable String mStorageManagerPackage;
1410    final @Nullable String mSystemTextClassifierPackage;
1411    final @NonNull String mServicesSystemSharedLibraryPackageName;
1412    final @NonNull String mSharedSystemSharedLibraryPackageName;
1413
1414    private final PackageUsage mPackageUsage = new PackageUsage();
1415    private final CompilerStats mCompilerStats = new CompilerStats();
1416
1417    class PackageHandler extends Handler {
1418        private boolean mBound = false;
1419        final ArrayList<HandlerParams> mPendingInstalls =
1420            new ArrayList<HandlerParams>();
1421
1422        private boolean connectToService() {
1423            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1424            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1426            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1427                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1428                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429                mBound = true;
1430                return true;
1431            }
1432            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            return false;
1434        }
1435
1436        private void disconnectService() {
1437            mContainerService = null;
1438            mBound = false;
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1440            mContext.unbindService(mDefContainerConn);
1441            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1442        }
1443
1444        PackageHandler(Looper looper) {
1445            super(looper);
1446        }
1447
1448        public void handleMessage(Message msg) {
1449            try {
1450                doHandleMessage(msg);
1451            } finally {
1452                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1453            }
1454        }
1455
1456        void doHandleMessage(Message msg) {
1457            switch (msg.what) {
1458                case DEF_CONTAINER_BIND:
1459                    if (!mBound) {
1460                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1461                                System.identityHashCode(mHandler));
1462                        if (!connectToService()) {
1463                            Slog.e(TAG, "Failed to bind to media container service");
1464                        }
1465                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1466                                System.identityHashCode(mHandler));
1467                    }
1468                    break;
1469                case INIT_COPY: {
1470                    HandlerParams params = (HandlerParams) msg.obj;
1471                    int idx = mPendingInstalls.size();
1472                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1473                    // If a bind was already initiated we dont really
1474                    // need to do anything. The pending install
1475                    // will be processed later on.
1476                    if (!mBound) {
1477                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1478                                System.identityHashCode(mHandler));
1479                        // If this is the only one pending we might
1480                        // have to bind to the service again.
1481                        if (!connectToService()) {
1482                            Slog.e(TAG, "Failed to bind to media container service");
1483                            params.serviceError();
1484                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1485                                    System.identityHashCode(mHandler));
1486                            if (params.traceMethod != null) {
1487                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1488                                        params.traceCookie);
1489                            }
1490                            return;
1491                        } else {
1492                            // Once we bind to the service, the first
1493                            // pending request will be processed.
1494                            mPendingInstalls.add(idx, params);
1495                        }
1496                    } else {
1497                        mPendingInstalls.add(idx, params);
1498                        // Already bound to the service. Just make
1499                        // sure we trigger off processing the first request.
1500                        if (idx == 0) {
1501                            mHandler.sendEmptyMessage(MCS_BOUND);
1502                        }
1503                    }
1504                    break;
1505                }
1506                case MCS_BOUND: {
1507                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1508                    if (msg.obj != null) {
1509                        mContainerService = (IMediaContainerService) msg.obj;
1510                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1511                                System.identityHashCode(mHandler));
1512                    }
1513                    if (mContainerService == null) {
1514                        if (!mBound) {
1515                            // Something seriously wrong since we are not bound and we are not
1516                            // waiting for connection. Bail out.
1517                            Slog.e(TAG, "Cannot bind to media container service");
1518                            for (HandlerParams params : mPendingInstalls) {
1519                                // Indicate service bind error
1520                                params.serviceError();
1521                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                                        System.identityHashCode(params));
1523                                if (params.traceMethod != null) {
1524                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1525                                            params.traceMethod, params.traceCookie);
1526                                }
1527                            }
1528                            mPendingInstalls.clear();
1529                        } else {
1530                            Slog.w(TAG, "Waiting to connect to media container service");
1531                        }
1532                    } else if (mPendingInstalls.size() > 0) {
1533                        HandlerParams params = mPendingInstalls.get(0);
1534                        if (params != null) {
1535                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1536                                    System.identityHashCode(params));
1537                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1538                            if (params.startCopy()) {
1539                                // We are done...  look for more work or to
1540                                // go idle.
1541                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                        "Checking for more work or unbind...");
1543                                // Delete pending install
1544                                if (mPendingInstalls.size() > 0) {
1545                                    mPendingInstalls.remove(0);
1546                                }
1547                                if (mPendingInstalls.size() == 0) {
1548                                    if (mBound) {
1549                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1550                                                "Posting delayed MCS_UNBIND");
1551                                        removeMessages(MCS_UNBIND);
1552                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1553                                        // Unbind after a little delay, to avoid
1554                                        // continual thrashing.
1555                                        sendMessageDelayed(ubmsg, 10000);
1556                                    }
1557                                } else {
1558                                    // There are more pending requests in queue.
1559                                    // Just post MCS_BOUND message to trigger processing
1560                                    // of next pending install.
1561                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1562                                            "Posting MCS_BOUND for next work");
1563                                    mHandler.sendEmptyMessage(MCS_BOUND);
1564                                }
1565                            }
1566                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1567                        }
1568                    } else {
1569                        // Should never happen ideally.
1570                        Slog.w(TAG, "Empty queue");
1571                    }
1572                    break;
1573                }
1574                case MCS_RECONNECT: {
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1576                    if (mPendingInstalls.size() > 0) {
1577                        if (mBound) {
1578                            disconnectService();
1579                        }
1580                        if (!connectToService()) {
1581                            Slog.e(TAG, "Failed to bind to media container service");
1582                            for (HandlerParams params : mPendingInstalls) {
1583                                // Indicate service bind error
1584                                params.serviceError();
1585                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                                        System.identityHashCode(params));
1587                            }
1588                            mPendingInstalls.clear();
1589                        }
1590                    }
1591                    break;
1592                }
1593                case MCS_UNBIND: {
1594                    // If there is no actual work left, then time to unbind.
1595                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1596
1597                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1598                        if (mBound) {
1599                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1600
1601                            disconnectService();
1602                        }
1603                    } else if (mPendingInstalls.size() > 0) {
1604                        // There are more pending requests in queue.
1605                        // Just post MCS_BOUND message to trigger processing
1606                        // of next pending install.
1607                        mHandler.sendEmptyMessage(MCS_BOUND);
1608                    }
1609
1610                    break;
1611                }
1612                case MCS_GIVE_UP: {
1613                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1614                    HandlerParams params = mPendingInstalls.remove(0);
1615                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1616                            System.identityHashCode(params));
1617                    break;
1618                }
1619                case SEND_PENDING_BROADCAST: {
1620                    String packages[];
1621                    ArrayList<String> components[];
1622                    int size = 0;
1623                    int uids[];
1624                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1625                    synchronized (mPackages) {
1626                        if (mPendingBroadcasts == null) {
1627                            return;
1628                        }
1629                        size = mPendingBroadcasts.size();
1630                        if (size <= 0) {
1631                            // Nothing to be done. Just return
1632                            return;
1633                        }
1634                        packages = new String[size];
1635                        components = new ArrayList[size];
1636                        uids = new int[size];
1637                        int i = 0;  // filling out the above arrays
1638
1639                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1640                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1641                            Iterator<Map.Entry<String, ArrayList<String>>> it
1642                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1643                                            .entrySet().iterator();
1644                            while (it.hasNext() && i < size) {
1645                                Map.Entry<String, ArrayList<String>> ent = it.next();
1646                                packages[i] = ent.getKey();
1647                                components[i] = ent.getValue();
1648                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1649                                uids[i] = (ps != null)
1650                                        ? UserHandle.getUid(packageUserId, ps.appId)
1651                                        : -1;
1652                                i++;
1653                            }
1654                        }
1655                        size = i;
1656                        mPendingBroadcasts.clear();
1657                    }
1658                    // Send broadcasts
1659                    for (int i = 0; i < size; i++) {
1660                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    break;
1664                }
1665                case START_CLEANING_PACKAGE: {
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1667                    final String packageName = (String)msg.obj;
1668                    final int userId = msg.arg1;
1669                    final boolean andCode = msg.arg2 != 0;
1670                    synchronized (mPackages) {
1671                        if (userId == UserHandle.USER_ALL) {
1672                            int[] users = sUserManager.getUserIds();
1673                            for (int user : users) {
1674                                mSettings.addPackageToCleanLPw(
1675                                        new PackageCleanItem(user, packageName, andCode));
1676                            }
1677                        } else {
1678                            mSettings.addPackageToCleanLPw(
1679                                    new PackageCleanItem(userId, packageName, andCode));
1680                        }
1681                    }
1682                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1683                    startCleaningPackages();
1684                } break;
1685                case POST_INSTALL: {
1686                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1687
1688                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1689                    final boolean didRestore = (msg.arg2 != 0);
1690                    mRunningInstalls.delete(msg.arg1);
1691
1692                    if (data != null) {
1693                        InstallArgs args = data.args;
1694                        PackageInstalledInfo parentRes = data.res;
1695
1696                        final boolean grantPermissions = (args.installFlags
1697                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1698                        final boolean killApp = (args.installFlags
1699                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1700                        final boolean virtualPreload = ((args.installFlags
1701                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1702                        final String[] grantedPermissions = args.installGrantPermissions;
1703
1704                        // Handle the parent package
1705                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1706                                virtualPreload, grantedPermissions, didRestore,
1707                                args.installerPackageName, args.observer);
1708
1709                        // Handle the child packages
1710                        final int childCount = (parentRes.addedChildPackages != null)
1711                                ? parentRes.addedChildPackages.size() : 0;
1712                        for (int i = 0; i < childCount; i++) {
1713                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1714                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1715                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1716                                    args.installerPackageName, args.observer);
1717                        }
1718
1719                        // Log tracing if needed
1720                        if (args.traceMethod != null) {
1721                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1722                                    args.traceCookie);
1723                        }
1724                    } else {
1725                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1726                    }
1727
1728                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1729                } break;
1730                case WRITE_SETTINGS: {
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1732                    synchronized (mPackages) {
1733                        removeMessages(WRITE_SETTINGS);
1734                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1735                        mSettings.writeLPr();
1736                        mDirtyUsers.clear();
1737                    }
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739                } break;
1740                case WRITE_PACKAGE_RESTRICTIONS: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1744                        for (int userId : mDirtyUsers) {
1745                            mSettings.writePackageRestrictionsLPr(userId);
1746                        }
1747                        mDirtyUsers.clear();
1748                    }
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1750                } break;
1751                case WRITE_PACKAGE_LIST: {
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1753                    synchronized (mPackages) {
1754                        removeMessages(WRITE_PACKAGE_LIST);
1755                        mSettings.writePackageListLPr(msg.arg1);
1756                    }
1757                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1758                } break;
1759                case CHECK_PENDING_VERIFICATION: {
1760                    final int verificationId = msg.arg1;
1761                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1762
1763                    if ((state != null) && !state.timeoutExtended()) {
1764                        final InstallArgs args = state.getInstallArgs();
1765                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1766
1767                        Slog.i(TAG, "Verification timed out for " + originUri);
1768                        mPendingVerification.remove(verificationId);
1769
1770                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1771
1772                        final UserHandle user = args.getUser();
1773                        if (getDefaultVerificationResponse(user)
1774                                == PackageManager.VERIFICATION_ALLOW) {
1775                            Slog.i(TAG, "Continuing with installation of " + originUri);
1776                            state.setVerifierResponse(Binder.getCallingUid(),
1777                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1778                            broadcastPackageVerified(verificationId, originUri,
1779                                    PackageManager.VERIFICATION_ALLOW, user);
1780                            try {
1781                                ret = args.copyApk(mContainerService, true);
1782                            } catch (RemoteException e) {
1783                                Slog.e(TAG, "Could not contact the ContainerService");
1784                            }
1785                        } else {
1786                            broadcastPackageVerified(verificationId, originUri,
1787                                    PackageManager.VERIFICATION_REJECT, user);
1788                        }
1789
1790                        Trace.asyncTraceEnd(
1791                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1792
1793                        processPendingInstall(args, ret);
1794                        mHandler.sendEmptyMessage(MCS_UNBIND);
1795                    }
1796                    break;
1797                }
1798                case PACKAGE_VERIFIED: {
1799                    final int verificationId = msg.arg1;
1800
1801                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1802                    if (state == null) {
1803                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1804                        break;
1805                    }
1806
1807                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1808
1809                    state.setVerifierResponse(response.callerUid, response.code);
1810
1811                    if (state.isVerificationComplete()) {
1812                        mPendingVerification.remove(verificationId);
1813
1814                        final InstallArgs args = state.getInstallArgs();
1815                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1816
1817                        int ret;
1818                        if (state.isInstallAllowed()) {
1819                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1820                            broadcastPackageVerified(verificationId, originUri,
1821                                    response.code, state.getInstallArgs().getUser());
1822                            try {
1823                                ret = args.copyApk(mContainerService, true);
1824                            } catch (RemoteException e) {
1825                                Slog.e(TAG, "Could not contact the ContainerService");
1826                            }
1827                        } else {
1828                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1829                        }
1830
1831                        Trace.asyncTraceEnd(
1832                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1833
1834                        processPendingInstall(args, ret);
1835                        mHandler.sendEmptyMessage(MCS_UNBIND);
1836                    }
1837
1838                    break;
1839                }
1840                case START_INTENT_FILTER_VERIFICATIONS: {
1841                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1842                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1843                            params.replacing, params.pkg);
1844                    break;
1845                }
1846                case INTENT_FILTER_VERIFIED: {
1847                    final int verificationId = msg.arg1;
1848
1849                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1850                            verificationId);
1851                    if (state == null) {
1852                        Slog.w(TAG, "Invalid IntentFilter verification token "
1853                                + verificationId + " received");
1854                        break;
1855                    }
1856
1857                    final int userId = state.getUserId();
1858
1859                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1860                            "Processing IntentFilter verification with token:"
1861                            + verificationId + " and userId:" + userId);
1862
1863                    final IntentFilterVerificationResponse response =
1864                            (IntentFilterVerificationResponse) msg.obj;
1865
1866                    state.setVerifierResponse(response.callerUid, response.code);
1867
1868                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1869                            "IntentFilter verification with token:" + verificationId
1870                            + " and userId:" + userId
1871                            + " is settings verifier response with response code:"
1872                            + response.code);
1873
1874                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1875                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1876                                + response.getFailedDomainsString());
1877                    }
1878
1879                    if (state.isVerificationComplete()) {
1880                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1881                    } else {
1882                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1883                                "IntentFilter verification with token:" + verificationId
1884                                + " was not said to be complete");
1885                    }
1886
1887                    break;
1888                }
1889                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1890                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1891                            mInstantAppResolverConnection,
1892                            (InstantAppRequest) msg.obj,
1893                            mInstantAppInstallerActivity,
1894                            mHandler);
1895                }
1896            }
1897        }
1898    }
1899
1900    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1901        @Override
1902        public void onGidsChanged(int appId, int userId) {
1903            mHandler.post(new Runnable() {
1904                @Override
1905                public void run() {
1906                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1907                }
1908            });
1909        }
1910        @Override
1911        public void onPermissionGranted(int uid, int userId) {
1912            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1913
1914            // Not critical; if this is lost, the application has to request again.
1915            synchronized (mPackages) {
1916                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1917            }
1918        }
1919        @Override
1920        public void onInstallPermissionGranted() {
1921            synchronized (mPackages) {
1922                scheduleWriteSettingsLocked();
1923            }
1924        }
1925        @Override
1926        public void onPermissionRevoked(int uid, int userId) {
1927            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1928
1929            synchronized (mPackages) {
1930                // Critical; after this call the application should never have the permission
1931                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1932            }
1933
1934            final int appId = UserHandle.getAppId(uid);
1935            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1936        }
1937        @Override
1938        public void onInstallPermissionRevoked() {
1939            synchronized (mPackages) {
1940                scheduleWriteSettingsLocked();
1941            }
1942        }
1943        @Override
1944        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1945            synchronized (mPackages) {
1946                for (int userId : updatedUserIds) {
1947                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1948                }
1949            }
1950        }
1951        @Override
1952        public void onInstallPermissionUpdated() {
1953            synchronized (mPackages) {
1954                scheduleWriteSettingsLocked();
1955            }
1956        }
1957        @Override
1958        public void onPermissionRemoved() {
1959            synchronized (mPackages) {
1960                mSettings.writeLPr();
1961            }
1962        }
1963    };
1964
1965    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1966            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1967            boolean launchedForRestore, String installerPackage,
1968            IPackageInstallObserver2 installObserver) {
1969        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1970            // Send the removed broadcasts
1971            if (res.removedInfo != null) {
1972                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1973            }
1974
1975            // Now that we successfully installed the package, grant runtime
1976            // permissions if requested before broadcasting the install. Also
1977            // for legacy apps in permission review mode we clear the permission
1978            // review flag which is used to emulate runtime permissions for
1979            // legacy apps.
1980            if (grantPermissions) {
1981                final int callingUid = Binder.getCallingUid();
1982                mPermissionManager.grantRequestedRuntimePermissions(
1983                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1984                        mPermissionCallback);
1985            }
1986
1987            final boolean update = res.removedInfo != null
1988                    && res.removedInfo.removedPackage != null;
1989            final String installerPackageName =
1990                    res.installerPackageName != null
1991                            ? res.installerPackageName
1992                            : res.removedInfo != null
1993                                    ? res.removedInfo.installerPackageName
1994                                    : null;
1995
1996            // If this is the first time we have child packages for a disabled privileged
1997            // app that had no children, we grant requested runtime permissions to the new
1998            // children if the parent on the system image had them already granted.
1999            if (res.pkg.parentPackage != null) {
2000                final int callingUid = Binder.getCallingUid();
2001                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2002                        res.pkg, callingUid, mPermissionCallback);
2003            }
2004
2005            synchronized (mPackages) {
2006                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2007            }
2008
2009            final String packageName = res.pkg.applicationInfo.packageName;
2010
2011            // Determine the set of users who are adding this package for
2012            // the first time vs. those who are seeing an update.
2013            int[] firstUserIds = EMPTY_INT_ARRAY;
2014            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2015            int[] updateUserIds = EMPTY_INT_ARRAY;
2016            int[] instantUserIds = EMPTY_INT_ARRAY;
2017            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2018            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2019            for (int newUser : res.newUsers) {
2020                final boolean isInstantApp = ps.getInstantApp(newUser);
2021                if (allNewUsers) {
2022                    if (isInstantApp) {
2023                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2024                    } else {
2025                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2026                    }
2027                    continue;
2028                }
2029                boolean isNew = true;
2030                for (int origUser : res.origUsers) {
2031                    if (origUser == newUser) {
2032                        isNew = false;
2033                        break;
2034                    }
2035                }
2036                if (isNew) {
2037                    if (isInstantApp) {
2038                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2039                    } else {
2040                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2041                    }
2042                } else {
2043                    if (isInstantApp) {
2044                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2045                    } else {
2046                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2047                    }
2048                }
2049            }
2050
2051            // Send installed broadcasts if the package is not a static shared lib.
2052            if (res.pkg.staticSharedLibName == null) {
2053                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2054
2055                // Send added for users that see the package for the first time
2056                // sendPackageAddedForNewUsers also deals with system apps
2057                int appId = UserHandle.getAppId(res.uid);
2058                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2059                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2060                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2061
2062                // Send added for users that don't see the package for the first time
2063                Bundle extras = new Bundle(1);
2064                extras.putInt(Intent.EXTRA_UID, res.uid);
2065                if (update) {
2066                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2067                }
2068                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2069                        extras, 0 /*flags*/,
2070                        null /*targetPackage*/, null /*finishedReceiver*/,
2071                        updateUserIds, instantUserIds);
2072                if (installerPackageName != null) {
2073                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2074                            extras, 0 /*flags*/,
2075                            installerPackageName, null /*finishedReceiver*/,
2076                            updateUserIds, instantUserIds);
2077                }
2078
2079                // Send replaced for users that don't see the package for the first time
2080                if (update) {
2081                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2082                            packageName, extras, 0 /*flags*/,
2083                            null /*targetPackage*/, null /*finishedReceiver*/,
2084                            updateUserIds, instantUserIds);
2085                    if (installerPackageName != null) {
2086                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2087                                extras, 0 /*flags*/,
2088                                installerPackageName, null /*finishedReceiver*/,
2089                                updateUserIds, instantUserIds);
2090                    }
2091                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2092                            null /*package*/, null /*extras*/, 0 /*flags*/,
2093                            packageName /*targetPackage*/,
2094                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2095                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2096                    // First-install and we did a restore, so we're responsible for the
2097                    // first-launch broadcast.
2098                    if (DEBUG_BACKUP) {
2099                        Slog.i(TAG, "Post-restore of " + packageName
2100                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2101                    }
2102                    sendFirstLaunchBroadcast(packageName, installerPackage,
2103                            firstUserIds, firstInstantUserIds);
2104                }
2105
2106                // Send broadcast package appeared if forward locked/external for all users
2107                // treat asec-hosted packages like removable media on upgrade
2108                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2109                    if (DEBUG_INSTALL) {
2110                        Slog.i(TAG, "upgrading pkg " + res.pkg
2111                                + " is ASEC-hosted -> AVAILABLE");
2112                    }
2113                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2114                    ArrayList<String> pkgList = new ArrayList<>(1);
2115                    pkgList.add(packageName);
2116                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2117                }
2118            }
2119
2120            // Work that needs to happen on first install within each user
2121            if (firstUserIds != null && firstUserIds.length > 0) {
2122                synchronized (mPackages) {
2123                    for (int userId : firstUserIds) {
2124                        // If this app is a browser and it's newly-installed for some
2125                        // users, clear any default-browser state in those users. The
2126                        // app's nature doesn't depend on the user, so we can just check
2127                        // its browser nature in any user and generalize.
2128                        if (packageIsBrowser(packageName, userId)) {
2129                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2130                        }
2131
2132                        // We may also need to apply pending (restored) runtime
2133                        // permission grants within these users.
2134                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2135                    }
2136                }
2137            }
2138
2139            if (allNewUsers && !update) {
2140                notifyPackageAdded(packageName);
2141            }
2142
2143            // Log current value of "unknown sources" setting
2144            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2145                    getUnknownSourcesSettings());
2146
2147            // Remove the replaced package's older resources safely now
2148            // We delete after a gc for applications  on sdcard.
2149            if (res.removedInfo != null && res.removedInfo.args != null) {
2150                Runtime.getRuntime().gc();
2151                synchronized (mInstallLock) {
2152                    res.removedInfo.args.doPostDeleteLI(true);
2153                }
2154            } else {
2155                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2156                // and not block here.
2157                VMRuntime.getRuntime().requestConcurrentGC();
2158            }
2159
2160            // Notify DexManager that the package was installed for new users.
2161            // The updated users should already be indexed and the package code paths
2162            // should not change.
2163            // Don't notify the manager for ephemeral apps as they are not expected to
2164            // survive long enough to benefit of background optimizations.
2165            for (int userId : firstUserIds) {
2166                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2167                // There's a race currently where some install events may interleave with an uninstall.
2168                // This can lead to package info being null (b/36642664).
2169                if (info != null) {
2170                    mDexManager.notifyPackageInstalled(info, userId);
2171                }
2172            }
2173        }
2174
2175        // If someone is watching installs - notify them
2176        if (installObserver != null) {
2177            try {
2178                Bundle extras = extrasForInstallResult(res);
2179                installObserver.onPackageInstalled(res.name, res.returnCode,
2180                        res.returnMsg, extras);
2181            } catch (RemoteException e) {
2182                Slog.i(TAG, "Observer no longer exists.");
2183            }
2184        }
2185    }
2186
2187    private StorageEventListener mStorageListener = new StorageEventListener() {
2188        @Override
2189        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2190            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2191                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2192                    final String volumeUuid = vol.getFsUuid();
2193
2194                    // Clean up any users or apps that were removed or recreated
2195                    // while this volume was missing
2196                    sUserManager.reconcileUsers(volumeUuid);
2197                    reconcileApps(volumeUuid);
2198
2199                    // Clean up any install sessions that expired or were
2200                    // cancelled while this volume was missing
2201                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2202
2203                    loadPrivatePackages(vol);
2204
2205                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2206                    unloadPrivatePackages(vol);
2207                }
2208            }
2209        }
2210
2211        @Override
2212        public void onVolumeForgotten(String fsUuid) {
2213            if (TextUtils.isEmpty(fsUuid)) {
2214                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2215                return;
2216            }
2217
2218            // Remove any apps installed on the forgotten volume
2219            synchronized (mPackages) {
2220                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2221                for (PackageSetting ps : packages) {
2222                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2223                    deletePackageVersioned(new VersionedPackage(ps.name,
2224                            PackageManager.VERSION_CODE_HIGHEST),
2225                            new LegacyPackageDeleteObserver(null).getBinder(),
2226                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2227                    // Try very hard to release any references to this package
2228                    // so we don't risk the system server being killed due to
2229                    // open FDs
2230                    AttributeCache.instance().removePackage(ps.name);
2231                }
2232
2233                mSettings.onVolumeForgotten(fsUuid);
2234                mSettings.writeLPr();
2235            }
2236        }
2237    };
2238
2239    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2240        Bundle extras = null;
2241        switch (res.returnCode) {
2242            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2243                extras = new Bundle();
2244                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2245                        res.origPermission);
2246                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2247                        res.origPackage);
2248                break;
2249            }
2250            case PackageManager.INSTALL_SUCCEEDED: {
2251                extras = new Bundle();
2252                extras.putBoolean(Intent.EXTRA_REPLACING,
2253                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2254                break;
2255            }
2256        }
2257        return extras;
2258    }
2259
2260    void scheduleWriteSettingsLocked() {
2261        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2262            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2263        }
2264    }
2265
2266    void scheduleWritePackageListLocked(int userId) {
2267        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2268            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2269            msg.arg1 = userId;
2270            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2271        }
2272    }
2273
2274    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2275        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2276        scheduleWritePackageRestrictionsLocked(userId);
2277    }
2278
2279    void scheduleWritePackageRestrictionsLocked(int userId) {
2280        final int[] userIds = (userId == UserHandle.USER_ALL)
2281                ? sUserManager.getUserIds() : new int[]{userId};
2282        for (int nextUserId : userIds) {
2283            if (!sUserManager.exists(nextUserId)) return;
2284            mDirtyUsers.add(nextUserId);
2285            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2286                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2287            }
2288        }
2289    }
2290
2291    public static PackageManagerService main(Context context, Installer installer,
2292            boolean factoryTest, boolean onlyCore) {
2293        // Self-check for initial settings.
2294        PackageManagerServiceCompilerMapping.checkProperties();
2295
2296        PackageManagerService m = new PackageManagerService(context, installer,
2297                factoryTest, onlyCore);
2298        m.enableSystemUserPackages();
2299        ServiceManager.addService("package", m);
2300        final PackageManagerNative pmn = m.new PackageManagerNative();
2301        ServiceManager.addService("package_native", pmn);
2302        return m;
2303    }
2304
2305    private void enableSystemUserPackages() {
2306        if (!UserManager.isSplitSystemUser()) {
2307            return;
2308        }
2309        // For system user, enable apps based on the following conditions:
2310        // - app is whitelisted or belong to one of these groups:
2311        //   -- system app which has no launcher icons
2312        //   -- system app which has INTERACT_ACROSS_USERS permission
2313        //   -- system IME app
2314        // - app is not in the blacklist
2315        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2316        Set<String> enableApps = new ArraySet<>();
2317        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2318                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2319                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2320        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2321        enableApps.addAll(wlApps);
2322        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2323                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2324        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2325        enableApps.removeAll(blApps);
2326        Log.i(TAG, "Applications installed for system user: " + enableApps);
2327        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2328                UserHandle.SYSTEM);
2329        final int allAppsSize = allAps.size();
2330        synchronized (mPackages) {
2331            for (int i = 0; i < allAppsSize; i++) {
2332                String pName = allAps.get(i);
2333                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2334                // Should not happen, but we shouldn't be failing if it does
2335                if (pkgSetting == null) {
2336                    continue;
2337                }
2338                boolean install = enableApps.contains(pName);
2339                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2340                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2341                            + " for system user");
2342                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2343                }
2344            }
2345            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2346        }
2347    }
2348
2349    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2350        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2351                Context.DISPLAY_SERVICE);
2352        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2353    }
2354
2355    /**
2356     * Requests that files preopted on a secondary system partition be copied to the data partition
2357     * if possible.  Note that the actual copying of the files is accomplished by init for security
2358     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2359     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2360     */
2361    private static void requestCopyPreoptedFiles() {
2362        final int WAIT_TIME_MS = 100;
2363        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2364        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2365            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2366            // We will wait for up to 100 seconds.
2367            final long timeStart = SystemClock.uptimeMillis();
2368            final long timeEnd = timeStart + 100 * 1000;
2369            long timeNow = timeStart;
2370            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2371                try {
2372                    Thread.sleep(WAIT_TIME_MS);
2373                } catch (InterruptedException e) {
2374                    // Do nothing
2375                }
2376                timeNow = SystemClock.uptimeMillis();
2377                if (timeNow > timeEnd) {
2378                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2379                    Slog.wtf(TAG, "cppreopt did not finish!");
2380                    break;
2381                }
2382            }
2383
2384            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2385        }
2386    }
2387
2388    public PackageManagerService(Context context, Installer installer,
2389            boolean factoryTest, boolean onlyCore) {
2390        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2391        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2392        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2393                SystemClock.uptimeMillis());
2394
2395        if (mSdkVersion <= 0) {
2396            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2397        }
2398
2399        mContext = context;
2400
2401        mFactoryTest = factoryTest;
2402        mOnlyCore = onlyCore;
2403        mMetrics = new DisplayMetrics();
2404        mInstaller = installer;
2405
2406        // Create sub-components that provide services / data. Order here is important.
2407        synchronized (mInstallLock) {
2408        synchronized (mPackages) {
2409            // Expose private service for system components to use.
2410            LocalServices.addService(
2411                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2412            sUserManager = new UserManagerService(context, this,
2413                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2414            mPermissionManager = PermissionManagerService.create(context,
2415                    new DefaultPermissionGrantedCallback() {
2416                        @Override
2417                        public void onDefaultRuntimePermissionsGranted(int userId) {
2418                            synchronized(mPackages) {
2419                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2420                            }
2421                        }
2422                    }, mPackages /*externalLock*/);
2423            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2424            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2425        }
2426        }
2427        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2440                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2441
2442        String separateProcesses = SystemProperties.get("debug.separate_processes");
2443        if (separateProcesses != null && separateProcesses.length() > 0) {
2444            if ("*".equals(separateProcesses)) {
2445                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2446                mSeparateProcesses = null;
2447                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2448            } else {
2449                mDefParseFlags = 0;
2450                mSeparateProcesses = separateProcesses.split(",");
2451                Slog.w(TAG, "Running with debug.separate_processes: "
2452                        + separateProcesses);
2453            }
2454        } else {
2455            mDefParseFlags = 0;
2456            mSeparateProcesses = null;
2457        }
2458
2459        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2460                "*dexopt*");
2461        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2462                installer, mInstallLock);
2463        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2464                dexManagerListener);
2465        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2466        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2467
2468        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2469                FgThread.get().getLooper());
2470
2471        getDefaultDisplayMetrics(context, mMetrics);
2472
2473        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2474        SystemConfig systemConfig = SystemConfig.getInstance();
2475        mAvailableFeatures = systemConfig.getAvailableFeatures();
2476        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2477
2478        mProtectedPackages = new ProtectedPackages(mContext);
2479
2480        synchronized (mInstallLock) {
2481        // writer
2482        synchronized (mPackages) {
2483            mHandlerThread = new ServiceThread(TAG,
2484                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2485            mHandlerThread.start();
2486            mHandler = new PackageHandler(mHandlerThread.getLooper());
2487            mProcessLoggingHandler = new ProcessLoggingHandler();
2488            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2489            mInstantAppRegistry = new InstantAppRegistry(this);
2490
2491            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2492            final int builtInLibCount = libConfig.size();
2493            for (int i = 0; i < builtInLibCount; i++) {
2494                String name = libConfig.keyAt(i);
2495                String path = libConfig.valueAt(i);
2496                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2497                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2498            }
2499
2500            SELinuxMMAC.readInstallPolicy();
2501
2502            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2503            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2504            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2505
2506            // Clean up orphaned packages for which the code path doesn't exist
2507            // and they are an update to a system app - caused by bug/32321269
2508            final int packageSettingCount = mSettings.mPackages.size();
2509            for (int i = packageSettingCount - 1; i >= 0; i--) {
2510                PackageSetting ps = mSettings.mPackages.valueAt(i);
2511                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2512                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2513                    mSettings.mPackages.removeAt(i);
2514                    mSettings.enableSystemPackageLPw(ps.name);
2515                }
2516            }
2517
2518            if (mFirstBoot) {
2519                requestCopyPreoptedFiles();
2520            }
2521
2522            String customResolverActivity = Resources.getSystem().getString(
2523                    R.string.config_customResolverActivity);
2524            if (TextUtils.isEmpty(customResolverActivity)) {
2525                customResolverActivity = null;
2526            } else {
2527                mCustomResolverComponentName = ComponentName.unflattenFromString(
2528                        customResolverActivity);
2529            }
2530
2531            long startTime = SystemClock.uptimeMillis();
2532
2533            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2534                    startTime);
2535
2536            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2537            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2538
2539            if (bootClassPath == null) {
2540                Slog.w(TAG, "No BOOTCLASSPATH found!");
2541            }
2542
2543            if (systemServerClassPath == null) {
2544                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2545            }
2546
2547            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2548
2549            final VersionInfo ver = mSettings.getInternalVersion();
2550            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2551            if (mIsUpgrade) {
2552                logCriticalInfo(Log.INFO,
2553                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2554            }
2555
2556            // when upgrading from pre-M, promote system app permissions from install to runtime
2557            mPromoteSystemApps =
2558                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2559
2560            // When upgrading from pre-N, we need to handle package extraction like first boot,
2561            // as there is no profiling data available.
2562            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2563
2564            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2565
2566            // save off the names of pre-existing system packages prior to scanning; we don't
2567            // want to automatically grant runtime permissions for new system apps
2568            if (mPromoteSystemApps) {
2569                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2570                while (pkgSettingIter.hasNext()) {
2571                    PackageSetting ps = pkgSettingIter.next();
2572                    if (isSystemApp(ps)) {
2573                        mExistingSystemPackages.add(ps.name);
2574                    }
2575                }
2576            }
2577
2578            mCacheDir = preparePackageParserCache(mIsUpgrade);
2579
2580            // Set flag to monitor and not change apk file paths when
2581            // scanning install directories.
2582            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2583
2584            if (mIsUpgrade || mFirstBoot) {
2585                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2586            }
2587
2588            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2589            // For security and version matching reason, only consider
2590            // overlay packages if they reside in the right directory.
2591            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2592                    mDefParseFlags
2593                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2594                    scanFlags
2595                    | SCAN_AS_SYSTEM
2596                    | SCAN_AS_VENDOR,
2597                    0);
2598            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2599                    mDefParseFlags
2600                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2601                    scanFlags
2602                    | SCAN_AS_SYSTEM
2603                    | SCAN_AS_PRODUCT,
2604                    0);
2605
2606            mParallelPackageParserCallback.findStaticOverlayPackages();
2607
2608            // Find base frameworks (resource packages without code).
2609            scanDirTracedLI(frameworkDir,
2610                    mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2612                    scanFlags
2613                    | SCAN_NO_DEX
2614                    | SCAN_AS_SYSTEM
2615                    | SCAN_AS_PRIVILEGED,
2616                    0);
2617
2618            // Collect privileged system packages.
2619            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2620            scanDirTracedLI(privilegedAppDir,
2621                    mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2623                    scanFlags
2624                    | SCAN_AS_SYSTEM
2625                    | SCAN_AS_PRIVILEGED,
2626                    0);
2627
2628            // Collect ordinary system packages.
2629            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2630            scanDirTracedLI(systemAppDir,
2631                    mDefParseFlags
2632                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2633                    scanFlags
2634                    | SCAN_AS_SYSTEM,
2635                    0);
2636
2637            // Collect privileged vendor packages.
2638            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2639            try {
2640                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2641            } catch (IOException e) {
2642                // failed to look up canonical path, continue with original one
2643            }
2644            scanDirTracedLI(privilegedVendorAppDir,
2645                    mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2647                    scanFlags
2648                    | SCAN_AS_SYSTEM
2649                    | SCAN_AS_VENDOR
2650                    | SCAN_AS_PRIVILEGED,
2651                    0);
2652
2653            // Collect ordinary vendor packages.
2654            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2655            try {
2656                vendorAppDir = vendorAppDir.getCanonicalFile();
2657            } catch (IOException e) {
2658                // failed to look up canonical path, continue with original one
2659            }
2660            scanDirTracedLI(vendorAppDir,
2661                    mDefParseFlags
2662                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2663                    scanFlags
2664                    | SCAN_AS_SYSTEM
2665                    | SCAN_AS_VENDOR,
2666                    0);
2667
2668            // Collect privileged odm packages. /odm is another vendor partition
2669            // other than /vendor.
2670            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2671                        "priv-app");
2672            try {
2673                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2674            } catch (IOException e) {
2675                // failed to look up canonical path, continue with original one
2676            }
2677            scanDirTracedLI(privilegedOdmAppDir,
2678                    mDefParseFlags
2679                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2680                    scanFlags
2681                    | SCAN_AS_SYSTEM
2682                    | SCAN_AS_VENDOR
2683                    | SCAN_AS_PRIVILEGED,
2684                    0);
2685
2686            // Collect ordinary odm packages. /odm is another vendor partition
2687            // other than /vendor.
2688            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2689            try {
2690                odmAppDir = odmAppDir.getCanonicalFile();
2691            } catch (IOException e) {
2692                // failed to look up canonical path, continue with original one
2693            }
2694            scanDirTracedLI(odmAppDir,
2695                    mDefParseFlags
2696                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2697                    scanFlags
2698                    | SCAN_AS_SYSTEM
2699                    | SCAN_AS_VENDOR,
2700                    0);
2701
2702            // Collect all OEM packages.
2703            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2704            scanDirTracedLI(oemAppDir,
2705                    mDefParseFlags
2706                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2707                    scanFlags
2708                    | SCAN_AS_SYSTEM
2709                    | SCAN_AS_OEM,
2710                    0);
2711
2712            // Collected privileged product packages.
2713            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2714            try {
2715                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2716            } catch (IOException e) {
2717                // failed to look up canonical path, continue with original one
2718            }
2719            scanDirTracedLI(privilegedProductAppDir,
2720                    mDefParseFlags
2721                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2722                    scanFlags
2723                    | SCAN_AS_SYSTEM
2724                    | SCAN_AS_PRODUCT
2725                    | SCAN_AS_PRIVILEGED,
2726                    0);
2727
2728            // Collect ordinary product packages.
2729            File productAppDir = new File(Environment.getProductDirectory(), "app");
2730            try {
2731                productAppDir = productAppDir.getCanonicalFile();
2732            } catch (IOException e) {
2733                // failed to look up canonical path, continue with original one
2734            }
2735            scanDirTracedLI(productAppDir,
2736                    mDefParseFlags
2737                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2738                    scanFlags
2739                    | SCAN_AS_SYSTEM
2740                    | SCAN_AS_PRODUCT,
2741                    0);
2742
2743            // Prune any system packages that no longer exist.
2744            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2745            // Stub packages must either be replaced with full versions in the /data
2746            // partition or be disabled.
2747            final List<String> stubSystemApps = new ArrayList<>();
2748            if (!mOnlyCore) {
2749                // do this first before mucking with mPackages for the "expecting better" case
2750                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2751                while (pkgIterator.hasNext()) {
2752                    final PackageParser.Package pkg = pkgIterator.next();
2753                    if (pkg.isStub) {
2754                        stubSystemApps.add(pkg.packageName);
2755                    }
2756                }
2757
2758                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2759                while (psit.hasNext()) {
2760                    PackageSetting ps = psit.next();
2761
2762                    /*
2763                     * If this is not a system app, it can't be a
2764                     * disable system app.
2765                     */
2766                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2767                        continue;
2768                    }
2769
2770                    /*
2771                     * If the package is scanned, it's not erased.
2772                     */
2773                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2774                    if (scannedPkg != null) {
2775                        /*
2776                         * If the system app is both scanned and in the
2777                         * disabled packages list, then it must have been
2778                         * added via OTA. Remove it from the currently
2779                         * scanned package so the previously user-installed
2780                         * application can be scanned.
2781                         */
2782                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2783                            logCriticalInfo(Log.WARN,
2784                                    "Expecting better updated system app for " + ps.name
2785                                    + "; removing system app.  Last known"
2786                                    + " codePath=" + ps.codePathString
2787                                    + ", versionCode=" + ps.versionCode
2788                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2789                            removePackageLI(scannedPkg, true);
2790                            mExpectingBetter.put(ps.name, ps.codePath);
2791                        }
2792
2793                        continue;
2794                    }
2795
2796                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2797                        psit.remove();
2798                        logCriticalInfo(Log.WARN, "System package " + ps.name
2799                                + " no longer exists; it's data will be wiped");
2800                        // Actual deletion of code and data will be handled by later
2801                        // reconciliation step
2802                    } else {
2803                        // we still have a disabled system package, but, it still might have
2804                        // been removed. check the code path still exists and check there's
2805                        // still a package. the latter can happen if an OTA keeps the same
2806                        // code path, but, changes the package name.
2807                        final PackageSetting disabledPs =
2808                                mSettings.getDisabledSystemPkgLPr(ps.name);
2809                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2810                                || disabledPs.pkg == null) {
2811                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2812                        }
2813                    }
2814                }
2815            }
2816
2817            //delete tmp files
2818            deleteTempPackageFiles();
2819
2820            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2821
2822            // Remove any shared userIDs that have no associated packages
2823            mSettings.pruneSharedUsersLPw();
2824            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2825            final int systemPackagesCount = mPackages.size();
2826            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2827                    + " ms, packageCount: " + systemPackagesCount
2828                    + " , timePerPackage: "
2829                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2830                    + " , cached: " + cachedSystemApps);
2831            if (mIsUpgrade && systemPackagesCount > 0) {
2832                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2833                        ((int) systemScanTime) / systemPackagesCount);
2834            }
2835            if (!mOnlyCore) {
2836                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2837                        SystemClock.uptimeMillis());
2838                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2839
2840                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2841                        | PackageParser.PARSE_FORWARD_LOCK,
2842                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2843
2844                // Remove disable package settings for updated system apps that were
2845                // removed via an OTA. If the update is no longer present, remove the
2846                // app completely. Otherwise, revoke their system privileges.
2847                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2848                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2849                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2850                    final String msg;
2851                    if (deletedPkg == null) {
2852                        // should have found an update, but, we didn't; remove everything
2853                        msg = "Updated system package " + deletedAppName
2854                                + " no longer exists; removing its data";
2855                        // Actual deletion of code and data will be handled by later
2856                        // reconciliation step
2857                    } else {
2858                        // found an update; revoke system privileges
2859                        msg = "Updated system package + " + deletedAppName
2860                                + " no longer exists; revoking system privileges";
2861
2862                        // Don't do anything if a stub is removed from the system image. If
2863                        // we were to remove the uncompressed version from the /data partition,
2864                        // this is where it'd be done.
2865
2866                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2867                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2868                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2869                    }
2870                    logCriticalInfo(Log.WARN, msg);
2871                }
2872
2873                /*
2874                 * Make sure all system apps that we expected to appear on
2875                 * the userdata partition actually showed up. If they never
2876                 * appeared, crawl back and revive the system version.
2877                 */
2878                for (int i = 0; i < mExpectingBetter.size(); i++) {
2879                    final String packageName = mExpectingBetter.keyAt(i);
2880                    if (!mPackages.containsKey(packageName)) {
2881                        final File scanFile = mExpectingBetter.valueAt(i);
2882
2883                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2884                                + " but never showed up; reverting to system");
2885
2886                        final @ParseFlags int reparseFlags;
2887                        final @ScanFlags int rescanFlags;
2888                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2889                            reparseFlags =
2890                                    mDefParseFlags |
2891                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2892                            rescanFlags =
2893                                    scanFlags
2894                                    | SCAN_AS_SYSTEM
2895                                    | SCAN_AS_PRIVILEGED;
2896                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2897                            reparseFlags =
2898                                    mDefParseFlags |
2899                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2900                            rescanFlags =
2901                                    scanFlags
2902                                    | SCAN_AS_SYSTEM;
2903                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2904                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2905                            reparseFlags =
2906                                    mDefParseFlags |
2907                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2908                            rescanFlags =
2909                                    scanFlags
2910                                    | SCAN_AS_SYSTEM
2911                                    | SCAN_AS_VENDOR
2912                                    | SCAN_AS_PRIVILEGED;
2913                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2914                                || FileUtils.contains(odmAppDir, scanFile)) {
2915                            reparseFlags =
2916                                    mDefParseFlags |
2917                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2918                            rescanFlags =
2919                                    scanFlags
2920                                    | SCAN_AS_SYSTEM
2921                                    | SCAN_AS_VENDOR;
2922                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2923                            reparseFlags =
2924                                    mDefParseFlags |
2925                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2926                            rescanFlags =
2927                                    scanFlags
2928                                    | SCAN_AS_SYSTEM
2929                                    | SCAN_AS_OEM;
2930                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2931                            reparseFlags =
2932                                    mDefParseFlags |
2933                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2934                            rescanFlags =
2935                                    scanFlags
2936                                    | SCAN_AS_SYSTEM
2937                                    | SCAN_AS_PRODUCT
2938                                    | SCAN_AS_PRIVILEGED;
2939                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2940                            reparseFlags =
2941                                    mDefParseFlags |
2942                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2943                            rescanFlags =
2944                                    scanFlags
2945                                    | SCAN_AS_SYSTEM
2946                                    | SCAN_AS_PRODUCT;
2947                        } else {
2948                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2949                            continue;
2950                        }
2951
2952                        mSettings.enableSystemPackageLPw(packageName);
2953
2954                        try {
2955                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2956                        } catch (PackageManagerException e) {
2957                            Slog.e(TAG, "Failed to parse original system package: "
2958                                    + e.getMessage());
2959                        }
2960                    }
2961                }
2962
2963                // Uncompress and install any stubbed system applications.
2964                // This must be done last to ensure all stubs are replaced or disabled.
2965                decompressSystemApplications(stubSystemApps, scanFlags);
2966
2967                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2968                                - cachedSystemApps;
2969
2970                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2971                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2972                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2973                        + " ms, packageCount: " + dataPackagesCount
2974                        + " , timePerPackage: "
2975                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2976                        + " , cached: " + cachedNonSystemApps);
2977                if (mIsUpgrade && dataPackagesCount > 0) {
2978                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2979                            ((int) dataScanTime) / dataPackagesCount);
2980                }
2981            }
2982            mExpectingBetter.clear();
2983
2984            // Resolve the storage manager.
2985            mStorageManagerPackage = getStorageManagerPackageName();
2986
2987            // Resolve protected action filters. Only the setup wizard is allowed to
2988            // have a high priority filter for these actions.
2989            mSetupWizardPackage = getSetupWizardPackageName();
2990            if (mProtectedFilters.size() > 0) {
2991                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2992                    Slog.i(TAG, "No setup wizard;"
2993                        + " All protected intents capped to priority 0");
2994                }
2995                for (ActivityIntentInfo filter : mProtectedFilters) {
2996                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2997                        if (DEBUG_FILTERS) {
2998                            Slog.i(TAG, "Found setup wizard;"
2999                                + " allow priority " + filter.getPriority() + ";"
3000                                + " package: " + filter.activity.info.packageName
3001                                + " activity: " + filter.activity.className
3002                                + " priority: " + filter.getPriority());
3003                        }
3004                        // skip setup wizard; allow it to keep the high priority filter
3005                        continue;
3006                    }
3007                    if (DEBUG_FILTERS) {
3008                        Slog.i(TAG, "Protected action; cap priority to 0;"
3009                                + " package: " + filter.activity.info.packageName
3010                                + " activity: " + filter.activity.className
3011                                + " origPrio: " + filter.getPriority());
3012                    }
3013                    filter.setPriority(0);
3014                }
3015            }
3016
3017            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3018
3019            mDeferProtectedFilters = false;
3020            mProtectedFilters.clear();
3021
3022            // Now that we know all of the shared libraries, update all clients to have
3023            // the correct library paths.
3024            updateAllSharedLibrariesLPw(null);
3025
3026            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3027                // NOTE: We ignore potential failures here during a system scan (like
3028                // the rest of the commands above) because there's precious little we
3029                // can do about it. A settings error is reported, though.
3030                final List<String> changedAbiCodePath =
3031                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3032                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3033                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3034                        final String codePathString = changedAbiCodePath.get(i);
3035                        try {
3036                            mInstaller.rmdex(codePathString,
3037                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3038                        } catch (InstallerException ignored) {
3039                        }
3040                    }
3041                }
3042                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3043                // SELinux domain.
3044                setting.fixSeInfoLocked();
3045            }
3046
3047            // Now that we know all the packages we are keeping,
3048            // read and update their last usage times.
3049            mPackageUsage.read(mPackages);
3050            mCompilerStats.read();
3051
3052            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3053                    SystemClock.uptimeMillis());
3054            Slog.i(TAG, "Time to scan packages: "
3055                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3056                    + " seconds");
3057
3058            // If the platform SDK has changed since the last time we booted,
3059            // we need to re-grant app permission to catch any new ones that
3060            // appear.  This is really a hack, and means that apps can in some
3061            // cases get permissions that the user didn't initially explicitly
3062            // allow...  it would be nice to have some better way to handle
3063            // this situation.
3064            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3065            if (sdkUpdated) {
3066                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3067                        + mSdkVersion + "; regranting permissions for internal storage");
3068            }
3069            mPermissionManager.updateAllPermissions(
3070                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3071                    mPermissionCallback);
3072            ver.sdkVersion = mSdkVersion;
3073
3074            // If this is the first boot or an update from pre-M, and it is a normal
3075            // boot, then we need to initialize the default preferred apps across
3076            // all defined users.
3077            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3078                for (UserInfo user : sUserManager.getUsers(true)) {
3079                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3080                    applyFactoryDefaultBrowserLPw(user.id);
3081                    primeDomainVerificationsLPw(user.id);
3082                }
3083            }
3084
3085            // Prepare storage for system user really early during boot,
3086            // since core system apps like SettingsProvider and SystemUI
3087            // can't wait for user to start
3088            final int storageFlags;
3089            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3090                storageFlags = StorageManager.FLAG_STORAGE_DE;
3091            } else {
3092                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3093            }
3094            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3095                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3096                    true /* onlyCoreApps */);
3097            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3098                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3099                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3100                traceLog.traceBegin("AppDataFixup");
3101                try {
3102                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3103                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3104                } catch (InstallerException e) {
3105                    Slog.w(TAG, "Trouble fixing GIDs", e);
3106                }
3107                traceLog.traceEnd();
3108
3109                traceLog.traceBegin("AppDataPrepare");
3110                if (deferPackages == null || deferPackages.isEmpty()) {
3111                    return;
3112                }
3113                int count = 0;
3114                for (String pkgName : deferPackages) {
3115                    PackageParser.Package pkg = null;
3116                    synchronized (mPackages) {
3117                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3118                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3119                            pkg = ps.pkg;
3120                        }
3121                    }
3122                    if (pkg != null) {
3123                        synchronized (mInstallLock) {
3124                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3125                                    true /* maybeMigrateAppData */);
3126                        }
3127                        count++;
3128                    }
3129                }
3130                traceLog.traceEnd();
3131                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3132            }, "prepareAppData");
3133
3134            // If this is first boot after an OTA, and a normal boot, then
3135            // we need to clear code cache directories.
3136            // Note that we do *not* clear the application profiles. These remain valid
3137            // across OTAs and are used to drive profile verification (post OTA) and
3138            // profile compilation (without waiting to collect a fresh set of profiles).
3139            if (mIsUpgrade && !onlyCore) {
3140                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3141                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3142                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3143                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3144                        // No apps are running this early, so no need to freeze
3145                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3146                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3147                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3148                    }
3149                }
3150                ver.fingerprint = Build.FINGERPRINT;
3151            }
3152
3153            checkDefaultBrowser();
3154
3155            // clear only after permissions and other defaults have been updated
3156            mExistingSystemPackages.clear();
3157            mPromoteSystemApps = false;
3158
3159            // All the changes are done during package scanning.
3160            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3161
3162            // can downgrade to reader
3163            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3164            mSettings.writeLPr();
3165            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3166            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3167                    SystemClock.uptimeMillis());
3168
3169            if (!mOnlyCore) {
3170                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3171                mRequiredInstallerPackage = getRequiredInstallerLPr();
3172                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3173                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3174                if (mIntentFilterVerifierComponent != null) {
3175                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3176                            mIntentFilterVerifierComponent);
3177                } else {
3178                    mIntentFilterVerifier = null;
3179                }
3180                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3181                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3182                        SharedLibraryInfo.VERSION_UNDEFINED);
3183                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3184                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3185                        SharedLibraryInfo.VERSION_UNDEFINED);
3186            } else {
3187                mRequiredVerifierPackage = null;
3188                mRequiredInstallerPackage = null;
3189                mRequiredUninstallerPackage = null;
3190                mIntentFilterVerifierComponent = null;
3191                mIntentFilterVerifier = null;
3192                mServicesSystemSharedLibraryPackageName = null;
3193                mSharedSystemSharedLibraryPackageName = null;
3194            }
3195
3196            mInstallerService = new PackageInstallerService(context, this);
3197            final Pair<ComponentName, String> instantAppResolverComponent =
3198                    getInstantAppResolverLPr();
3199            if (instantAppResolverComponent != null) {
3200                if (DEBUG_INSTANT) {
3201                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3202                }
3203                mInstantAppResolverConnection = new InstantAppResolverConnection(
3204                        mContext, instantAppResolverComponent.first,
3205                        instantAppResolverComponent.second);
3206                mInstantAppResolverSettingsComponent =
3207                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3208            } else {
3209                mInstantAppResolverConnection = null;
3210                mInstantAppResolverSettingsComponent = null;
3211            }
3212            updateInstantAppInstallerLocked(null);
3213
3214            // Read and update the usage of dex files.
3215            // Do this at the end of PM init so that all the packages have their
3216            // data directory reconciled.
3217            // At this point we know the code paths of the packages, so we can validate
3218            // the disk file and build the internal cache.
3219            // The usage file is expected to be small so loading and verifying it
3220            // should take a fairly small time compare to the other activities (e.g. package
3221            // scanning).
3222            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3223            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3224            for (int userId : currentUserIds) {
3225                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3226            }
3227            mDexManager.load(userPackages);
3228            if (mIsUpgrade) {
3229                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3230                        (int) (SystemClock.uptimeMillis() - startTime));
3231            }
3232        } // synchronized (mPackages)
3233        } // synchronized (mInstallLock)
3234
3235        // Now after opening every single application zip, make sure they
3236        // are all flushed.  Not really needed, but keeps things nice and
3237        // tidy.
3238        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3239        Runtime.getRuntime().gc();
3240        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3241
3242        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3243        FallbackCategoryProvider.loadFallbacks();
3244        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3245
3246        // The initial scanning above does many calls into installd while
3247        // holding the mPackages lock, but we're mostly interested in yelling
3248        // once we have a booted system.
3249        mInstaller.setWarnIfHeld(mPackages);
3250
3251        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3252    }
3253
3254    /**
3255     * Uncompress and install stub applications.
3256     * <p>In order to save space on the system partition, some applications are shipped in a
3257     * compressed form. In addition the compressed bits for the full application, the
3258     * system image contains a tiny stub comprised of only the Android manifest.
3259     * <p>During the first boot, attempt to uncompress and install the full application. If
3260     * the application can't be installed for any reason, disable the stub and prevent
3261     * uncompressing the full application during future boots.
3262     * <p>In order to forcefully attempt an installation of a full application, go to app
3263     * settings and enable the application.
3264     */
3265    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3266        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3267            final String pkgName = stubSystemApps.get(i);
3268            // skip if the system package is already disabled
3269            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3270                stubSystemApps.remove(i);
3271                continue;
3272            }
3273            // skip if the package isn't installed (?!); this should never happen
3274            final PackageParser.Package pkg = mPackages.get(pkgName);
3275            if (pkg == null) {
3276                stubSystemApps.remove(i);
3277                continue;
3278            }
3279            // skip if the package has been disabled by the user
3280            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3281            if (ps != null) {
3282                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3283                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3284                    stubSystemApps.remove(i);
3285                    continue;
3286                }
3287            }
3288
3289            if (DEBUG_COMPRESSION) {
3290                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3291            }
3292
3293            // uncompress the binary to its eventual destination on /data
3294            final File scanFile = decompressPackage(pkg);
3295            if (scanFile == null) {
3296                continue;
3297            }
3298
3299            // install the package to replace the stub on /system
3300            try {
3301                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3302                removePackageLI(pkg, true /*chatty*/);
3303                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3304                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3305                        UserHandle.USER_SYSTEM, "android");
3306                stubSystemApps.remove(i);
3307                continue;
3308            } catch (PackageManagerException e) {
3309                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3310            }
3311
3312            // any failed attempt to install the package will be cleaned up later
3313        }
3314
3315        // disable any stub still left; these failed to install the full application
3316        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3317            final String pkgName = stubSystemApps.get(i);
3318            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3319            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3320                    UserHandle.USER_SYSTEM, "android");
3321            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3322        }
3323    }
3324
3325    /**
3326     * Decompresses the given package on the system image onto
3327     * the /data partition.
3328     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3329     */
3330    private File decompressPackage(PackageParser.Package pkg) {
3331        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3332        if (compressedFiles == null || compressedFiles.length == 0) {
3333            if (DEBUG_COMPRESSION) {
3334                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3335            }
3336            return null;
3337        }
3338        final File dstCodePath =
3339                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3340        int ret = PackageManager.INSTALL_SUCCEEDED;
3341        try {
3342            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3343            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3344            for (File srcFile : compressedFiles) {
3345                final String srcFileName = srcFile.getName();
3346                final String dstFileName = srcFileName.substring(
3347                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3348                final File dstFile = new File(dstCodePath, dstFileName);
3349                ret = decompressFile(srcFile, dstFile);
3350                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3351                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3352                            + "; pkg: " + pkg.packageName
3353                            + ", file: " + dstFileName);
3354                    break;
3355                }
3356            }
3357        } catch (ErrnoException e) {
3358            logCriticalInfo(Log.ERROR, "Failed to decompress"
3359                    + "; pkg: " + pkg.packageName
3360                    + ", err: " + e.errno);
3361        }
3362        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3363            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3364            NativeLibraryHelper.Handle handle = null;
3365            try {
3366                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3367                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3368                        null /*abiOverride*/);
3369            } catch (IOException e) {
3370                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3371                        + "; pkg: " + pkg.packageName);
3372                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3373            } finally {
3374                IoUtils.closeQuietly(handle);
3375            }
3376        }
3377        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3378            if (dstCodePath == null || !dstCodePath.exists()) {
3379                return null;
3380            }
3381            removeCodePathLI(dstCodePath);
3382            return null;
3383        }
3384
3385        return dstCodePath;
3386    }
3387
3388    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3389        // we're only interested in updating the installer appliction when 1) it's not
3390        // already set or 2) the modified package is the installer
3391        if (mInstantAppInstallerActivity != null
3392                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3393                        .equals(modifiedPackage)) {
3394            return;
3395        }
3396        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3397    }
3398
3399    private static File preparePackageParserCache(boolean isUpgrade) {
3400        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3401            return null;
3402        }
3403
3404        // Disable package parsing on eng builds to allow for faster incremental development.
3405        if (Build.IS_ENG) {
3406            return null;
3407        }
3408
3409        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3410            Slog.i(TAG, "Disabling package parser cache due to system property.");
3411            return null;
3412        }
3413
3414        // The base directory for the package parser cache lives under /data/system/.
3415        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3416                "package_cache");
3417        if (cacheBaseDir == null) {
3418            return null;
3419        }
3420
3421        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3422        // This also serves to "GC" unused entries when the package cache version changes (which
3423        // can only happen during upgrades).
3424        if (isUpgrade) {
3425            FileUtils.deleteContents(cacheBaseDir);
3426        }
3427
3428
3429        // Return the versioned package cache directory. This is something like
3430        // "/data/system/package_cache/1"
3431        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3432
3433        if (cacheDir == null) {
3434            // Something went wrong. Attempt to delete everything and return.
3435            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3436            FileUtils.deleteContentsAndDir(cacheBaseDir);
3437            return null;
3438        }
3439
3440        // The following is a workaround to aid development on non-numbered userdebug
3441        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3442        // the system partition is newer.
3443        //
3444        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3445        // that starts with "eng." to signify that this is an engineering build and not
3446        // destined for release.
3447        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3448            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3449
3450            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3451            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3452            // in general and should not be used for production changes. In this specific case,
3453            // we know that they will work.
3454            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3455            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3456                FileUtils.deleteContents(cacheBaseDir);
3457                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3458            }
3459        }
3460
3461        return cacheDir;
3462    }
3463
3464    @Override
3465    public boolean isFirstBoot() {
3466        // allow instant applications
3467        return mFirstBoot;
3468    }
3469
3470    @Override
3471    public boolean isOnlyCoreApps() {
3472        // allow instant applications
3473        return mOnlyCore;
3474    }
3475
3476    @Override
3477    public boolean isUpgrade() {
3478        // allow instant applications
3479        // The system property allows testing ota flow when upgraded to the same image.
3480        return mIsUpgrade || SystemProperties.getBoolean(
3481                "persist.pm.mock-upgrade", false /* default */);
3482    }
3483
3484    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3485        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3486
3487        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3488                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3489                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3490        if (matches.size() == 1) {
3491            return matches.get(0).getComponentInfo().packageName;
3492        } else if (matches.size() == 0) {
3493            Log.e(TAG, "There should probably be a verifier, but, none were found");
3494            return null;
3495        }
3496        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3497    }
3498
3499    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3500        synchronized (mPackages) {
3501            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3502            if (libraryEntry == null) {
3503                throw new IllegalStateException("Missing required shared library:" + name);
3504            }
3505            return libraryEntry.apk;
3506        }
3507    }
3508
3509    private @NonNull String getRequiredInstallerLPr() {
3510        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3511        intent.addCategory(Intent.CATEGORY_DEFAULT);
3512        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3513
3514        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3515                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3516                UserHandle.USER_SYSTEM);
3517        if (matches.size() == 1) {
3518            ResolveInfo resolveInfo = matches.get(0);
3519            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3520                throw new RuntimeException("The installer must be a privileged app");
3521            }
3522            return matches.get(0).getComponentInfo().packageName;
3523        } else {
3524            throw new RuntimeException("There must be exactly one installer; found " + matches);
3525        }
3526    }
3527
3528    private @NonNull String getRequiredUninstallerLPr() {
3529        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3530        intent.addCategory(Intent.CATEGORY_DEFAULT);
3531        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3532
3533        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3534                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3535                UserHandle.USER_SYSTEM);
3536        if (resolveInfo == null ||
3537                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3538            throw new RuntimeException("There must be exactly one uninstaller; found "
3539                    + resolveInfo);
3540        }
3541        return resolveInfo.getComponentInfo().packageName;
3542    }
3543
3544    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3545        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3546
3547        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3548                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3549                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3550        ResolveInfo best = null;
3551        final int N = matches.size();
3552        for (int i = 0; i < N; i++) {
3553            final ResolveInfo cur = matches.get(i);
3554            final String packageName = cur.getComponentInfo().packageName;
3555            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3556                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3557                continue;
3558            }
3559
3560            if (best == null || cur.priority > best.priority) {
3561                best = cur;
3562            }
3563        }
3564
3565        if (best != null) {
3566            return best.getComponentInfo().getComponentName();
3567        }
3568        Slog.w(TAG, "Intent filter verifier not found");
3569        return null;
3570    }
3571
3572    @Override
3573    public @Nullable ComponentName getInstantAppResolverComponent() {
3574        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3575            return null;
3576        }
3577        synchronized (mPackages) {
3578            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3579            if (instantAppResolver == null) {
3580                return null;
3581            }
3582            return instantAppResolver.first;
3583        }
3584    }
3585
3586    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3587        final String[] packageArray =
3588                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3589        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3590            if (DEBUG_INSTANT) {
3591                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3592            }
3593            return null;
3594        }
3595
3596        final int callingUid = Binder.getCallingUid();
3597        final int resolveFlags =
3598                MATCH_DIRECT_BOOT_AWARE
3599                | MATCH_DIRECT_BOOT_UNAWARE
3600                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3601        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3602        final Intent resolverIntent = new Intent(actionName);
3603        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3604                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3605        final int N = resolvers.size();
3606        if (N == 0) {
3607            if (DEBUG_INSTANT) {
3608                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3609            }
3610            return null;
3611        }
3612
3613        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3614        for (int i = 0; i < N; i++) {
3615            final ResolveInfo info = resolvers.get(i);
3616
3617            if (info.serviceInfo == null) {
3618                continue;
3619            }
3620
3621            final String packageName = info.serviceInfo.packageName;
3622            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3623                if (DEBUG_INSTANT) {
3624                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3625                            + " pkg: " + packageName + ", info:" + info);
3626                }
3627                continue;
3628            }
3629
3630            if (DEBUG_INSTANT) {
3631                Slog.v(TAG, "Ephemeral resolver found;"
3632                        + " pkg: " + packageName + ", info:" + info);
3633            }
3634            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3635        }
3636        if (DEBUG_INSTANT) {
3637            Slog.v(TAG, "Ephemeral resolver NOT found");
3638        }
3639        return null;
3640    }
3641
3642    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3643        String[] orderedActions = Build.IS_ENG
3644                ? new String[]{
3645                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3646                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3647                : new String[]{
3648                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3649
3650        final int resolveFlags =
3651                MATCH_DIRECT_BOOT_AWARE
3652                        | MATCH_DIRECT_BOOT_UNAWARE
3653                        | Intent.FLAG_IGNORE_EPHEMERAL
3654                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3655        final Intent intent = new Intent();
3656        intent.addCategory(Intent.CATEGORY_DEFAULT);
3657        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3658        List<ResolveInfo> matches = null;
3659        for (String action : orderedActions) {
3660            intent.setAction(action);
3661            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3662                    resolveFlags, UserHandle.USER_SYSTEM);
3663            if (matches.isEmpty()) {
3664                if (DEBUG_INSTANT) {
3665                    Slog.d(TAG, "Instant App installer not found with " + action);
3666                }
3667            } else {
3668                break;
3669            }
3670        }
3671        Iterator<ResolveInfo> iter = matches.iterator();
3672        while (iter.hasNext()) {
3673            final ResolveInfo rInfo = iter.next();
3674            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3675            if (ps != null) {
3676                final PermissionsState permissionsState = ps.getPermissionsState();
3677                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3678                        || Build.IS_ENG) {
3679                    continue;
3680                }
3681            }
3682            iter.remove();
3683        }
3684        if (matches.size() == 0) {
3685            return null;
3686        } else if (matches.size() == 1) {
3687            return (ActivityInfo) matches.get(0).getComponentInfo();
3688        } else {
3689            throw new RuntimeException(
3690                    "There must be at most one ephemeral installer; found " + matches);
3691        }
3692    }
3693
3694    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3695            @NonNull ComponentName resolver) {
3696        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3697                .addCategory(Intent.CATEGORY_DEFAULT)
3698                .setPackage(resolver.getPackageName());
3699        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3700        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3701                UserHandle.USER_SYSTEM);
3702        if (matches.isEmpty()) {
3703            return null;
3704        }
3705        return matches.get(0).getComponentInfo().getComponentName();
3706    }
3707
3708    private void primeDomainVerificationsLPw(int userId) {
3709        if (DEBUG_DOMAIN_VERIFICATION) {
3710            Slog.d(TAG, "Priming domain verifications in user " + userId);
3711        }
3712
3713        SystemConfig systemConfig = SystemConfig.getInstance();
3714        ArraySet<String> packages = systemConfig.getLinkedApps();
3715
3716        for (String packageName : packages) {
3717            PackageParser.Package pkg = mPackages.get(packageName);
3718            if (pkg != null) {
3719                if (!pkg.isSystem()) {
3720                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3721                    continue;
3722                }
3723
3724                ArraySet<String> domains = null;
3725                for (PackageParser.Activity a : pkg.activities) {
3726                    for (ActivityIntentInfo filter : a.intents) {
3727                        if (hasValidDomains(filter)) {
3728                            if (domains == null) {
3729                                domains = new ArraySet<String>();
3730                            }
3731                            domains.addAll(filter.getHostsList());
3732                        }
3733                    }
3734                }
3735
3736                if (domains != null && domains.size() > 0) {
3737                    if (DEBUG_DOMAIN_VERIFICATION) {
3738                        Slog.v(TAG, "      + " + packageName);
3739                    }
3740                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3741                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3742                    // and then 'always' in the per-user state actually used for intent resolution.
3743                    final IntentFilterVerificationInfo ivi;
3744                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3745                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3746                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3747                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3748                } else {
3749                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3750                            + "' does not handle web links");
3751                }
3752            } else {
3753                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3754            }
3755        }
3756
3757        scheduleWritePackageRestrictionsLocked(userId);
3758        scheduleWriteSettingsLocked();
3759    }
3760
3761    private void applyFactoryDefaultBrowserLPw(int userId) {
3762        // The default browser app's package name is stored in a string resource,
3763        // with a product-specific overlay used for vendor customization.
3764        String browserPkg = mContext.getResources().getString(
3765                com.android.internal.R.string.default_browser);
3766        if (!TextUtils.isEmpty(browserPkg)) {
3767            // non-empty string => required to be a known package
3768            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3769            if (ps == null) {
3770                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3771                browserPkg = null;
3772            } else {
3773                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3774            }
3775        }
3776
3777        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3778        // default.  If there's more than one, just leave everything alone.
3779        if (browserPkg == null) {
3780            calculateDefaultBrowserLPw(userId);
3781        }
3782    }
3783
3784    private void calculateDefaultBrowserLPw(int userId) {
3785        List<String> allBrowsers = resolveAllBrowserApps(userId);
3786        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3787        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3788    }
3789
3790    private List<String> resolveAllBrowserApps(int userId) {
3791        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3792        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3793                PackageManager.MATCH_ALL, userId);
3794
3795        final int count = list.size();
3796        List<String> result = new ArrayList<String>(count);
3797        for (int i=0; i<count; i++) {
3798            ResolveInfo info = list.get(i);
3799            if (info.activityInfo == null
3800                    || !info.handleAllWebDataURI
3801                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3802                    || result.contains(info.activityInfo.packageName)) {
3803                continue;
3804            }
3805            result.add(info.activityInfo.packageName);
3806        }
3807
3808        return result;
3809    }
3810
3811    private boolean packageIsBrowser(String packageName, int userId) {
3812        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3813                PackageManager.MATCH_ALL, userId);
3814        final int N = list.size();
3815        for (int i = 0; i < N; i++) {
3816            ResolveInfo info = list.get(i);
3817            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3818                return true;
3819            }
3820        }
3821        return false;
3822    }
3823
3824    private void checkDefaultBrowser() {
3825        final int myUserId = UserHandle.myUserId();
3826        final String packageName = getDefaultBrowserPackageName(myUserId);
3827        if (packageName != null) {
3828            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3829            if (info == null) {
3830                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3831                synchronized (mPackages) {
3832                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3833                }
3834            }
3835        }
3836    }
3837
3838    @Override
3839    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3840            throws RemoteException {
3841        try {
3842            return super.onTransact(code, data, reply, flags);
3843        } catch (RuntimeException e) {
3844            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3845                Slog.wtf(TAG, "Package Manager Crash", e);
3846            }
3847            throw e;
3848        }
3849    }
3850
3851    static int[] appendInts(int[] cur, int[] add) {
3852        if (add == null) return cur;
3853        if (cur == null) return add;
3854        final int N = add.length;
3855        for (int i=0; i<N; i++) {
3856            cur = appendInt(cur, add[i]);
3857        }
3858        return cur;
3859    }
3860
3861    /**
3862     * Returns whether or not a full application can see an instant application.
3863     * <p>
3864     * Currently, there are three cases in which this can occur:
3865     * <ol>
3866     * <li>The calling application is a "special" process. Special processes
3867     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3868     * <li>The calling application has the permission
3869     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3870     * <li>The calling application is the default launcher on the
3871     *     system partition.</li>
3872     * </ol>
3873     */
3874    private boolean canViewInstantApps(int callingUid, int userId) {
3875        if (callingUid < Process.FIRST_APPLICATION_UID) {
3876            return true;
3877        }
3878        if (mContext.checkCallingOrSelfPermission(
3879                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3880            return true;
3881        }
3882        if (mContext.checkCallingOrSelfPermission(
3883                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3884            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3885            if (homeComponent != null
3886                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3887                return true;
3888            }
3889        }
3890        return false;
3891    }
3892
3893    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3894        if (!sUserManager.exists(userId)) return null;
3895        if (ps == null) {
3896            return null;
3897        }
3898        final int callingUid = Binder.getCallingUid();
3899        // Filter out ephemeral app metadata:
3900        //   * The system/shell/root can see metadata for any app
3901        //   * An installed app can see metadata for 1) other installed apps
3902        //     and 2) ephemeral apps that have explicitly interacted with it
3903        //   * Ephemeral apps can only see their own data and exposed installed apps
3904        //   * Holding a signature permission allows seeing instant apps
3905        if (filterAppAccessLPr(ps, callingUid, userId)) {
3906            return null;
3907        }
3908
3909        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3910                && ps.isSystem()) {
3911            flags |= MATCH_ANY_USER;
3912        }
3913
3914        final PackageUserState state = ps.readUserState(userId);
3915        PackageParser.Package p = ps.pkg;
3916        if (p != null) {
3917            final PermissionsState permissionsState = ps.getPermissionsState();
3918
3919            // Compute GIDs only if requested
3920            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3921                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3922            // Compute granted permissions only if package has requested permissions
3923            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3924                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3925
3926            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3927                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3928
3929            if (packageInfo == null) {
3930                return null;
3931            }
3932
3933            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3934                    resolveExternalPackageNameLPr(p);
3935
3936            return packageInfo;
3937        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3938            PackageInfo pi = new PackageInfo();
3939            pi.packageName = ps.name;
3940            pi.setLongVersionCode(ps.versionCode);
3941            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3942            pi.firstInstallTime = ps.firstInstallTime;
3943            pi.lastUpdateTime = ps.lastUpdateTime;
3944
3945            ApplicationInfo ai = new ApplicationInfo();
3946            ai.packageName = ps.name;
3947            ai.uid = UserHandle.getUid(userId, ps.appId);
3948            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3949            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3950            ai.setVersionCode(ps.versionCode);
3951            ai.flags = ps.pkgFlags;
3952            ai.privateFlags = ps.pkgPrivateFlags;
3953            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3954
3955            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3956                    + ps.name + "]. Provides a minimum info.");
3957            return pi;
3958        } else {
3959            return null;
3960        }
3961    }
3962
3963    @Override
3964    public void checkPackageStartable(String packageName, int userId) {
3965        final int callingUid = Binder.getCallingUid();
3966        if (getInstantAppPackageName(callingUid) != null) {
3967            throw new SecurityException("Instant applications don't have access to this method");
3968        }
3969        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3970        synchronized (mPackages) {
3971            final PackageSetting ps = mSettings.mPackages.get(packageName);
3972            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3973                throw new SecurityException("Package " + packageName + " was not found!");
3974            }
3975
3976            if (!ps.getInstalled(userId)) {
3977                throw new SecurityException(
3978                        "Package " + packageName + " was not installed for user " + userId + "!");
3979            }
3980
3981            if (mSafeMode && !ps.isSystem()) {
3982                throw new SecurityException("Package " + packageName + " not a system app!");
3983            }
3984
3985            if (mFrozenPackages.contains(packageName)) {
3986                throw new SecurityException("Package " + packageName + " is currently frozen!");
3987            }
3988
3989            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3990                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3991            }
3992        }
3993    }
3994
3995    @Override
3996    public boolean isPackageAvailable(String packageName, int userId) {
3997        if (!sUserManager.exists(userId)) return false;
3998        final int callingUid = Binder.getCallingUid();
3999        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4000                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4001        synchronized (mPackages) {
4002            PackageParser.Package p = mPackages.get(packageName);
4003            if (p != null) {
4004                final PackageSetting ps = (PackageSetting) p.mExtras;
4005                if (filterAppAccessLPr(ps, callingUid, userId)) {
4006                    return false;
4007                }
4008                if (ps != null) {
4009                    final PackageUserState state = ps.readUserState(userId);
4010                    if (state != null) {
4011                        return PackageParser.isAvailable(state);
4012                    }
4013                }
4014            }
4015        }
4016        return false;
4017    }
4018
4019    @Override
4020    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4021        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4022                flags, Binder.getCallingUid(), userId);
4023    }
4024
4025    @Override
4026    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4027            int flags, int userId) {
4028        return getPackageInfoInternal(versionedPackage.getPackageName(),
4029                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4030    }
4031
4032    /**
4033     * Important: The provided filterCallingUid is used exclusively to filter out packages
4034     * that can be seen based on user state. It's typically the original caller uid prior
4035     * to clearing. Because it can only be provided by trusted code, it's value can be
4036     * trusted and will be used as-is; unlike userId which will be validated by this method.
4037     */
4038    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4039            int flags, int filterCallingUid, int userId) {
4040        if (!sUserManager.exists(userId)) return null;
4041        flags = updateFlagsForPackage(flags, userId, packageName);
4042        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4043                false /* requireFullPermission */, false /* checkShell */, "get package info");
4044
4045        // reader
4046        synchronized (mPackages) {
4047            // Normalize package name to handle renamed packages and static libs
4048            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4049
4050            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4051            if (matchFactoryOnly) {
4052                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4053                if (ps != null) {
4054                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4055                        return null;
4056                    }
4057                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4058                        return null;
4059                    }
4060                    return generatePackageInfo(ps, flags, userId);
4061                }
4062            }
4063
4064            PackageParser.Package p = mPackages.get(packageName);
4065            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4066                return null;
4067            }
4068            if (DEBUG_PACKAGE_INFO)
4069                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4070            if (p != null) {
4071                final PackageSetting ps = (PackageSetting) p.mExtras;
4072                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4073                    return null;
4074                }
4075                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4076                    return null;
4077                }
4078                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4079            }
4080            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4081                final PackageSetting ps = mSettings.mPackages.get(packageName);
4082                if (ps == null) return null;
4083                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4084                    return null;
4085                }
4086                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4087                    return null;
4088                }
4089                return generatePackageInfo(ps, flags, userId);
4090            }
4091        }
4092        return null;
4093    }
4094
4095    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4096        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4097            return true;
4098        }
4099        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4100            return true;
4101        }
4102        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4103            return true;
4104        }
4105        return false;
4106    }
4107
4108    private boolean isComponentVisibleToInstantApp(
4109            @Nullable ComponentName component, @ComponentType int type) {
4110        if (type == TYPE_ACTIVITY) {
4111            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4112            if (activity == null) {
4113                return false;
4114            }
4115            final boolean visibleToInstantApp =
4116                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4117            final boolean explicitlyVisibleToInstantApp =
4118                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4119            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4120        } else if (type == TYPE_RECEIVER) {
4121            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4122            if (activity == null) {
4123                return false;
4124            }
4125            final boolean visibleToInstantApp =
4126                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4127            final boolean explicitlyVisibleToInstantApp =
4128                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4129            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4130        } else if (type == TYPE_SERVICE) {
4131            final PackageParser.Service service = mServices.mServices.get(component);
4132            return service != null
4133                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4134                    : false;
4135        } else if (type == TYPE_PROVIDER) {
4136            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4137            return provider != null
4138                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4139                    : false;
4140        } else if (type == TYPE_UNKNOWN) {
4141            return isComponentVisibleToInstantApp(component);
4142        }
4143        return false;
4144    }
4145
4146    /**
4147     * Returns whether or not access to the application should be filtered.
4148     * <p>
4149     * Access may be limited based upon whether the calling or target applications
4150     * are instant applications.
4151     *
4152     * @see #canAccessInstantApps(int)
4153     */
4154    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4155            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4156        // if we're in an isolated process, get the real calling UID
4157        if (Process.isIsolated(callingUid)) {
4158            callingUid = mIsolatedOwners.get(callingUid);
4159        }
4160        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4161        final boolean callerIsInstantApp = instantAppPkgName != null;
4162        if (ps == null) {
4163            if (callerIsInstantApp) {
4164                // pretend the application exists, but, needs to be filtered
4165                return true;
4166            }
4167            return false;
4168        }
4169        // if the target and caller are the same application, don't filter
4170        if (isCallerSameApp(ps.name, callingUid)) {
4171            return false;
4172        }
4173        if (callerIsInstantApp) {
4174            // both caller and target are both instant, but, different applications, filter
4175            if (ps.getInstantApp(userId)) {
4176                return true;
4177            }
4178            // request for a specific component; if it hasn't been explicitly exposed through
4179            // property or instrumentation target, filter
4180            if (component != null) {
4181                final PackageParser.Instrumentation instrumentation =
4182                        mInstrumentation.get(component);
4183                if (instrumentation != null
4184                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4185                    return false;
4186                }
4187                return !isComponentVisibleToInstantApp(component, componentType);
4188            }
4189            // request for application; if no components have been explicitly exposed, filter
4190            return !ps.pkg.visibleToInstantApps;
4191        }
4192        if (ps.getInstantApp(userId)) {
4193            // caller can see all components of all instant applications, don't filter
4194            if (canViewInstantApps(callingUid, userId)) {
4195                return false;
4196            }
4197            // request for a specific instant application component, filter
4198            if (component != null) {
4199                return true;
4200            }
4201            // request for an instant application; if the caller hasn't been granted access, filter
4202            return !mInstantAppRegistry.isInstantAccessGranted(
4203                    userId, UserHandle.getAppId(callingUid), ps.appId);
4204        }
4205        return false;
4206    }
4207
4208    /**
4209     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4210     */
4211    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4212        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4213    }
4214
4215    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4216            int flags) {
4217        // Callers can access only the libs they depend on, otherwise they need to explicitly
4218        // ask for the shared libraries given the caller is allowed to access all static libs.
4219        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4220            // System/shell/root get to see all static libs
4221            final int appId = UserHandle.getAppId(uid);
4222            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4223                    || appId == Process.ROOT_UID) {
4224                return false;
4225            }
4226        }
4227
4228        // No package means no static lib as it is always on internal storage
4229        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4230            return false;
4231        }
4232
4233        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4234                ps.pkg.staticSharedLibVersion);
4235        if (libEntry == null) {
4236            return false;
4237        }
4238
4239        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4240        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4241        if (uidPackageNames == null) {
4242            return true;
4243        }
4244
4245        for (String uidPackageName : uidPackageNames) {
4246            if (ps.name.equals(uidPackageName)) {
4247                return false;
4248            }
4249            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4250            if (uidPs != null) {
4251                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4252                        libEntry.info.getName());
4253                if (index < 0) {
4254                    continue;
4255                }
4256                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4257                    return false;
4258                }
4259            }
4260        }
4261        return true;
4262    }
4263
4264    @Override
4265    public String[] currentToCanonicalPackageNames(String[] names) {
4266        final int callingUid = Binder.getCallingUid();
4267        if (getInstantAppPackageName(callingUid) != null) {
4268            return names;
4269        }
4270        final String[] out = new String[names.length];
4271        // reader
4272        synchronized (mPackages) {
4273            final int callingUserId = UserHandle.getUserId(callingUid);
4274            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4275            for (int i=names.length-1; i>=0; i--) {
4276                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4277                boolean translateName = false;
4278                if (ps != null && ps.realName != null) {
4279                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4280                    translateName = !targetIsInstantApp
4281                            || canViewInstantApps
4282                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4283                                    UserHandle.getAppId(callingUid), ps.appId);
4284                }
4285                out[i] = translateName ? ps.realName : names[i];
4286            }
4287        }
4288        return out;
4289    }
4290
4291    @Override
4292    public String[] canonicalToCurrentPackageNames(String[] names) {
4293        final int callingUid = Binder.getCallingUid();
4294        if (getInstantAppPackageName(callingUid) != null) {
4295            return names;
4296        }
4297        final String[] out = new String[names.length];
4298        // reader
4299        synchronized (mPackages) {
4300            final int callingUserId = UserHandle.getUserId(callingUid);
4301            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4302            for (int i=names.length-1; i>=0; i--) {
4303                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4304                boolean translateName = false;
4305                if (cur != null) {
4306                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4307                    final boolean targetIsInstantApp =
4308                            ps != null && ps.getInstantApp(callingUserId);
4309                    translateName = !targetIsInstantApp
4310                            || canViewInstantApps
4311                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4312                                    UserHandle.getAppId(callingUid), ps.appId);
4313                }
4314                out[i] = translateName ? cur : names[i];
4315            }
4316        }
4317        return out;
4318    }
4319
4320    @Override
4321    public int getPackageUid(String packageName, int flags, int userId) {
4322        if (!sUserManager.exists(userId)) return -1;
4323        final int callingUid = Binder.getCallingUid();
4324        flags = updateFlagsForPackage(flags, userId, packageName);
4325        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4326                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4327
4328        // reader
4329        synchronized (mPackages) {
4330            final PackageParser.Package p = mPackages.get(packageName);
4331            if (p != null && p.isMatch(flags)) {
4332                PackageSetting ps = (PackageSetting) p.mExtras;
4333                if (filterAppAccessLPr(ps, callingUid, userId)) {
4334                    return -1;
4335                }
4336                return UserHandle.getUid(userId, p.applicationInfo.uid);
4337            }
4338            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4339                final PackageSetting ps = mSettings.mPackages.get(packageName);
4340                if (ps != null && ps.isMatch(flags)
4341                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4342                    return UserHandle.getUid(userId, ps.appId);
4343                }
4344            }
4345        }
4346
4347        return -1;
4348    }
4349
4350    @Override
4351    public int[] getPackageGids(String packageName, int flags, int userId) {
4352        if (!sUserManager.exists(userId)) return null;
4353        final int callingUid = Binder.getCallingUid();
4354        flags = updateFlagsForPackage(flags, userId, packageName);
4355        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4356                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4357
4358        // reader
4359        synchronized (mPackages) {
4360            final PackageParser.Package p = mPackages.get(packageName);
4361            if (p != null && p.isMatch(flags)) {
4362                PackageSetting ps = (PackageSetting) p.mExtras;
4363                if (filterAppAccessLPr(ps, callingUid, userId)) {
4364                    return null;
4365                }
4366                // TODO: Shouldn't this be checking for package installed state for userId and
4367                // return null?
4368                return ps.getPermissionsState().computeGids(userId);
4369            }
4370            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4371                final PackageSetting ps = mSettings.mPackages.get(packageName);
4372                if (ps != null && ps.isMatch(flags)
4373                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4374                    return ps.getPermissionsState().computeGids(userId);
4375                }
4376            }
4377        }
4378
4379        return null;
4380    }
4381
4382    @Override
4383    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4384        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4385    }
4386
4387    @Override
4388    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4389            int flags) {
4390        final List<PermissionInfo> permissionList =
4391                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4392        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4393    }
4394
4395    @Override
4396    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4397        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4398    }
4399
4400    @Override
4401    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4402        final List<PermissionGroupInfo> permissionList =
4403                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4404        return (permissionList == null)
4405                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4406    }
4407
4408    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4409            int filterCallingUid, int userId) {
4410        if (!sUserManager.exists(userId)) return null;
4411        PackageSetting ps = mSettings.mPackages.get(packageName);
4412        if (ps != null) {
4413            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4414                return null;
4415            }
4416            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4417                return null;
4418            }
4419            if (ps.pkg == null) {
4420                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4421                if (pInfo != null) {
4422                    return pInfo.applicationInfo;
4423                }
4424                return null;
4425            }
4426            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4427                    ps.readUserState(userId), userId);
4428            if (ai != null) {
4429                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4430            }
4431            return ai;
4432        }
4433        return null;
4434    }
4435
4436    @Override
4437    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4438        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4439    }
4440
4441    /**
4442     * Important: The provided filterCallingUid is used exclusively to filter out applications
4443     * that can be seen based on user state. It's typically the original caller uid prior
4444     * to clearing. Because it can only be provided by trusted code, it's value can be
4445     * trusted and will be used as-is; unlike userId which will be validated by this method.
4446     */
4447    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4448            int filterCallingUid, int userId) {
4449        if (!sUserManager.exists(userId)) return null;
4450        flags = updateFlagsForApplication(flags, userId, packageName);
4451        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4452                false /* requireFullPermission */, false /* checkShell */, "get application info");
4453
4454        // writer
4455        synchronized (mPackages) {
4456            // Normalize package name to handle renamed packages and static libs
4457            packageName = resolveInternalPackageNameLPr(packageName,
4458                    PackageManager.VERSION_CODE_HIGHEST);
4459
4460            PackageParser.Package p = mPackages.get(packageName);
4461            if (DEBUG_PACKAGE_INFO) Log.v(
4462                    TAG, "getApplicationInfo " + packageName
4463                    + ": " + p);
4464            if (p != null) {
4465                PackageSetting ps = mSettings.mPackages.get(packageName);
4466                if (ps == null) return null;
4467                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4468                    return null;
4469                }
4470                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4471                    return null;
4472                }
4473                // Note: isEnabledLP() does not apply here - always return info
4474                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4475                        p, flags, ps.readUserState(userId), userId);
4476                if (ai != null) {
4477                    ai.packageName = resolveExternalPackageNameLPr(p);
4478                }
4479                return ai;
4480            }
4481            if ("android".equals(packageName)||"system".equals(packageName)) {
4482                return mAndroidApplication;
4483            }
4484            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4485                // Already generates the external package name
4486                return generateApplicationInfoFromSettingsLPw(packageName,
4487                        flags, filterCallingUid, userId);
4488            }
4489        }
4490        return null;
4491    }
4492
4493    private String normalizePackageNameLPr(String packageName) {
4494        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4495        return normalizedPackageName != null ? normalizedPackageName : packageName;
4496    }
4497
4498    @Override
4499    public void deletePreloadsFileCache() {
4500        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4501            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4502        }
4503        File dir = Environment.getDataPreloadsFileCacheDirectory();
4504        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4505        FileUtils.deleteContents(dir);
4506    }
4507
4508    @Override
4509    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4510            final int storageFlags, final IPackageDataObserver observer) {
4511        mContext.enforceCallingOrSelfPermission(
4512                android.Manifest.permission.CLEAR_APP_CACHE, null);
4513        mHandler.post(() -> {
4514            boolean success = false;
4515            try {
4516                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4517                success = true;
4518            } catch (IOException e) {
4519                Slog.w(TAG, e);
4520            }
4521            if (observer != null) {
4522                try {
4523                    observer.onRemoveCompleted(null, success);
4524                } catch (RemoteException e) {
4525                    Slog.w(TAG, e);
4526                }
4527            }
4528        });
4529    }
4530
4531    @Override
4532    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4533            final int storageFlags, final IntentSender pi) {
4534        mContext.enforceCallingOrSelfPermission(
4535                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4536        mHandler.post(() -> {
4537            boolean success = false;
4538            try {
4539                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4540                success = true;
4541            } catch (IOException e) {
4542                Slog.w(TAG, e);
4543            }
4544            if (pi != null) {
4545                try {
4546                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4547                } catch (SendIntentException e) {
4548                    Slog.w(TAG, e);
4549                }
4550            }
4551        });
4552    }
4553
4554    /**
4555     * Blocking call to clear various types of cached data across the system
4556     * until the requested bytes are available.
4557     */
4558    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4559        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4560        final File file = storage.findPathForUuid(volumeUuid);
4561        if (file.getUsableSpace() >= bytes) return;
4562
4563        if (ENABLE_FREE_CACHE_V2) {
4564            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4565                    volumeUuid);
4566            final boolean aggressive = (storageFlags
4567                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4568            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4569
4570            // 1. Pre-flight to determine if we have any chance to succeed
4571            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4572            if (internalVolume && (aggressive || SystemProperties
4573                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4574                deletePreloadsFileCache();
4575                if (file.getUsableSpace() >= bytes) return;
4576            }
4577
4578            // 3. Consider parsed APK data (aggressive only)
4579            if (internalVolume && aggressive) {
4580                FileUtils.deleteContents(mCacheDir);
4581                if (file.getUsableSpace() >= bytes) return;
4582            }
4583
4584            // 4. Consider cached app data (above quotas)
4585            try {
4586                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4587                        Installer.FLAG_FREE_CACHE_V2);
4588            } catch (InstallerException ignored) {
4589            }
4590            if (file.getUsableSpace() >= bytes) return;
4591
4592            // 5. Consider shared libraries with refcount=0 and age>min cache period
4593            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4594                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4595                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4596                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4597                return;
4598            }
4599
4600            // 6. Consider dexopt output (aggressive only)
4601            // TODO: Implement
4602
4603            // 7. Consider installed instant apps unused longer than min cache period
4604            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4605                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4606                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4607                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4608                return;
4609            }
4610
4611            // 8. Consider cached app data (below quotas)
4612            try {
4613                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4614                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4615            } catch (InstallerException ignored) {
4616            }
4617            if (file.getUsableSpace() >= bytes) return;
4618
4619            // 9. Consider DropBox entries
4620            // TODO: Implement
4621
4622            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4623            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4624                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4625                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4626                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4627                return;
4628            }
4629        } else {
4630            try {
4631                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4632            } catch (InstallerException ignored) {
4633            }
4634            if (file.getUsableSpace() >= bytes) return;
4635        }
4636
4637        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4638    }
4639
4640    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4641            throws IOException {
4642        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4643        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4644
4645        List<VersionedPackage> packagesToDelete = null;
4646        final long now = System.currentTimeMillis();
4647
4648        synchronized (mPackages) {
4649            final int[] allUsers = sUserManager.getUserIds();
4650            final int libCount = mSharedLibraries.size();
4651            for (int i = 0; i < libCount; i++) {
4652                final LongSparseArray<SharedLibraryEntry> versionedLib
4653                        = mSharedLibraries.valueAt(i);
4654                if (versionedLib == null) {
4655                    continue;
4656                }
4657                final int versionCount = versionedLib.size();
4658                for (int j = 0; j < versionCount; j++) {
4659                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4660                    // Skip packages that are not static shared libs.
4661                    if (!libInfo.isStatic()) {
4662                        break;
4663                    }
4664                    // Important: We skip static shared libs used for some user since
4665                    // in such a case we need to keep the APK on the device. The check for
4666                    // a lib being used for any user is performed by the uninstall call.
4667                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4668                    // Resolve the package name - we use synthetic package names internally
4669                    final String internalPackageName = resolveInternalPackageNameLPr(
4670                            declaringPackage.getPackageName(),
4671                            declaringPackage.getLongVersionCode());
4672                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4673                    // Skip unused static shared libs cached less than the min period
4674                    // to prevent pruning a lib needed by a subsequently installed package.
4675                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4676                        continue;
4677                    }
4678                    if (packagesToDelete == null) {
4679                        packagesToDelete = new ArrayList<>();
4680                    }
4681                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4682                            declaringPackage.getLongVersionCode()));
4683                }
4684            }
4685        }
4686
4687        if (packagesToDelete != null) {
4688            final int packageCount = packagesToDelete.size();
4689            for (int i = 0; i < packageCount; i++) {
4690                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4691                // Delete the package synchronously (will fail of the lib used for any user).
4692                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4693                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4694                                == PackageManager.DELETE_SUCCEEDED) {
4695                    if (volume.getUsableSpace() >= neededSpace) {
4696                        return true;
4697                    }
4698                }
4699            }
4700        }
4701
4702        return false;
4703    }
4704
4705    /**
4706     * Update given flags based on encryption status of current user.
4707     */
4708    private int updateFlags(int flags, int userId) {
4709        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4710                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4711            // Caller expressed an explicit opinion about what encryption
4712            // aware/unaware components they want to see, so fall through and
4713            // give them what they want
4714        } else {
4715            // Caller expressed no opinion, so match based on user state
4716            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4717                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4718            } else {
4719                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4720            }
4721        }
4722        return flags;
4723    }
4724
4725    private UserManagerInternal getUserManagerInternal() {
4726        if (mUserManagerInternal == null) {
4727            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4728        }
4729        return mUserManagerInternal;
4730    }
4731
4732    private ActivityManagerInternal getActivityManagerInternal() {
4733        if (mActivityManagerInternal == null) {
4734            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4735        }
4736        return mActivityManagerInternal;
4737    }
4738
4739
4740    private DeviceIdleController.LocalService getDeviceIdleController() {
4741        if (mDeviceIdleController == null) {
4742            mDeviceIdleController =
4743                    LocalServices.getService(DeviceIdleController.LocalService.class);
4744        }
4745        return mDeviceIdleController;
4746    }
4747
4748    /**
4749     * Update given flags when being used to request {@link PackageInfo}.
4750     */
4751    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4752        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4753        boolean triaged = true;
4754        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4755                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4756            // Caller is asking for component details, so they'd better be
4757            // asking for specific encryption matching behavior, or be triaged
4758            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4759                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4760                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4761                triaged = false;
4762            }
4763        }
4764        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4765                | PackageManager.MATCH_SYSTEM_ONLY
4766                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4767            triaged = false;
4768        }
4769        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4770            mPermissionManager.enforceCrossUserPermission(
4771                    Binder.getCallingUid(), userId, false, false,
4772                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4773                    + Debug.getCallers(5));
4774        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4775                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4776            // If the caller wants all packages and has a restricted profile associated with it,
4777            // then match all users. This is to make sure that launchers that need to access work
4778            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4779            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4780            flags |= PackageManager.MATCH_ANY_USER;
4781        }
4782        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4783            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4784                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4785        }
4786        return updateFlags(flags, userId);
4787    }
4788
4789    /**
4790     * Update given flags when being used to request {@link ApplicationInfo}.
4791     */
4792    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4793        return updateFlagsForPackage(flags, userId, cookie);
4794    }
4795
4796    /**
4797     * Update given flags when being used to request {@link ComponentInfo}.
4798     */
4799    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4800        if (cookie instanceof Intent) {
4801            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4802                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4803            }
4804        }
4805
4806        boolean triaged = true;
4807        // Caller is asking for component details, so they'd better be
4808        // asking for specific encryption matching behavior, or be triaged
4809        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4810                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4811                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4812            triaged = false;
4813        }
4814        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4815            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4816                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4817        }
4818
4819        return updateFlags(flags, userId);
4820    }
4821
4822    /**
4823     * Update given intent when being used to request {@link ResolveInfo}.
4824     */
4825    private Intent updateIntentForResolve(Intent intent) {
4826        if (intent.getSelector() != null) {
4827            intent = intent.getSelector();
4828        }
4829        if (DEBUG_PREFERRED) {
4830            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4831        }
4832        return intent;
4833    }
4834
4835    /**
4836     * Update given flags when being used to request {@link ResolveInfo}.
4837     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4838     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4839     * flag set. However, this flag is only honoured in three circumstances:
4840     * <ul>
4841     * <li>when called from a system process</li>
4842     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4843     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4844     * action and a {@code android.intent.category.BROWSABLE} category</li>
4845     * </ul>
4846     */
4847    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4848        return updateFlagsForResolve(flags, userId, intent, callingUid,
4849                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4850    }
4851    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4852            boolean wantInstantApps) {
4853        return updateFlagsForResolve(flags, userId, intent, callingUid,
4854                wantInstantApps, false /*onlyExposedExplicitly*/);
4855    }
4856    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4857            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4858        // Safe mode means we shouldn't match any third-party components
4859        if (mSafeMode) {
4860            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4861        }
4862        if (getInstantAppPackageName(callingUid) != null) {
4863            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4864            if (onlyExposedExplicitly) {
4865                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4866            }
4867            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4868            flags |= PackageManager.MATCH_INSTANT;
4869        } else {
4870            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4871            final boolean allowMatchInstant = wantInstantApps
4872                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4873            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4874                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4875            if (!allowMatchInstant) {
4876                flags &= ~PackageManager.MATCH_INSTANT;
4877            }
4878        }
4879        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4880    }
4881
4882    @Override
4883    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4884        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4885    }
4886
4887    /**
4888     * Important: The provided filterCallingUid is used exclusively to filter out activities
4889     * that can be seen based on user state. It's typically the original caller uid prior
4890     * to clearing. Because it can only be provided by trusted code, it's value can be
4891     * trusted and will be used as-is; unlike userId which will be validated by this method.
4892     */
4893    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4894            int filterCallingUid, int userId) {
4895        if (!sUserManager.exists(userId)) return null;
4896        flags = updateFlagsForComponent(flags, userId, component);
4897
4898        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4899            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4900                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4901        }
4902
4903        synchronized (mPackages) {
4904            PackageParser.Activity a = mActivities.mActivities.get(component);
4905
4906            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4907            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4908                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4909                if (ps == null) return null;
4910                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4911                    return null;
4912                }
4913                return PackageParser.generateActivityInfo(
4914                        a, flags, ps.readUserState(userId), userId);
4915            }
4916            if (mResolveComponentName.equals(component)) {
4917                return PackageParser.generateActivityInfo(
4918                        mResolveActivity, flags, new PackageUserState(), userId);
4919            }
4920        }
4921        return null;
4922    }
4923
4924    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4925        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4926            return false;
4927        }
4928        final long token = Binder.clearCallingIdentity();
4929        try {
4930            final int callingUserId = UserHandle.getUserId(callingUid);
4931            if (ActivityManager.getCurrentUser() != callingUserId) {
4932                return false;
4933            }
4934            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4935        } finally {
4936            Binder.restoreCallingIdentity(token);
4937        }
4938    }
4939
4940    @Override
4941    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4942            String resolvedType) {
4943        synchronized (mPackages) {
4944            if (component.equals(mResolveComponentName)) {
4945                // The resolver supports EVERYTHING!
4946                return true;
4947            }
4948            final int callingUid = Binder.getCallingUid();
4949            final int callingUserId = UserHandle.getUserId(callingUid);
4950            PackageParser.Activity a = mActivities.mActivities.get(component);
4951            if (a == null) {
4952                return false;
4953            }
4954            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4955            if (ps == null) {
4956                return false;
4957            }
4958            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4959                return false;
4960            }
4961            for (int i=0; i<a.intents.size(); i++) {
4962                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4963                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4964                    return true;
4965                }
4966            }
4967            return false;
4968        }
4969    }
4970
4971    @Override
4972    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4973        if (!sUserManager.exists(userId)) return null;
4974        final int callingUid = Binder.getCallingUid();
4975        flags = updateFlagsForComponent(flags, userId, component);
4976        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4977                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4978        synchronized (mPackages) {
4979            PackageParser.Activity a = mReceivers.mActivities.get(component);
4980            if (DEBUG_PACKAGE_INFO) Log.v(
4981                TAG, "getReceiverInfo " + component + ": " + a);
4982            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4983                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4984                if (ps == null) return null;
4985                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4986                    return null;
4987                }
4988                return PackageParser.generateActivityInfo(
4989                        a, flags, ps.readUserState(userId), userId);
4990            }
4991        }
4992        return null;
4993    }
4994
4995    @Override
4996    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4997            int flags, int userId) {
4998        if (!sUserManager.exists(userId)) return null;
4999        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5000        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5001            return null;
5002        }
5003
5004        flags = updateFlagsForPackage(flags, userId, null);
5005
5006        final boolean canSeeStaticLibraries =
5007                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5008                        == PERMISSION_GRANTED
5009                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5010                        == PERMISSION_GRANTED
5011                || canRequestPackageInstallsInternal(packageName,
5012                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5013                        false  /* throwIfPermNotDeclared*/)
5014                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5015                        == PERMISSION_GRANTED;
5016
5017        synchronized (mPackages) {
5018            List<SharedLibraryInfo> result = null;
5019
5020            final int libCount = mSharedLibraries.size();
5021            for (int i = 0; i < libCount; i++) {
5022                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5023                if (versionedLib == null) {
5024                    continue;
5025                }
5026
5027                final int versionCount = versionedLib.size();
5028                for (int j = 0; j < versionCount; j++) {
5029                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5030                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5031                        break;
5032                    }
5033                    final long identity = Binder.clearCallingIdentity();
5034                    try {
5035                        PackageInfo packageInfo = getPackageInfoVersioned(
5036                                libInfo.getDeclaringPackage(), flags
5037                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5038                        if (packageInfo == null) {
5039                            continue;
5040                        }
5041                    } finally {
5042                        Binder.restoreCallingIdentity(identity);
5043                    }
5044
5045                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5046                            libInfo.getLongVersion(), libInfo.getType(),
5047                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5048                            flags, userId));
5049
5050                    if (result == null) {
5051                        result = new ArrayList<>();
5052                    }
5053                    result.add(resLibInfo);
5054                }
5055            }
5056
5057            return result != null ? new ParceledListSlice<>(result) : null;
5058        }
5059    }
5060
5061    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5062            SharedLibraryInfo libInfo, int flags, int userId) {
5063        List<VersionedPackage> versionedPackages = null;
5064        final int packageCount = mSettings.mPackages.size();
5065        for (int i = 0; i < packageCount; i++) {
5066            PackageSetting ps = mSettings.mPackages.valueAt(i);
5067
5068            if (ps == null) {
5069                continue;
5070            }
5071
5072            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5073                continue;
5074            }
5075
5076            final String libName = libInfo.getName();
5077            if (libInfo.isStatic()) {
5078                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5079                if (libIdx < 0) {
5080                    continue;
5081                }
5082                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5083                    continue;
5084                }
5085                if (versionedPackages == null) {
5086                    versionedPackages = new ArrayList<>();
5087                }
5088                // If the dependent is a static shared lib, use the public package name
5089                String dependentPackageName = ps.name;
5090                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5091                    dependentPackageName = ps.pkg.manifestPackageName;
5092                }
5093                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5094            } else if (ps.pkg != null) {
5095                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5096                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5097                    if (versionedPackages == null) {
5098                        versionedPackages = new ArrayList<>();
5099                    }
5100                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5101                }
5102            }
5103        }
5104
5105        return versionedPackages;
5106    }
5107
5108    @Override
5109    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5110        if (!sUserManager.exists(userId)) return null;
5111        final int callingUid = Binder.getCallingUid();
5112        flags = updateFlagsForComponent(flags, userId, component);
5113        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5114                false /* requireFullPermission */, false /* checkShell */, "get service info");
5115        synchronized (mPackages) {
5116            PackageParser.Service s = mServices.mServices.get(component);
5117            if (DEBUG_PACKAGE_INFO) Log.v(
5118                TAG, "getServiceInfo " + component + ": " + s);
5119            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5120                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5121                if (ps == null) return null;
5122                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5123                    return null;
5124                }
5125                return PackageParser.generateServiceInfo(
5126                        s, flags, ps.readUserState(userId), userId);
5127            }
5128        }
5129        return null;
5130    }
5131
5132    @Override
5133    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5134        if (!sUserManager.exists(userId)) return null;
5135        final int callingUid = Binder.getCallingUid();
5136        flags = updateFlagsForComponent(flags, userId, component);
5137        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5138                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5139        synchronized (mPackages) {
5140            PackageParser.Provider p = mProviders.mProviders.get(component);
5141            if (DEBUG_PACKAGE_INFO) Log.v(
5142                TAG, "getProviderInfo " + component + ": " + p);
5143            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5144                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5145                if (ps == null) return null;
5146                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5147                    return null;
5148                }
5149                return PackageParser.generateProviderInfo(
5150                        p, flags, ps.readUserState(userId), userId);
5151            }
5152        }
5153        return null;
5154    }
5155
5156    @Override
5157    public String[] getSystemSharedLibraryNames() {
5158        // allow instant applications
5159        synchronized (mPackages) {
5160            Set<String> libs = null;
5161            final int libCount = mSharedLibraries.size();
5162            for (int i = 0; i < libCount; i++) {
5163                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5164                if (versionedLib == null) {
5165                    continue;
5166                }
5167                final int versionCount = versionedLib.size();
5168                for (int j = 0; j < versionCount; j++) {
5169                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5170                    if (!libEntry.info.isStatic()) {
5171                        if (libs == null) {
5172                            libs = new ArraySet<>();
5173                        }
5174                        libs.add(libEntry.info.getName());
5175                        break;
5176                    }
5177                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5178                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5179                            UserHandle.getUserId(Binder.getCallingUid()),
5180                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5181                        if (libs == null) {
5182                            libs = new ArraySet<>();
5183                        }
5184                        libs.add(libEntry.info.getName());
5185                        break;
5186                    }
5187                }
5188            }
5189
5190            if (libs != null) {
5191                String[] libsArray = new String[libs.size()];
5192                libs.toArray(libsArray);
5193                return libsArray;
5194            }
5195
5196            return null;
5197        }
5198    }
5199
5200    @Override
5201    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5202        // allow instant applications
5203        synchronized (mPackages) {
5204            return mServicesSystemSharedLibraryPackageName;
5205        }
5206    }
5207
5208    @Override
5209    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5210        // allow instant applications
5211        synchronized (mPackages) {
5212            return mSharedSystemSharedLibraryPackageName;
5213        }
5214    }
5215
5216    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5217        for (int i = userList.length - 1; i >= 0; --i) {
5218            final int userId = userList[i];
5219            // don't add instant app to the list of updates
5220            if (pkgSetting.getInstantApp(userId)) {
5221                continue;
5222            }
5223            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5224            if (changedPackages == null) {
5225                changedPackages = new SparseArray<>();
5226                mChangedPackages.put(userId, changedPackages);
5227            }
5228            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5229            if (sequenceNumbers == null) {
5230                sequenceNumbers = new HashMap<>();
5231                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5232            }
5233            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5234            if (sequenceNumber != null) {
5235                changedPackages.remove(sequenceNumber);
5236            }
5237            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5238            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5239        }
5240        mChangedPackagesSequenceNumber++;
5241    }
5242
5243    @Override
5244    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5245        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5246            return null;
5247        }
5248        synchronized (mPackages) {
5249            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5250                return null;
5251            }
5252            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5253            if (changedPackages == null) {
5254                return null;
5255            }
5256            final List<String> packageNames =
5257                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5258            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5259                final String packageName = changedPackages.get(i);
5260                if (packageName != null) {
5261                    packageNames.add(packageName);
5262                }
5263            }
5264            return packageNames.isEmpty()
5265                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5266        }
5267    }
5268
5269    @Override
5270    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5271        // allow instant applications
5272        ArrayList<FeatureInfo> res;
5273        synchronized (mAvailableFeatures) {
5274            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5275            res.addAll(mAvailableFeatures.values());
5276        }
5277        final FeatureInfo fi = new FeatureInfo();
5278        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5279                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5280        res.add(fi);
5281
5282        return new ParceledListSlice<>(res);
5283    }
5284
5285    @Override
5286    public boolean hasSystemFeature(String name, int version) {
5287        // allow instant applications
5288        synchronized (mAvailableFeatures) {
5289            final FeatureInfo feat = mAvailableFeatures.get(name);
5290            if (feat == null) {
5291                return false;
5292            } else {
5293                return feat.version >= version;
5294            }
5295        }
5296    }
5297
5298    @Override
5299    public int checkPermission(String permName, String pkgName, int userId) {
5300        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5301    }
5302
5303    @Override
5304    public int checkUidPermission(String permName, int uid) {
5305        synchronized (mPackages) {
5306            final String[] packageNames = getPackagesForUid(uid);
5307            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5308                    ? mPackages.get(packageNames[0])
5309                    : null;
5310            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5311        }
5312    }
5313
5314    @Override
5315    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5316        if (UserHandle.getCallingUserId() != userId) {
5317            mContext.enforceCallingPermission(
5318                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5319                    "isPermissionRevokedByPolicy for user " + userId);
5320        }
5321
5322        if (checkPermission(permission, packageName, userId)
5323                == PackageManager.PERMISSION_GRANTED) {
5324            return false;
5325        }
5326
5327        final int callingUid = Binder.getCallingUid();
5328        if (getInstantAppPackageName(callingUid) != null) {
5329            if (!isCallerSameApp(packageName, callingUid)) {
5330                return false;
5331            }
5332        } else {
5333            if (isInstantApp(packageName, userId)) {
5334                return false;
5335            }
5336        }
5337
5338        final long identity = Binder.clearCallingIdentity();
5339        try {
5340            final int flags = getPermissionFlags(permission, packageName, userId);
5341            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5342        } finally {
5343            Binder.restoreCallingIdentity(identity);
5344        }
5345    }
5346
5347    @Override
5348    public String getPermissionControllerPackageName() {
5349        synchronized (mPackages) {
5350            return mRequiredInstallerPackage;
5351        }
5352    }
5353
5354    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5355        return mPermissionManager.addDynamicPermission(
5356                info, async, getCallingUid(), new PermissionCallback() {
5357                    @Override
5358                    public void onPermissionChanged() {
5359                        if (!async) {
5360                            mSettings.writeLPr();
5361                        } else {
5362                            scheduleWriteSettingsLocked();
5363                        }
5364                    }
5365                });
5366    }
5367
5368    @Override
5369    public boolean addPermission(PermissionInfo info) {
5370        synchronized (mPackages) {
5371            return addDynamicPermission(info, false);
5372        }
5373    }
5374
5375    @Override
5376    public boolean addPermissionAsync(PermissionInfo info) {
5377        synchronized (mPackages) {
5378            return addDynamicPermission(info, true);
5379        }
5380    }
5381
5382    @Override
5383    public void removePermission(String permName) {
5384        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5385    }
5386
5387    @Override
5388    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5389        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5390                getCallingUid(), userId, mPermissionCallback);
5391    }
5392
5393    @Override
5394    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5395        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5396                getCallingUid(), userId, mPermissionCallback);
5397    }
5398
5399    @Override
5400    public void resetRuntimePermissions() {
5401        mContext.enforceCallingOrSelfPermission(
5402                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5403                "revokeRuntimePermission");
5404
5405        int callingUid = Binder.getCallingUid();
5406        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5407            mContext.enforceCallingOrSelfPermission(
5408                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5409                    "resetRuntimePermissions");
5410        }
5411
5412        synchronized (mPackages) {
5413            mPermissionManager.updateAllPermissions(
5414                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5415                    mPermissionCallback);
5416            for (int userId : UserManagerService.getInstance().getUserIds()) {
5417                final int packageCount = mPackages.size();
5418                for (int i = 0; i < packageCount; i++) {
5419                    PackageParser.Package pkg = mPackages.valueAt(i);
5420                    if (!(pkg.mExtras instanceof PackageSetting)) {
5421                        continue;
5422                    }
5423                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5424                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5425                }
5426            }
5427        }
5428    }
5429
5430    @Override
5431    public int getPermissionFlags(String permName, String packageName, int userId) {
5432        return mPermissionManager.getPermissionFlags(
5433                permName, packageName, getCallingUid(), userId);
5434    }
5435
5436    @Override
5437    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5438            int flagValues, int userId) {
5439        mPermissionManager.updatePermissionFlags(
5440                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5441                mPermissionCallback);
5442    }
5443
5444    /**
5445     * Update the permission flags for all packages and runtime permissions of a user in order
5446     * to allow device or profile owner to remove POLICY_FIXED.
5447     */
5448    @Override
5449    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5450        synchronized (mPackages) {
5451            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5452                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5453                    mPermissionCallback);
5454            if (changed) {
5455                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5456            }
5457        }
5458    }
5459
5460    @Override
5461    public boolean shouldShowRequestPermissionRationale(String permissionName,
5462            String packageName, int userId) {
5463        if (UserHandle.getCallingUserId() != userId) {
5464            mContext.enforceCallingPermission(
5465                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5466                    "canShowRequestPermissionRationale for user " + userId);
5467        }
5468
5469        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5470        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5471            return false;
5472        }
5473
5474        if (checkPermission(permissionName, packageName, userId)
5475                == PackageManager.PERMISSION_GRANTED) {
5476            return false;
5477        }
5478
5479        final int flags;
5480
5481        final long identity = Binder.clearCallingIdentity();
5482        try {
5483            flags = getPermissionFlags(permissionName,
5484                    packageName, userId);
5485        } finally {
5486            Binder.restoreCallingIdentity(identity);
5487        }
5488
5489        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5490                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5491                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5492
5493        if ((flags & fixedFlags) != 0) {
5494            return false;
5495        }
5496
5497        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5498    }
5499
5500    @Override
5501    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5502        mContext.enforceCallingOrSelfPermission(
5503                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5504                "addOnPermissionsChangeListener");
5505
5506        synchronized (mPackages) {
5507            mOnPermissionChangeListeners.addListenerLocked(listener);
5508        }
5509    }
5510
5511    @Override
5512    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5513        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5514            throw new SecurityException("Instant applications don't have access to this method");
5515        }
5516        synchronized (mPackages) {
5517            mOnPermissionChangeListeners.removeListenerLocked(listener);
5518        }
5519    }
5520
5521    @Override
5522    public boolean isProtectedBroadcast(String actionName) {
5523        // allow instant applications
5524        synchronized (mProtectedBroadcasts) {
5525            if (mProtectedBroadcasts.contains(actionName)) {
5526                return true;
5527            } else if (actionName != null) {
5528                // TODO: remove these terrible hacks
5529                if (actionName.startsWith("android.net.netmon.lingerExpired")
5530                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5531                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5532                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5533                    return true;
5534                }
5535            }
5536        }
5537        return false;
5538    }
5539
5540    @Override
5541    public int checkSignatures(String pkg1, String pkg2) {
5542        synchronized (mPackages) {
5543            final PackageParser.Package p1 = mPackages.get(pkg1);
5544            final PackageParser.Package p2 = mPackages.get(pkg2);
5545            if (p1 == null || p1.mExtras == null
5546                    || p2 == null || p2.mExtras == null) {
5547                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5548            }
5549            final int callingUid = Binder.getCallingUid();
5550            final int callingUserId = UserHandle.getUserId(callingUid);
5551            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5552            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5553            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5554                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5555                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5556            }
5557            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5558        }
5559    }
5560
5561    @Override
5562    public int checkUidSignatures(int uid1, int uid2) {
5563        final int callingUid = Binder.getCallingUid();
5564        final int callingUserId = UserHandle.getUserId(callingUid);
5565        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5566        // Map to base uids.
5567        uid1 = UserHandle.getAppId(uid1);
5568        uid2 = UserHandle.getAppId(uid2);
5569        // reader
5570        synchronized (mPackages) {
5571            Signature[] s1;
5572            Signature[] s2;
5573            Object obj = mSettings.getUserIdLPr(uid1);
5574            if (obj != null) {
5575                if (obj instanceof SharedUserSetting) {
5576                    if (isCallerInstantApp) {
5577                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5578                    }
5579                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5580                } else if (obj instanceof PackageSetting) {
5581                    final PackageSetting ps = (PackageSetting) obj;
5582                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5583                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5584                    }
5585                    s1 = ps.signatures.mSigningDetails.signatures;
5586                } else {
5587                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5588                }
5589            } else {
5590                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5591            }
5592            obj = mSettings.getUserIdLPr(uid2);
5593            if (obj != null) {
5594                if (obj instanceof SharedUserSetting) {
5595                    if (isCallerInstantApp) {
5596                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5597                    }
5598                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5599                } else if (obj instanceof PackageSetting) {
5600                    final PackageSetting ps = (PackageSetting) obj;
5601                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5602                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5603                    }
5604                    s2 = ps.signatures.mSigningDetails.signatures;
5605                } else {
5606                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5607                }
5608            } else {
5609                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5610            }
5611            return compareSignatures(s1, s2);
5612        }
5613    }
5614
5615    @Override
5616    public boolean hasSigningCertificate(
5617            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5618
5619        synchronized (mPackages) {
5620            final PackageParser.Package p = mPackages.get(packageName);
5621            if (p == null || p.mExtras == null) {
5622                return false;
5623            }
5624            final int callingUid = Binder.getCallingUid();
5625            final int callingUserId = UserHandle.getUserId(callingUid);
5626            final PackageSetting ps = (PackageSetting) p.mExtras;
5627            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5628                return false;
5629            }
5630            switch (type) {
5631                case CERT_INPUT_RAW_X509:
5632                    return p.mSigningDetails.hasCertificate(certificate);
5633                case CERT_INPUT_SHA256:
5634                    return p.mSigningDetails.hasSha256Certificate(certificate);
5635                default:
5636                    return false;
5637            }
5638        }
5639    }
5640
5641    @Override
5642    public boolean hasUidSigningCertificate(
5643            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5644        final int callingUid = Binder.getCallingUid();
5645        final int callingUserId = UserHandle.getUserId(callingUid);
5646        // Map to base uids.
5647        uid = UserHandle.getAppId(uid);
5648        // reader
5649        synchronized (mPackages) {
5650            final PackageParser.SigningDetails signingDetails;
5651            final Object obj = mSettings.getUserIdLPr(uid);
5652            if (obj != null) {
5653                if (obj instanceof SharedUserSetting) {
5654                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5655                    if (isCallerInstantApp) {
5656                        return false;
5657                    }
5658                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5659                } else if (obj instanceof PackageSetting) {
5660                    final PackageSetting ps = (PackageSetting) obj;
5661                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5662                        return false;
5663                    }
5664                    signingDetails = ps.signatures.mSigningDetails;
5665                } else {
5666                    return false;
5667                }
5668            } else {
5669                return false;
5670            }
5671            switch (type) {
5672                case CERT_INPUT_RAW_X509:
5673                    return signingDetails.hasCertificate(certificate);
5674                case CERT_INPUT_SHA256:
5675                    return signingDetails.hasSha256Certificate(certificate);
5676                default:
5677                    return false;
5678            }
5679        }
5680    }
5681
5682    /**
5683     * This method should typically only be used when granting or revoking
5684     * permissions, since the app may immediately restart after this call.
5685     * <p>
5686     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5687     * guard your work against the app being relaunched.
5688     */
5689    private void killUid(int appId, int userId, String reason) {
5690        final long identity = Binder.clearCallingIdentity();
5691        try {
5692            IActivityManager am = ActivityManager.getService();
5693            if (am != null) {
5694                try {
5695                    am.killUid(appId, userId, reason);
5696                } catch (RemoteException e) {
5697                    /* ignore - same process */
5698                }
5699            }
5700        } finally {
5701            Binder.restoreCallingIdentity(identity);
5702        }
5703    }
5704
5705    /**
5706     * If the database version for this type of package (internal storage or
5707     * external storage) is less than the version where package signatures
5708     * were updated, return true.
5709     */
5710    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5711        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5712        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5713    }
5714
5715    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5716        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5717        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5718    }
5719
5720    @Override
5721    public List<String> getAllPackages() {
5722        final int callingUid = Binder.getCallingUid();
5723        final int callingUserId = UserHandle.getUserId(callingUid);
5724        synchronized (mPackages) {
5725            if (canViewInstantApps(callingUid, callingUserId)) {
5726                return new ArrayList<String>(mPackages.keySet());
5727            }
5728            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5729            final List<String> result = new ArrayList<>();
5730            if (instantAppPkgName != null) {
5731                // caller is an instant application; filter unexposed applications
5732                for (PackageParser.Package pkg : mPackages.values()) {
5733                    if (!pkg.visibleToInstantApps) {
5734                        continue;
5735                    }
5736                    result.add(pkg.packageName);
5737                }
5738            } else {
5739                // caller is a normal application; filter instant applications
5740                for (PackageParser.Package pkg : mPackages.values()) {
5741                    final PackageSetting ps =
5742                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5743                    if (ps != null
5744                            && ps.getInstantApp(callingUserId)
5745                            && !mInstantAppRegistry.isInstantAccessGranted(
5746                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5747                        continue;
5748                    }
5749                    result.add(pkg.packageName);
5750                }
5751            }
5752            return result;
5753        }
5754    }
5755
5756    @Override
5757    public String[] getPackagesForUid(int uid) {
5758        final int callingUid = Binder.getCallingUid();
5759        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5760        final int userId = UserHandle.getUserId(uid);
5761        uid = UserHandle.getAppId(uid);
5762        // reader
5763        synchronized (mPackages) {
5764            Object obj = mSettings.getUserIdLPr(uid);
5765            if (obj instanceof SharedUserSetting) {
5766                if (isCallerInstantApp) {
5767                    return null;
5768                }
5769                final SharedUserSetting sus = (SharedUserSetting) obj;
5770                final int N = sus.packages.size();
5771                String[] res = new String[N];
5772                final Iterator<PackageSetting> it = sus.packages.iterator();
5773                int i = 0;
5774                while (it.hasNext()) {
5775                    PackageSetting ps = it.next();
5776                    if (ps.getInstalled(userId)) {
5777                        res[i++] = ps.name;
5778                    } else {
5779                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5780                    }
5781                }
5782                return res;
5783            } else if (obj instanceof PackageSetting) {
5784                final PackageSetting ps = (PackageSetting) obj;
5785                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5786                    return new String[]{ps.name};
5787                }
5788            }
5789        }
5790        return null;
5791    }
5792
5793    @Override
5794    public String getNameForUid(int uid) {
5795        final int callingUid = Binder.getCallingUid();
5796        if (getInstantAppPackageName(callingUid) != null) {
5797            return null;
5798        }
5799        synchronized (mPackages) {
5800            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5801            if (obj instanceof SharedUserSetting) {
5802                final SharedUserSetting sus = (SharedUserSetting) obj;
5803                return sus.name + ":" + sus.userId;
5804            } else if (obj instanceof PackageSetting) {
5805                final PackageSetting ps = (PackageSetting) obj;
5806                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5807                    return null;
5808                }
5809                return ps.name;
5810            }
5811            return null;
5812        }
5813    }
5814
5815    @Override
5816    public String[] getNamesForUids(int[] uids) {
5817        if (uids == null || uids.length == 0) {
5818            return null;
5819        }
5820        final int callingUid = Binder.getCallingUid();
5821        if (getInstantAppPackageName(callingUid) != null) {
5822            return null;
5823        }
5824        final String[] names = new String[uids.length];
5825        synchronized (mPackages) {
5826            for (int i = uids.length - 1; i >= 0; i--) {
5827                final int uid = uids[i];
5828                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5829                if (obj instanceof SharedUserSetting) {
5830                    final SharedUserSetting sus = (SharedUserSetting) obj;
5831                    names[i] = "shared:" + sus.name;
5832                } else if (obj instanceof PackageSetting) {
5833                    final PackageSetting ps = (PackageSetting) obj;
5834                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5835                        names[i] = null;
5836                    } else {
5837                        names[i] = ps.name;
5838                    }
5839                } else {
5840                    names[i] = null;
5841                }
5842            }
5843        }
5844        return names;
5845    }
5846
5847    @Override
5848    public int getUidForSharedUser(String sharedUserName) {
5849        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5850            return -1;
5851        }
5852        if (sharedUserName == null) {
5853            return -1;
5854        }
5855        // reader
5856        synchronized (mPackages) {
5857            SharedUserSetting suid;
5858            try {
5859                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5860                if (suid != null) {
5861                    return suid.userId;
5862                }
5863            } catch (PackageManagerException ignore) {
5864                // can't happen, but, still need to catch it
5865            }
5866            return -1;
5867        }
5868    }
5869
5870    @Override
5871    public int getFlagsForUid(int uid) {
5872        final int callingUid = Binder.getCallingUid();
5873        if (getInstantAppPackageName(callingUid) != null) {
5874            return 0;
5875        }
5876        synchronized (mPackages) {
5877            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5878            if (obj instanceof SharedUserSetting) {
5879                final SharedUserSetting sus = (SharedUserSetting) obj;
5880                return sus.pkgFlags;
5881            } else if (obj instanceof PackageSetting) {
5882                final PackageSetting ps = (PackageSetting) obj;
5883                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5884                    return 0;
5885                }
5886                return ps.pkgFlags;
5887            }
5888        }
5889        return 0;
5890    }
5891
5892    @Override
5893    public int getPrivateFlagsForUid(int uid) {
5894        final int callingUid = Binder.getCallingUid();
5895        if (getInstantAppPackageName(callingUid) != null) {
5896            return 0;
5897        }
5898        synchronized (mPackages) {
5899            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5900            if (obj instanceof SharedUserSetting) {
5901                final SharedUserSetting sus = (SharedUserSetting) obj;
5902                return sus.pkgPrivateFlags;
5903            } else if (obj instanceof PackageSetting) {
5904                final PackageSetting ps = (PackageSetting) obj;
5905                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5906                    return 0;
5907                }
5908                return ps.pkgPrivateFlags;
5909            }
5910        }
5911        return 0;
5912    }
5913
5914    @Override
5915    public boolean isUidPrivileged(int uid) {
5916        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5917            return false;
5918        }
5919        uid = UserHandle.getAppId(uid);
5920        // reader
5921        synchronized (mPackages) {
5922            Object obj = mSettings.getUserIdLPr(uid);
5923            if (obj instanceof SharedUserSetting) {
5924                final SharedUserSetting sus = (SharedUserSetting) obj;
5925                final Iterator<PackageSetting> it = sus.packages.iterator();
5926                while (it.hasNext()) {
5927                    if (it.next().isPrivileged()) {
5928                        return true;
5929                    }
5930                }
5931            } else if (obj instanceof PackageSetting) {
5932                final PackageSetting ps = (PackageSetting) obj;
5933                return ps.isPrivileged();
5934            }
5935        }
5936        return false;
5937    }
5938
5939    @Override
5940    public String[] getAppOpPermissionPackages(String permName) {
5941        return mPermissionManager.getAppOpPermissionPackages(permName);
5942    }
5943
5944    @Override
5945    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5946            int flags, int userId) {
5947        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5948                Binder.getCallingUid());
5949    }
5950
5951    /**
5952     * Normally instant apps can only be resolved when they're visible to the caller.
5953     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5954     * since we need to allow the system to start any installed application.
5955     */
5956    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5957            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5958        try {
5959            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5960
5961            if (!sUserManager.exists(userId)) return null;
5962            final int callingUid = Binder.getCallingUid();
5963            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5964            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5965                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5966
5967            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5968            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5969                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5970            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5971
5972            final ResolveInfo bestChoice =
5973                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5974            return bestChoice;
5975        } finally {
5976            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5977        }
5978    }
5979
5980    @Override
5981    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5982        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5983            throw new SecurityException(
5984                    "findPersistentPreferredActivity can only be run by the system");
5985        }
5986        if (!sUserManager.exists(userId)) {
5987            return null;
5988        }
5989        final int callingUid = Binder.getCallingUid();
5990        intent = updateIntentForResolve(intent);
5991        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5992        final int flags = updateFlagsForResolve(
5993                0, userId, intent, callingUid, false /*includeInstantApps*/);
5994        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5995                userId);
5996        synchronized (mPackages) {
5997            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5998                    userId);
5999        }
6000    }
6001
6002    @Override
6003    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6004            IntentFilter filter, int match, ComponentName activity) {
6005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6006            return;
6007        }
6008        final int userId = UserHandle.getCallingUserId();
6009        if (DEBUG_PREFERRED) {
6010            Log.v(TAG, "setLastChosenActivity intent=" + intent
6011                + " resolvedType=" + resolvedType
6012                + " flags=" + flags
6013                + " filter=" + filter
6014                + " match=" + match
6015                + " activity=" + activity);
6016            filter.dump(new PrintStreamPrinter(System.out), "    ");
6017        }
6018        intent.setComponent(null);
6019        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6020                userId);
6021        // Find any earlier preferred or last chosen entries and nuke them
6022        findPreferredActivity(intent, resolvedType,
6023                flags, query, 0, false, true, false, userId);
6024        // Add the new activity as the last chosen for this filter
6025        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6026                "Setting last chosen");
6027    }
6028
6029    @Override
6030    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6031        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6032            return null;
6033        }
6034        final int userId = UserHandle.getCallingUserId();
6035        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6036        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6037                userId);
6038        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6039                false, false, false, userId);
6040    }
6041
6042    /**
6043     * Returns whether or not instant apps have been disabled remotely.
6044     */
6045    private boolean areWebInstantAppsDisabled() {
6046        return mWebInstantAppsDisabled;
6047    }
6048
6049    private boolean isInstantAppResolutionAllowed(
6050            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6051            boolean skipPackageCheck) {
6052        if (mInstantAppResolverConnection == null) {
6053            return false;
6054        }
6055        if (mInstantAppInstallerActivity == null) {
6056            return false;
6057        }
6058        if (intent.getComponent() != null) {
6059            return false;
6060        }
6061        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6062            return false;
6063        }
6064        if (!skipPackageCheck && intent.getPackage() != null) {
6065            return false;
6066        }
6067        if (!intent.isWebIntent()) {
6068            // for non web intents, we should not resolve externally if an app already exists to
6069            // handle it or if the caller didn't explicitly request it.
6070            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6071                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6072                return false;
6073            }
6074        } else {
6075            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6076                return false;
6077            } else if (areWebInstantAppsDisabled()) {
6078                return false;
6079            }
6080        }
6081        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6082        // Or if there's already an ephemeral app installed that handles the action
6083        synchronized (mPackages) {
6084            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6085            for (int n = 0; n < count; n++) {
6086                final ResolveInfo info = resolvedActivities.get(n);
6087                final String packageName = info.activityInfo.packageName;
6088                final PackageSetting ps = mSettings.mPackages.get(packageName);
6089                if (ps != null) {
6090                    // only check domain verification status if the app is not a browser
6091                    if (!info.handleAllWebDataURI) {
6092                        // Try to get the status from User settings first
6093                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6094                        final int status = (int) (packedStatus >> 32);
6095                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6096                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6097                            if (DEBUG_INSTANT) {
6098                                Slog.v(TAG, "DENY instant app;"
6099                                    + " pkg: " + packageName + ", status: " + status);
6100                            }
6101                            return false;
6102                        }
6103                    }
6104                    if (ps.getInstantApp(userId)) {
6105                        if (DEBUG_INSTANT) {
6106                            Slog.v(TAG, "DENY instant app installed;"
6107                                    + " pkg: " + packageName);
6108                        }
6109                        return false;
6110                    }
6111                }
6112            }
6113        }
6114        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6115        return true;
6116    }
6117
6118    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6119            Intent origIntent, String resolvedType, String callingPackage,
6120            Bundle verificationBundle, int userId) {
6121        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6122                new InstantAppRequest(responseObj, origIntent, resolvedType,
6123                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6124        mHandler.sendMessage(msg);
6125    }
6126
6127    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6128            int flags, List<ResolveInfo> query, int userId) {
6129        if (query != null) {
6130            final int N = query.size();
6131            if (N == 1) {
6132                return query.get(0);
6133            } else if (N > 1) {
6134                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6135                // If there is more than one activity with the same priority,
6136                // then let the user decide between them.
6137                ResolveInfo r0 = query.get(0);
6138                ResolveInfo r1 = query.get(1);
6139                if (DEBUG_INTENT_MATCHING || debug) {
6140                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6141                            + r1.activityInfo.name + "=" + r1.priority);
6142                }
6143                // If the first activity has a higher priority, or a different
6144                // default, then it is always desirable to pick it.
6145                if (r0.priority != r1.priority
6146                        || r0.preferredOrder != r1.preferredOrder
6147                        || r0.isDefault != r1.isDefault) {
6148                    return query.get(0);
6149                }
6150                // If we have saved a preference for a preferred activity for
6151                // this Intent, use that.
6152                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6153                        flags, query, r0.priority, true, false, debug, userId);
6154                if (ri != null) {
6155                    return ri;
6156                }
6157                // If we have an ephemeral app, use it
6158                for (int i = 0; i < N; i++) {
6159                    ri = query.get(i);
6160                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6161                        final String packageName = ri.activityInfo.packageName;
6162                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6163                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6164                        final int status = (int)(packedStatus >> 32);
6165                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6166                            return ri;
6167                        }
6168                    }
6169                }
6170                ri = new ResolveInfo(mResolveInfo);
6171                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6172                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6173                // If all of the options come from the same package, show the application's
6174                // label and icon instead of the generic resolver's.
6175                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6176                // and then throw away the ResolveInfo itself, meaning that the caller loses
6177                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6178                // a fallback for this case; we only set the target package's resources on
6179                // the ResolveInfo, not the ActivityInfo.
6180                final String intentPackage = intent.getPackage();
6181                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6182                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6183                    ri.resolvePackageName = intentPackage;
6184                    if (userNeedsBadging(userId)) {
6185                        ri.noResourceId = true;
6186                    } else {
6187                        ri.icon = appi.icon;
6188                    }
6189                    ri.iconResourceId = appi.icon;
6190                    ri.labelRes = appi.labelRes;
6191                }
6192                ri.activityInfo.applicationInfo = new ApplicationInfo(
6193                        ri.activityInfo.applicationInfo);
6194                if (userId != 0) {
6195                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6196                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6197                }
6198                // Make sure that the resolver is displayable in car mode
6199                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6200                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6201                return ri;
6202            }
6203        }
6204        return null;
6205    }
6206
6207    /**
6208     * Return true if the given list is not empty and all of its contents have
6209     * an activityInfo with the given package name.
6210     */
6211    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6212        if (ArrayUtils.isEmpty(list)) {
6213            return false;
6214        }
6215        for (int i = 0, N = list.size(); i < N; i++) {
6216            final ResolveInfo ri = list.get(i);
6217            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6218            if (ai == null || !packageName.equals(ai.packageName)) {
6219                return false;
6220            }
6221        }
6222        return true;
6223    }
6224
6225    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6226            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6227        final int N = query.size();
6228        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6229                .get(userId);
6230        // Get the list of persistent preferred activities that handle the intent
6231        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6232        List<PersistentPreferredActivity> pprefs = ppir != null
6233                ? ppir.queryIntent(intent, resolvedType,
6234                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6235                        userId)
6236                : null;
6237        if (pprefs != null && pprefs.size() > 0) {
6238            final int M = pprefs.size();
6239            for (int i=0; i<M; i++) {
6240                final PersistentPreferredActivity ppa = pprefs.get(i);
6241                if (DEBUG_PREFERRED || debug) {
6242                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6243                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6244                            + "\n  component=" + ppa.mComponent);
6245                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6246                }
6247                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6248                        flags | MATCH_DISABLED_COMPONENTS, userId);
6249                if (DEBUG_PREFERRED || debug) {
6250                    Slog.v(TAG, "Found persistent preferred activity:");
6251                    if (ai != null) {
6252                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6253                    } else {
6254                        Slog.v(TAG, "  null");
6255                    }
6256                }
6257                if (ai == null) {
6258                    // This previously registered persistent preferred activity
6259                    // component is no longer known. Ignore it and do NOT remove it.
6260                    continue;
6261                }
6262                for (int j=0; j<N; j++) {
6263                    final ResolveInfo ri = query.get(j);
6264                    if (!ri.activityInfo.applicationInfo.packageName
6265                            .equals(ai.applicationInfo.packageName)) {
6266                        continue;
6267                    }
6268                    if (!ri.activityInfo.name.equals(ai.name)) {
6269                        continue;
6270                    }
6271                    //  Found a persistent preference that can handle the intent.
6272                    if (DEBUG_PREFERRED || debug) {
6273                        Slog.v(TAG, "Returning persistent preferred activity: " +
6274                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6275                    }
6276                    return ri;
6277                }
6278            }
6279        }
6280        return null;
6281    }
6282
6283    // TODO: handle preferred activities missing while user has amnesia
6284    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6285            List<ResolveInfo> query, int priority, boolean always,
6286            boolean removeMatches, boolean debug, int userId) {
6287        if (!sUserManager.exists(userId)) return null;
6288        final int callingUid = Binder.getCallingUid();
6289        flags = updateFlagsForResolve(
6290                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6291        intent = updateIntentForResolve(intent);
6292        // writer
6293        synchronized (mPackages) {
6294            // Try to find a matching persistent preferred activity.
6295            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6296                    debug, userId);
6297
6298            // If a persistent preferred activity matched, use it.
6299            if (pri != null) {
6300                return pri;
6301            }
6302
6303            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6304            // Get the list of preferred activities that handle the intent
6305            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6306            List<PreferredActivity> prefs = pir != null
6307                    ? pir.queryIntent(intent, resolvedType,
6308                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6309                            userId)
6310                    : null;
6311            if (prefs != null && prefs.size() > 0) {
6312                boolean changed = false;
6313                try {
6314                    // First figure out how good the original match set is.
6315                    // We will only allow preferred activities that came
6316                    // from the same match quality.
6317                    int match = 0;
6318
6319                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6320
6321                    final int N = query.size();
6322                    for (int j=0; j<N; j++) {
6323                        final ResolveInfo ri = query.get(j);
6324                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6325                                + ": 0x" + Integer.toHexString(match));
6326                        if (ri.match > match) {
6327                            match = ri.match;
6328                        }
6329                    }
6330
6331                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6332                            + Integer.toHexString(match));
6333
6334                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6335                    final int M = prefs.size();
6336                    for (int i=0; i<M; i++) {
6337                        final PreferredActivity pa = prefs.get(i);
6338                        if (DEBUG_PREFERRED || debug) {
6339                            Slog.v(TAG, "Checking PreferredActivity ds="
6340                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6341                                    + "\n  component=" + pa.mPref.mComponent);
6342                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6343                        }
6344                        if (pa.mPref.mMatch != match) {
6345                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6346                                    + Integer.toHexString(pa.mPref.mMatch));
6347                            continue;
6348                        }
6349                        // If it's not an "always" type preferred activity and that's what we're
6350                        // looking for, skip it.
6351                        if (always && !pa.mPref.mAlways) {
6352                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6353                            continue;
6354                        }
6355                        final ActivityInfo ai = getActivityInfo(
6356                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6357                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6358                                userId);
6359                        if (DEBUG_PREFERRED || debug) {
6360                            Slog.v(TAG, "Found preferred activity:");
6361                            if (ai != null) {
6362                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6363                            } else {
6364                                Slog.v(TAG, "  null");
6365                            }
6366                        }
6367                        if (ai == null) {
6368                            // This previously registered preferred activity
6369                            // component is no longer known.  Most likely an update
6370                            // to the app was installed and in the new version this
6371                            // component no longer exists.  Clean it up by removing
6372                            // it from the preferred activities list, and skip it.
6373                            Slog.w(TAG, "Removing dangling preferred activity: "
6374                                    + pa.mPref.mComponent);
6375                            pir.removeFilter(pa);
6376                            changed = true;
6377                            continue;
6378                        }
6379                        for (int j=0; j<N; j++) {
6380                            final ResolveInfo ri = query.get(j);
6381                            if (!ri.activityInfo.applicationInfo.packageName
6382                                    .equals(ai.applicationInfo.packageName)) {
6383                                continue;
6384                            }
6385                            if (!ri.activityInfo.name.equals(ai.name)) {
6386                                continue;
6387                            }
6388
6389                            if (removeMatches) {
6390                                pir.removeFilter(pa);
6391                                changed = true;
6392                                if (DEBUG_PREFERRED) {
6393                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6394                                }
6395                                break;
6396                            }
6397
6398                            // Okay we found a previously set preferred or last chosen app.
6399                            // If the result set is different from when this
6400                            // was created, and is not a subset of the preferred set, we need to
6401                            // clear it and re-ask the user their preference, if we're looking for
6402                            // an "always" type entry.
6403                            if (always && !pa.mPref.sameSet(query)) {
6404                                if (pa.mPref.isSuperset(query)) {
6405                                    // some components of the set are no longer present in
6406                                    // the query, but the preferred activity can still be reused
6407                                    if (DEBUG_PREFERRED) {
6408                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6409                                                + " still valid as only non-preferred components"
6410                                                + " were removed for " + intent + " type "
6411                                                + resolvedType);
6412                                    }
6413                                    // remove obsolete components and re-add the up-to-date filter
6414                                    PreferredActivity freshPa = new PreferredActivity(pa,
6415                                            pa.mPref.mMatch,
6416                                            pa.mPref.discardObsoleteComponents(query),
6417                                            pa.mPref.mComponent,
6418                                            pa.mPref.mAlways);
6419                                    pir.removeFilter(pa);
6420                                    pir.addFilter(freshPa);
6421                                    changed = true;
6422                                } else {
6423                                    Slog.i(TAG,
6424                                            "Result set changed, dropping preferred activity for "
6425                                                    + intent + " type " + resolvedType);
6426                                    if (DEBUG_PREFERRED) {
6427                                        Slog.v(TAG, "Removing preferred activity since set changed "
6428                                                + pa.mPref.mComponent);
6429                                    }
6430                                    pir.removeFilter(pa);
6431                                    // Re-add the filter as a "last chosen" entry (!always)
6432                                    PreferredActivity lastChosen = new PreferredActivity(
6433                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6434                                    pir.addFilter(lastChosen);
6435                                    changed = true;
6436                                    return null;
6437                                }
6438                            }
6439
6440                            // Yay! Either the set matched or we're looking for the last chosen
6441                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6442                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6443                            return ri;
6444                        }
6445                    }
6446                } finally {
6447                    if (changed) {
6448                        if (DEBUG_PREFERRED) {
6449                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6450                        }
6451                        scheduleWritePackageRestrictionsLocked(userId);
6452                    }
6453                }
6454            }
6455        }
6456        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6457        return null;
6458    }
6459
6460    /*
6461     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6462     */
6463    @Override
6464    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6465            int targetUserId) {
6466        mContext.enforceCallingOrSelfPermission(
6467                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6468        List<CrossProfileIntentFilter> matches =
6469                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6470        if (matches != null) {
6471            int size = matches.size();
6472            for (int i = 0; i < size; i++) {
6473                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6474            }
6475        }
6476        if (intent.hasWebURI()) {
6477            // cross-profile app linking works only towards the parent.
6478            final int callingUid = Binder.getCallingUid();
6479            final UserInfo parent = getProfileParent(sourceUserId);
6480            synchronized(mPackages) {
6481                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6482                        false /*includeInstantApps*/);
6483                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6484                        intent, resolvedType, flags, sourceUserId, parent.id);
6485                return xpDomainInfo != null;
6486            }
6487        }
6488        return false;
6489    }
6490
6491    private UserInfo getProfileParent(int userId) {
6492        final long identity = Binder.clearCallingIdentity();
6493        try {
6494            return sUserManager.getProfileParent(userId);
6495        } finally {
6496            Binder.restoreCallingIdentity(identity);
6497        }
6498    }
6499
6500    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6501            String resolvedType, int userId) {
6502        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6503        if (resolver != null) {
6504            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6505        }
6506        return null;
6507    }
6508
6509    @Override
6510    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6511            String resolvedType, int flags, int userId) {
6512        try {
6513            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6514
6515            return new ParceledListSlice<>(
6516                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6517        } finally {
6518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6519        }
6520    }
6521
6522    /**
6523     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6524     * instant, returns {@code null}.
6525     */
6526    private String getInstantAppPackageName(int callingUid) {
6527        synchronized (mPackages) {
6528            // If the caller is an isolated app use the owner's uid for the lookup.
6529            if (Process.isIsolated(callingUid)) {
6530                callingUid = mIsolatedOwners.get(callingUid);
6531            }
6532            final int appId = UserHandle.getAppId(callingUid);
6533            final Object obj = mSettings.getUserIdLPr(appId);
6534            if (obj instanceof PackageSetting) {
6535                final PackageSetting ps = (PackageSetting) obj;
6536                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6537                return isInstantApp ? ps.pkg.packageName : null;
6538            }
6539        }
6540        return null;
6541    }
6542
6543    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6544            String resolvedType, int flags, int userId) {
6545        return queryIntentActivitiesInternal(
6546                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6547                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6548    }
6549
6550    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6551            String resolvedType, int flags, int filterCallingUid, int userId,
6552            boolean resolveForStart, boolean allowDynamicSplits) {
6553        if (!sUserManager.exists(userId)) return Collections.emptyList();
6554        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6555        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6556                false /* requireFullPermission */, false /* checkShell */,
6557                "query intent activities");
6558        final String pkgName = intent.getPackage();
6559        ComponentName comp = intent.getComponent();
6560        if (comp == null) {
6561            if (intent.getSelector() != null) {
6562                intent = intent.getSelector();
6563                comp = intent.getComponent();
6564            }
6565        }
6566
6567        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6568                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6569        if (comp != null) {
6570            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6571            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6572            if (ai != null) {
6573                // When specifying an explicit component, we prevent the activity from being
6574                // used when either 1) the calling package is normal and the activity is within
6575                // an ephemeral application or 2) the calling package is ephemeral and the
6576                // activity is not visible to ephemeral applications.
6577                final boolean matchInstantApp =
6578                        (flags & PackageManager.MATCH_INSTANT) != 0;
6579                final boolean matchVisibleToInstantAppOnly =
6580                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6581                final boolean matchExplicitlyVisibleOnly =
6582                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6583                final boolean isCallerInstantApp =
6584                        instantAppPkgName != null;
6585                final boolean isTargetSameInstantApp =
6586                        comp.getPackageName().equals(instantAppPkgName);
6587                final boolean isTargetInstantApp =
6588                        (ai.applicationInfo.privateFlags
6589                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6590                final boolean isTargetVisibleToInstantApp =
6591                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6592                final boolean isTargetExplicitlyVisibleToInstantApp =
6593                        isTargetVisibleToInstantApp
6594                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6595                final boolean isTargetHiddenFromInstantApp =
6596                        !isTargetVisibleToInstantApp
6597                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6598                final boolean blockResolution =
6599                        !isTargetSameInstantApp
6600                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6601                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6602                                        && isTargetHiddenFromInstantApp));
6603                if (!blockResolution) {
6604                    final ResolveInfo ri = new ResolveInfo();
6605                    ri.activityInfo = ai;
6606                    list.add(ri);
6607                }
6608            }
6609            return applyPostResolutionFilter(
6610                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6611        }
6612
6613        // reader
6614        boolean sortResult = false;
6615        boolean addInstant = false;
6616        List<ResolveInfo> result;
6617        synchronized (mPackages) {
6618            if (pkgName == null) {
6619                List<CrossProfileIntentFilter> matchingFilters =
6620                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6621                // Check for results that need to skip the current profile.
6622                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6623                        resolvedType, flags, userId);
6624                if (xpResolveInfo != null) {
6625                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6626                    xpResult.add(xpResolveInfo);
6627                    return applyPostResolutionFilter(
6628                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6629                            allowDynamicSplits, filterCallingUid, userId, intent);
6630                }
6631
6632                // Check for results in the current profile.
6633                result = filterIfNotSystemUser(mActivities.queryIntent(
6634                        intent, resolvedType, flags, userId), userId);
6635                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6636                        false /*skipPackageCheck*/);
6637                // Check for cross profile results.
6638                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6639                xpResolveInfo = queryCrossProfileIntents(
6640                        matchingFilters, intent, resolvedType, flags, userId,
6641                        hasNonNegativePriorityResult);
6642                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6643                    boolean isVisibleToUser = filterIfNotSystemUser(
6644                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6645                    if (isVisibleToUser) {
6646                        result.add(xpResolveInfo);
6647                        sortResult = true;
6648                    }
6649                }
6650                if (intent.hasWebURI()) {
6651                    CrossProfileDomainInfo xpDomainInfo = null;
6652                    final UserInfo parent = getProfileParent(userId);
6653                    if (parent != null) {
6654                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6655                                flags, userId, parent.id);
6656                    }
6657                    if (xpDomainInfo != null) {
6658                        if (xpResolveInfo != null) {
6659                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6660                            // in the result.
6661                            result.remove(xpResolveInfo);
6662                        }
6663                        if (result.size() == 0 && !addInstant) {
6664                            // No result in current profile, but found candidate in parent user.
6665                            // And we are not going to add emphemeral app, so we can return the
6666                            // result straight away.
6667                            result.add(xpDomainInfo.resolveInfo);
6668                            return applyPostResolutionFilter(result, instantAppPkgName,
6669                                    allowDynamicSplits, filterCallingUid, userId, intent);
6670                        }
6671                    } else if (result.size() <= 1 && !addInstant) {
6672                        // No result in parent user and <= 1 result in current profile, and we
6673                        // are not going to add emphemeral app, so we can return the result without
6674                        // further processing.
6675                        return applyPostResolutionFilter(result, instantAppPkgName,
6676                                allowDynamicSplits, filterCallingUid, userId, intent);
6677                    }
6678                    // We have more than one candidate (combining results from current and parent
6679                    // profile), so we need filtering and sorting.
6680                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6681                            intent, flags, result, xpDomainInfo, userId);
6682                    sortResult = true;
6683                }
6684            } else {
6685                final PackageParser.Package pkg = mPackages.get(pkgName);
6686                result = null;
6687                if (pkg != null) {
6688                    result = filterIfNotSystemUser(
6689                            mActivities.queryIntentForPackage(
6690                                    intent, resolvedType, flags, pkg.activities, userId),
6691                            userId);
6692                }
6693                if (result == null || result.size() == 0) {
6694                    // the caller wants to resolve for a particular package; however, there
6695                    // were no installed results, so, try to find an ephemeral result
6696                    addInstant = isInstantAppResolutionAllowed(
6697                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6698                    if (result == null) {
6699                        result = new ArrayList<>();
6700                    }
6701                }
6702            }
6703        }
6704        if (addInstant) {
6705            result = maybeAddInstantAppInstaller(
6706                    result, intent, resolvedType, flags, userId, resolveForStart);
6707        }
6708        if (sortResult) {
6709            Collections.sort(result, mResolvePrioritySorter);
6710        }
6711        return applyPostResolutionFilter(
6712                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6713    }
6714
6715    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6716            String resolvedType, int flags, int userId, boolean resolveForStart) {
6717        // first, check to see if we've got an instant app already installed
6718        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6719        ResolveInfo localInstantApp = null;
6720        boolean blockResolution = false;
6721        if (!alreadyResolvedLocally) {
6722            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6723                    flags
6724                        | PackageManager.GET_RESOLVED_FILTER
6725                        | PackageManager.MATCH_INSTANT
6726                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6727                    userId);
6728            for (int i = instantApps.size() - 1; i >= 0; --i) {
6729                final ResolveInfo info = instantApps.get(i);
6730                final String packageName = info.activityInfo.packageName;
6731                final PackageSetting ps = mSettings.mPackages.get(packageName);
6732                if (ps.getInstantApp(userId)) {
6733                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6734                    final int status = (int)(packedStatus >> 32);
6735                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6736                        // there's a local instant application installed, but, the user has
6737                        // chosen to never use it; skip resolution and don't acknowledge
6738                        // an instant application is even available
6739                        if (DEBUG_INSTANT) {
6740                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6741                        }
6742                        blockResolution = true;
6743                        break;
6744                    } else {
6745                        // we have a locally installed instant application; skip resolution
6746                        // but acknowledge there's an instant application available
6747                        if (DEBUG_INSTANT) {
6748                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6749                        }
6750                        localInstantApp = info;
6751                        break;
6752                    }
6753                }
6754            }
6755        }
6756        // no app installed, let's see if one's available
6757        AuxiliaryResolveInfo auxiliaryResponse = null;
6758        if (!blockResolution) {
6759            if (localInstantApp == null) {
6760                // we don't have an instant app locally, resolve externally
6761                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6762                final InstantAppRequest requestObject = new InstantAppRequest(
6763                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6764                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6765                        resolveForStart);
6766                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6767                        mInstantAppResolverConnection, requestObject);
6768                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6769            } else {
6770                // we have an instant application locally, but, we can't admit that since
6771                // callers shouldn't be able to determine prior browsing. create a dummy
6772                // auxiliary response so the downstream code behaves as if there's an
6773                // instant application available externally. when it comes time to start
6774                // the instant application, we'll do the right thing.
6775                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6776                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6777                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6778            }
6779        }
6780        if (intent.isWebIntent() && auxiliaryResponse == null) {
6781            return result;
6782        }
6783        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6784        if (ps == null
6785                || ps.getUserState().get(userId) == null
6786                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6787            return result;
6788        }
6789        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6790        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6791                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6792        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6793                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6794        // add a non-generic filter
6795        ephemeralInstaller.filter = new IntentFilter();
6796        if (intent.getAction() != null) {
6797            ephemeralInstaller.filter.addAction(intent.getAction());
6798        }
6799        if (intent.getData() != null && intent.getData().getPath() != null) {
6800            ephemeralInstaller.filter.addDataPath(
6801                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6802        }
6803        ephemeralInstaller.isInstantAppAvailable = true;
6804        // make sure this resolver is the default
6805        ephemeralInstaller.isDefault = true;
6806        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6807        if (DEBUG_INSTANT) {
6808            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6809        }
6810
6811        result.add(ephemeralInstaller);
6812        return result;
6813    }
6814
6815    private static class CrossProfileDomainInfo {
6816        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6817        ResolveInfo resolveInfo;
6818        /* Best domain verification status of the activities found in the other profile */
6819        int bestDomainVerificationStatus;
6820    }
6821
6822    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6823            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6824        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6825                sourceUserId)) {
6826            return null;
6827        }
6828        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6829                resolvedType, flags, parentUserId);
6830
6831        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6832            return null;
6833        }
6834        CrossProfileDomainInfo result = null;
6835        int size = resultTargetUser.size();
6836        for (int i = 0; i < size; i++) {
6837            ResolveInfo riTargetUser = resultTargetUser.get(i);
6838            // Intent filter verification is only for filters that specify a host. So don't return
6839            // those that handle all web uris.
6840            if (riTargetUser.handleAllWebDataURI) {
6841                continue;
6842            }
6843            String packageName = riTargetUser.activityInfo.packageName;
6844            PackageSetting ps = mSettings.mPackages.get(packageName);
6845            if (ps == null) {
6846                continue;
6847            }
6848            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6849            int status = (int)(verificationState >> 32);
6850            if (result == null) {
6851                result = new CrossProfileDomainInfo();
6852                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6853                        sourceUserId, parentUserId);
6854                result.bestDomainVerificationStatus = status;
6855            } else {
6856                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6857                        result.bestDomainVerificationStatus);
6858            }
6859        }
6860        // Don't consider matches with status NEVER across profiles.
6861        if (result != null && result.bestDomainVerificationStatus
6862                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6863            return null;
6864        }
6865        return result;
6866    }
6867
6868    /**
6869     * Verification statuses are ordered from the worse to the best, except for
6870     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6871     */
6872    private int bestDomainVerificationStatus(int status1, int status2) {
6873        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6874            return status2;
6875        }
6876        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6877            return status1;
6878        }
6879        return (int) MathUtils.max(status1, status2);
6880    }
6881
6882    private boolean isUserEnabled(int userId) {
6883        long callingId = Binder.clearCallingIdentity();
6884        try {
6885            UserInfo userInfo = sUserManager.getUserInfo(userId);
6886            return userInfo != null && userInfo.isEnabled();
6887        } finally {
6888            Binder.restoreCallingIdentity(callingId);
6889        }
6890    }
6891
6892    /**
6893     * Filter out activities with systemUserOnly flag set, when current user is not System.
6894     *
6895     * @return filtered list
6896     */
6897    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6898        if (userId == UserHandle.USER_SYSTEM) {
6899            return resolveInfos;
6900        }
6901        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6902            ResolveInfo info = resolveInfos.get(i);
6903            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6904                resolveInfos.remove(i);
6905            }
6906        }
6907        return resolveInfos;
6908    }
6909
6910    /**
6911     * Filters out ephemeral activities.
6912     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6913     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6914     *
6915     * @param resolveInfos The pre-filtered list of resolved activities
6916     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6917     *          is performed.
6918     * @param intent
6919     * @return A filtered list of resolved activities.
6920     */
6921    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6922            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6923            Intent intent) {
6924        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6925        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6926            final ResolveInfo info = resolveInfos.get(i);
6927            // remove locally resolved instant app web results when disabled
6928            if (info.isInstantAppAvailable && blockInstant) {
6929                resolveInfos.remove(i);
6930                continue;
6931            }
6932            // allow activities that are defined in the provided package
6933            if (allowDynamicSplits
6934                    && info.activityInfo != null
6935                    && info.activityInfo.splitName != null
6936                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6937                            info.activityInfo.splitName)) {
6938                if (mInstantAppInstallerActivity == null) {
6939                    if (DEBUG_INSTALL) {
6940                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6941                    }
6942                    resolveInfos.remove(i);
6943                    continue;
6944                }
6945                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6946                    resolveInfos.remove(i);
6947                    continue;
6948                }
6949                // requested activity is defined in a split that hasn't been installed yet.
6950                // add the installer to the resolve list
6951                if (DEBUG_INSTALL) {
6952                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6953                }
6954                final ResolveInfo installerInfo = new ResolveInfo(
6955                        mInstantAppInstallerInfo);
6956                final ComponentName installFailureActivity = findInstallFailureActivity(
6957                        info.activityInfo.packageName,  filterCallingUid, userId);
6958                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6959                        installFailureActivity,
6960                        info.activityInfo.packageName,
6961                        info.activityInfo.applicationInfo.longVersionCode,
6962                        info.activityInfo.splitName);
6963                // add a non-generic filter
6964                installerInfo.filter = new IntentFilter();
6965
6966                // This resolve info may appear in the chooser UI, so let us make it
6967                // look as the one it replaces as far as the user is concerned which
6968                // requires loading the correct label and icon for the resolve info.
6969                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6970                installerInfo.labelRes = info.resolveLabelResId();
6971                installerInfo.icon = info.resolveIconResId();
6972                installerInfo.isInstantAppAvailable = true;
6973                resolveInfos.set(i, installerInfo);
6974                continue;
6975            }
6976            // caller is a full app, don't need to apply any other filtering
6977            if (ephemeralPkgName == null) {
6978                continue;
6979            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6980                // caller is same app; don't need to apply any other filtering
6981                continue;
6982            }
6983            // allow activities that have been explicitly exposed to ephemeral apps
6984            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6985            if (!isEphemeralApp
6986                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6987                continue;
6988            }
6989            resolveInfos.remove(i);
6990        }
6991        return resolveInfos;
6992    }
6993
6994    /**
6995     * Returns the activity component that can handle install failures.
6996     * <p>By default, the instant application installer handles failures. However, an
6997     * application may want to handle failures on its own. Applications do this by
6998     * creating an activity with an intent filter that handles the action
6999     * {@link Intent#ACTION_INSTALL_FAILURE}.
7000     */
7001    private @Nullable ComponentName findInstallFailureActivity(
7002            String packageName, int filterCallingUid, int userId) {
7003        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7004        failureActivityIntent.setPackage(packageName);
7005        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7006        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7007                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7008                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7009        final int NR = result.size();
7010        if (NR > 0) {
7011            for (int i = 0; i < NR; i++) {
7012                final ResolveInfo info = result.get(i);
7013                if (info.activityInfo.splitName != null) {
7014                    continue;
7015                }
7016                return new ComponentName(packageName, info.activityInfo.name);
7017            }
7018        }
7019        return null;
7020    }
7021
7022    /**
7023     * @param resolveInfos list of resolve infos in descending priority order
7024     * @return if the list contains a resolve info with non-negative priority
7025     */
7026    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7027        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7028    }
7029
7030    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7031            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7032            int userId) {
7033        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7034
7035        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7036            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7037                    candidates.size());
7038        }
7039
7040        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7041        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7042        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7043        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7044        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7045        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7046
7047        synchronized (mPackages) {
7048            final int count = candidates.size();
7049            // First, try to use linked apps. Partition the candidates into four lists:
7050            // one for the final results, one for the "do not use ever", one for "undefined status"
7051            // and finally one for "browser app type".
7052            for (int n=0; n<count; n++) {
7053                ResolveInfo info = candidates.get(n);
7054                String packageName = info.activityInfo.packageName;
7055                PackageSetting ps = mSettings.mPackages.get(packageName);
7056                if (ps != null) {
7057                    // Add to the special match all list (Browser use case)
7058                    if (info.handleAllWebDataURI) {
7059                        matchAllList.add(info);
7060                        continue;
7061                    }
7062                    // Try to get the status from User settings first
7063                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7064                    int status = (int)(packedStatus >> 32);
7065                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7066                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7067                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7068                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7069                                    + " : linkgen=" + linkGeneration);
7070                        }
7071                        // Use link-enabled generation as preferredOrder, i.e.
7072                        // prefer newly-enabled over earlier-enabled.
7073                        info.preferredOrder = linkGeneration;
7074                        alwaysList.add(info);
7075                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7076                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7077                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7078                        }
7079                        neverList.add(info);
7080                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7081                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7082                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7083                        }
7084                        alwaysAskList.add(info);
7085                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7086                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7087                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7088                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7089                        }
7090                        undefinedList.add(info);
7091                    }
7092                }
7093            }
7094
7095            // We'll want to include browser possibilities in a few cases
7096            boolean includeBrowser = false;
7097
7098            // First try to add the "always" resolution(s) for the current user, if any
7099            if (alwaysList.size() > 0) {
7100                result.addAll(alwaysList);
7101            } else {
7102                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7103                result.addAll(undefinedList);
7104                // Maybe add one for the other profile.
7105                if (xpDomainInfo != null && (
7106                        xpDomainInfo.bestDomainVerificationStatus
7107                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7108                    result.add(xpDomainInfo.resolveInfo);
7109                }
7110                includeBrowser = true;
7111            }
7112
7113            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7114            // If there were 'always' entries their preferred order has been set, so we also
7115            // back that off to make the alternatives equivalent
7116            if (alwaysAskList.size() > 0) {
7117                for (ResolveInfo i : result) {
7118                    i.preferredOrder = 0;
7119                }
7120                result.addAll(alwaysAskList);
7121                includeBrowser = true;
7122            }
7123
7124            if (includeBrowser) {
7125                // Also add browsers (all of them or only the default one)
7126                if (DEBUG_DOMAIN_VERIFICATION) {
7127                    Slog.v(TAG, "   ...including browsers in candidate set");
7128                }
7129                if ((matchFlags & MATCH_ALL) != 0) {
7130                    result.addAll(matchAllList);
7131                } else {
7132                    // Browser/generic handling case.  If there's a default browser, go straight
7133                    // to that (but only if there is no other higher-priority match).
7134                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7135                    int maxMatchPrio = 0;
7136                    ResolveInfo defaultBrowserMatch = null;
7137                    final int numCandidates = matchAllList.size();
7138                    for (int n = 0; n < numCandidates; n++) {
7139                        ResolveInfo info = matchAllList.get(n);
7140                        // track the highest overall match priority...
7141                        if (info.priority > maxMatchPrio) {
7142                            maxMatchPrio = info.priority;
7143                        }
7144                        // ...and the highest-priority default browser match
7145                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7146                            if (defaultBrowserMatch == null
7147                                    || (defaultBrowserMatch.priority < info.priority)) {
7148                                if (debug) {
7149                                    Slog.v(TAG, "Considering default browser match " + info);
7150                                }
7151                                defaultBrowserMatch = info;
7152                            }
7153                        }
7154                    }
7155                    if (defaultBrowserMatch != null
7156                            && defaultBrowserMatch.priority >= maxMatchPrio
7157                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7158                    {
7159                        if (debug) {
7160                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7161                        }
7162                        result.add(defaultBrowserMatch);
7163                    } else {
7164                        result.addAll(matchAllList);
7165                    }
7166                }
7167
7168                // If there is nothing selected, add all candidates and remove the ones that the user
7169                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7170                if (result.size() == 0) {
7171                    result.addAll(candidates);
7172                    result.removeAll(neverList);
7173                }
7174            }
7175        }
7176        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7177            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7178                    result.size());
7179            for (ResolveInfo info : result) {
7180                Slog.v(TAG, "  + " + info.activityInfo);
7181            }
7182        }
7183        return result;
7184    }
7185
7186    // Returns a packed value as a long:
7187    //
7188    // high 'int'-sized word: link status: undefined/ask/never/always.
7189    // low 'int'-sized word: relative priority among 'always' results.
7190    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7191        long result = ps.getDomainVerificationStatusForUser(userId);
7192        // if none available, get the master status
7193        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7194            if (ps.getIntentFilterVerificationInfo() != null) {
7195                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7196            }
7197        }
7198        return result;
7199    }
7200
7201    private ResolveInfo querySkipCurrentProfileIntents(
7202            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7203            int flags, int sourceUserId) {
7204        if (matchingFilters != null) {
7205            int size = matchingFilters.size();
7206            for (int i = 0; i < size; i ++) {
7207                CrossProfileIntentFilter filter = matchingFilters.get(i);
7208                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7209                    // Checking if there are activities in the target user that can handle the
7210                    // intent.
7211                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7212                            resolvedType, flags, sourceUserId);
7213                    if (resolveInfo != null) {
7214                        return resolveInfo;
7215                    }
7216                }
7217            }
7218        }
7219        return null;
7220    }
7221
7222    // Return matching ResolveInfo in target user if any.
7223    private ResolveInfo queryCrossProfileIntents(
7224            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7225            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7226        if (matchingFilters != null) {
7227            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7228            // match the same intent. For performance reasons, it is better not to
7229            // run queryIntent twice for the same userId
7230            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7231            int size = matchingFilters.size();
7232            for (int i = 0; i < size; i++) {
7233                CrossProfileIntentFilter filter = matchingFilters.get(i);
7234                int targetUserId = filter.getTargetUserId();
7235                boolean skipCurrentProfile =
7236                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7237                boolean skipCurrentProfileIfNoMatchFound =
7238                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7239                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7240                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7241                    // Checking if there are activities in the target user that can handle the
7242                    // intent.
7243                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7244                            resolvedType, flags, sourceUserId);
7245                    if (resolveInfo != null) return resolveInfo;
7246                    alreadyTriedUserIds.put(targetUserId, true);
7247                }
7248            }
7249        }
7250        return null;
7251    }
7252
7253    /**
7254     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7255     * will forward the intent to the filter's target user.
7256     * Otherwise, returns null.
7257     */
7258    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7259            String resolvedType, int flags, int sourceUserId) {
7260        int targetUserId = filter.getTargetUserId();
7261        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7262                resolvedType, flags, targetUserId);
7263        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7264            // If all the matches in the target profile are suspended, return null.
7265            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7266                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7267                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7268                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7269                            targetUserId);
7270                }
7271            }
7272        }
7273        return null;
7274    }
7275
7276    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7277            int sourceUserId, int targetUserId) {
7278        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7279        long ident = Binder.clearCallingIdentity();
7280        boolean targetIsProfile;
7281        try {
7282            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7283        } finally {
7284            Binder.restoreCallingIdentity(ident);
7285        }
7286        String className;
7287        if (targetIsProfile) {
7288            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7289        } else {
7290            className = FORWARD_INTENT_TO_PARENT;
7291        }
7292        ComponentName forwardingActivityComponentName = new ComponentName(
7293                mAndroidApplication.packageName, className);
7294        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7295                sourceUserId);
7296        if (!targetIsProfile) {
7297            forwardingActivityInfo.showUserIcon = targetUserId;
7298            forwardingResolveInfo.noResourceId = true;
7299        }
7300        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7301        forwardingResolveInfo.priority = 0;
7302        forwardingResolveInfo.preferredOrder = 0;
7303        forwardingResolveInfo.match = 0;
7304        forwardingResolveInfo.isDefault = true;
7305        forwardingResolveInfo.filter = filter;
7306        forwardingResolveInfo.targetUserId = targetUserId;
7307        return forwardingResolveInfo;
7308    }
7309
7310    @Override
7311    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7312            Intent[] specifics, String[] specificTypes, Intent intent,
7313            String resolvedType, int flags, int userId) {
7314        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7315                specificTypes, intent, resolvedType, flags, userId));
7316    }
7317
7318    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7319            Intent[] specifics, String[] specificTypes, Intent intent,
7320            String resolvedType, int flags, int userId) {
7321        if (!sUserManager.exists(userId)) return Collections.emptyList();
7322        final int callingUid = Binder.getCallingUid();
7323        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7324                false /*includeInstantApps*/);
7325        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7326                false /*requireFullPermission*/, false /*checkShell*/,
7327                "query intent activity options");
7328        final String resultsAction = intent.getAction();
7329
7330        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7331                | PackageManager.GET_RESOLVED_FILTER, userId);
7332
7333        if (DEBUG_INTENT_MATCHING) {
7334            Log.v(TAG, "Query " + intent + ": " + results);
7335        }
7336
7337        int specificsPos = 0;
7338        int N;
7339
7340        // todo: note that the algorithm used here is O(N^2).  This
7341        // isn't a problem in our current environment, but if we start running
7342        // into situations where we have more than 5 or 10 matches then this
7343        // should probably be changed to something smarter...
7344
7345        // First we go through and resolve each of the specific items
7346        // that were supplied, taking care of removing any corresponding
7347        // duplicate items in the generic resolve list.
7348        if (specifics != null) {
7349            for (int i=0; i<specifics.length; i++) {
7350                final Intent sintent = specifics[i];
7351                if (sintent == null) {
7352                    continue;
7353                }
7354
7355                if (DEBUG_INTENT_MATCHING) {
7356                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7357                }
7358
7359                String action = sintent.getAction();
7360                if (resultsAction != null && resultsAction.equals(action)) {
7361                    // If this action was explicitly requested, then don't
7362                    // remove things that have it.
7363                    action = null;
7364                }
7365
7366                ResolveInfo ri = null;
7367                ActivityInfo ai = null;
7368
7369                ComponentName comp = sintent.getComponent();
7370                if (comp == null) {
7371                    ri = resolveIntent(
7372                        sintent,
7373                        specificTypes != null ? specificTypes[i] : null,
7374                            flags, userId);
7375                    if (ri == null) {
7376                        continue;
7377                    }
7378                    if (ri == mResolveInfo) {
7379                        // ACK!  Must do something better with this.
7380                    }
7381                    ai = ri.activityInfo;
7382                    comp = new ComponentName(ai.applicationInfo.packageName,
7383                            ai.name);
7384                } else {
7385                    ai = getActivityInfo(comp, flags, userId);
7386                    if (ai == null) {
7387                        continue;
7388                    }
7389                }
7390
7391                // Look for any generic query activities that are duplicates
7392                // of this specific one, and remove them from the results.
7393                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7394                N = results.size();
7395                int j;
7396                for (j=specificsPos; j<N; j++) {
7397                    ResolveInfo sri = results.get(j);
7398                    if ((sri.activityInfo.name.equals(comp.getClassName())
7399                            && sri.activityInfo.applicationInfo.packageName.equals(
7400                                    comp.getPackageName()))
7401                        || (action != null && sri.filter.matchAction(action))) {
7402                        results.remove(j);
7403                        if (DEBUG_INTENT_MATCHING) Log.v(
7404                            TAG, "Removing duplicate item from " + j
7405                            + " due to specific " + specificsPos);
7406                        if (ri == null) {
7407                            ri = sri;
7408                        }
7409                        j--;
7410                        N--;
7411                    }
7412                }
7413
7414                // Add this specific item to its proper place.
7415                if (ri == null) {
7416                    ri = new ResolveInfo();
7417                    ri.activityInfo = ai;
7418                }
7419                results.add(specificsPos, ri);
7420                ri.specificIndex = i;
7421                specificsPos++;
7422            }
7423        }
7424
7425        // Now we go through the remaining generic results and remove any
7426        // duplicate actions that are found here.
7427        N = results.size();
7428        for (int i=specificsPos; i<N-1; i++) {
7429            final ResolveInfo rii = results.get(i);
7430            if (rii.filter == null) {
7431                continue;
7432            }
7433
7434            // Iterate over all of the actions of this result's intent
7435            // filter...  typically this should be just one.
7436            final Iterator<String> it = rii.filter.actionsIterator();
7437            if (it == null) {
7438                continue;
7439            }
7440            while (it.hasNext()) {
7441                final String action = it.next();
7442                if (resultsAction != null && resultsAction.equals(action)) {
7443                    // If this action was explicitly requested, then don't
7444                    // remove things that have it.
7445                    continue;
7446                }
7447                for (int j=i+1; j<N; j++) {
7448                    final ResolveInfo rij = results.get(j);
7449                    if (rij.filter != null && rij.filter.hasAction(action)) {
7450                        results.remove(j);
7451                        if (DEBUG_INTENT_MATCHING) Log.v(
7452                            TAG, "Removing duplicate item from " + j
7453                            + " due to action " + action + " at " + i);
7454                        j--;
7455                        N--;
7456                    }
7457                }
7458            }
7459
7460            // If the caller didn't request filter information, drop it now
7461            // so we don't have to marshall/unmarshall it.
7462            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7463                rii.filter = null;
7464            }
7465        }
7466
7467        // Filter out the caller activity if so requested.
7468        if (caller != null) {
7469            N = results.size();
7470            for (int i=0; i<N; i++) {
7471                ActivityInfo ainfo = results.get(i).activityInfo;
7472                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7473                        && caller.getClassName().equals(ainfo.name)) {
7474                    results.remove(i);
7475                    break;
7476                }
7477            }
7478        }
7479
7480        // If the caller didn't request filter information,
7481        // drop them now so we don't have to
7482        // marshall/unmarshall it.
7483        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7484            N = results.size();
7485            for (int i=0; i<N; i++) {
7486                results.get(i).filter = null;
7487            }
7488        }
7489
7490        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7491        return results;
7492    }
7493
7494    @Override
7495    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7496            String resolvedType, int flags, int userId) {
7497        return new ParceledListSlice<>(
7498                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7499                        false /*allowDynamicSplits*/));
7500    }
7501
7502    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7503            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7504        if (!sUserManager.exists(userId)) return Collections.emptyList();
7505        final int callingUid = Binder.getCallingUid();
7506        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7507                false /*requireFullPermission*/, false /*checkShell*/,
7508                "query intent receivers");
7509        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7510        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7511                false /*includeInstantApps*/);
7512        ComponentName comp = intent.getComponent();
7513        if (comp == null) {
7514            if (intent.getSelector() != null) {
7515                intent = intent.getSelector();
7516                comp = intent.getComponent();
7517            }
7518        }
7519        if (comp != null) {
7520            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7521            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7522            if (ai != null) {
7523                // When specifying an explicit component, we prevent the activity from being
7524                // used when either 1) the calling package is normal and the activity is within
7525                // an instant application or 2) the calling package is ephemeral and the
7526                // activity is not visible to instant applications.
7527                final boolean matchInstantApp =
7528                        (flags & PackageManager.MATCH_INSTANT) != 0;
7529                final boolean matchVisibleToInstantAppOnly =
7530                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7531                final boolean matchExplicitlyVisibleOnly =
7532                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7533                final boolean isCallerInstantApp =
7534                        instantAppPkgName != null;
7535                final boolean isTargetSameInstantApp =
7536                        comp.getPackageName().equals(instantAppPkgName);
7537                final boolean isTargetInstantApp =
7538                        (ai.applicationInfo.privateFlags
7539                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7540                final boolean isTargetVisibleToInstantApp =
7541                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7542                final boolean isTargetExplicitlyVisibleToInstantApp =
7543                        isTargetVisibleToInstantApp
7544                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7545                final boolean isTargetHiddenFromInstantApp =
7546                        !isTargetVisibleToInstantApp
7547                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7548                final boolean blockResolution =
7549                        !isTargetSameInstantApp
7550                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7551                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7552                                        && isTargetHiddenFromInstantApp));
7553                if (!blockResolution) {
7554                    ResolveInfo ri = new ResolveInfo();
7555                    ri.activityInfo = ai;
7556                    list.add(ri);
7557                }
7558            }
7559            return applyPostResolutionFilter(
7560                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7561        }
7562
7563        // reader
7564        synchronized (mPackages) {
7565            String pkgName = intent.getPackage();
7566            if (pkgName == null) {
7567                final List<ResolveInfo> result =
7568                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7569                return applyPostResolutionFilter(
7570                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7571            }
7572            final PackageParser.Package pkg = mPackages.get(pkgName);
7573            if (pkg != null) {
7574                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7575                        intent, resolvedType, flags, pkg.receivers, userId);
7576                return applyPostResolutionFilter(
7577                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7578            }
7579            return Collections.emptyList();
7580        }
7581    }
7582
7583    @Override
7584    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7585        final int callingUid = Binder.getCallingUid();
7586        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7587    }
7588
7589    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7590            int userId, int callingUid) {
7591        if (!sUserManager.exists(userId)) return null;
7592        flags = updateFlagsForResolve(
7593                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7594        List<ResolveInfo> query = queryIntentServicesInternal(
7595                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7596        if (query != null) {
7597            if (query.size() >= 1) {
7598                // If there is more than one service with the same priority,
7599                // just arbitrarily pick the first one.
7600                return query.get(0);
7601            }
7602        }
7603        return null;
7604    }
7605
7606    @Override
7607    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7608            String resolvedType, int flags, int userId) {
7609        final int callingUid = Binder.getCallingUid();
7610        return new ParceledListSlice<>(queryIntentServicesInternal(
7611                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7612    }
7613
7614    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7615            String resolvedType, int flags, int userId, int callingUid,
7616            boolean includeInstantApps) {
7617        if (!sUserManager.exists(userId)) return Collections.emptyList();
7618        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7619                false /*requireFullPermission*/, false /*checkShell*/,
7620                "query intent receivers");
7621        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7622        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7623        ComponentName comp = intent.getComponent();
7624        if (comp == null) {
7625            if (intent.getSelector() != null) {
7626                intent = intent.getSelector();
7627                comp = intent.getComponent();
7628            }
7629        }
7630        if (comp != null) {
7631            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7632            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7633            if (si != null) {
7634                // When specifying an explicit component, we prevent the service from being
7635                // used when either 1) the service is in an instant application and the
7636                // caller is not the same instant application or 2) the calling package is
7637                // ephemeral and the activity is not visible to ephemeral applications.
7638                final boolean matchInstantApp =
7639                        (flags & PackageManager.MATCH_INSTANT) != 0;
7640                final boolean matchVisibleToInstantAppOnly =
7641                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7642                final boolean isCallerInstantApp =
7643                        instantAppPkgName != null;
7644                final boolean isTargetSameInstantApp =
7645                        comp.getPackageName().equals(instantAppPkgName);
7646                final boolean isTargetInstantApp =
7647                        (si.applicationInfo.privateFlags
7648                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7649                final boolean isTargetHiddenFromInstantApp =
7650                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7651                final boolean blockResolution =
7652                        !isTargetSameInstantApp
7653                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7654                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7655                                        && isTargetHiddenFromInstantApp));
7656                if (!blockResolution) {
7657                    final ResolveInfo ri = new ResolveInfo();
7658                    ri.serviceInfo = si;
7659                    list.add(ri);
7660                }
7661            }
7662            return list;
7663        }
7664
7665        // reader
7666        synchronized (mPackages) {
7667            String pkgName = intent.getPackage();
7668            if (pkgName == null) {
7669                return applyPostServiceResolutionFilter(
7670                        mServices.queryIntent(intent, resolvedType, flags, userId),
7671                        instantAppPkgName);
7672            }
7673            final PackageParser.Package pkg = mPackages.get(pkgName);
7674            if (pkg != null) {
7675                return applyPostServiceResolutionFilter(
7676                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7677                                userId),
7678                        instantAppPkgName);
7679            }
7680            return Collections.emptyList();
7681        }
7682    }
7683
7684    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7685            String instantAppPkgName) {
7686        if (instantAppPkgName == null) {
7687            return resolveInfos;
7688        }
7689        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7690            final ResolveInfo info = resolveInfos.get(i);
7691            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7692            // allow services that are defined in the provided package
7693            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7694                if (info.serviceInfo.splitName != null
7695                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7696                                info.serviceInfo.splitName)) {
7697                    // requested service is defined in a split that hasn't been installed yet.
7698                    // add the installer to the resolve list
7699                    if (DEBUG_INSTANT) {
7700                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7701                    }
7702                    final ResolveInfo installerInfo = new ResolveInfo(
7703                            mInstantAppInstallerInfo);
7704                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7705                            null /* installFailureActivity */,
7706                            info.serviceInfo.packageName,
7707                            info.serviceInfo.applicationInfo.longVersionCode,
7708                            info.serviceInfo.splitName);
7709                    // add a non-generic filter
7710                    installerInfo.filter = new IntentFilter();
7711                    // load resources from the correct package
7712                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7713                    resolveInfos.set(i, installerInfo);
7714                }
7715                continue;
7716            }
7717            // allow services that have been explicitly exposed to ephemeral apps
7718            if (!isEphemeralApp
7719                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7720                continue;
7721            }
7722            resolveInfos.remove(i);
7723        }
7724        return resolveInfos;
7725    }
7726
7727    @Override
7728    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7729            String resolvedType, int flags, int userId) {
7730        return new ParceledListSlice<>(
7731                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7732    }
7733
7734    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7735            Intent intent, String resolvedType, int flags, int userId) {
7736        if (!sUserManager.exists(userId)) return Collections.emptyList();
7737        final int callingUid = Binder.getCallingUid();
7738        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7739        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7740                false /*includeInstantApps*/);
7741        ComponentName comp = intent.getComponent();
7742        if (comp == null) {
7743            if (intent.getSelector() != null) {
7744                intent = intent.getSelector();
7745                comp = intent.getComponent();
7746            }
7747        }
7748        if (comp != null) {
7749            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7750            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7751            if (pi != null) {
7752                // When specifying an explicit component, we prevent the provider from being
7753                // used when either 1) the provider is in an instant application and the
7754                // caller is not the same instant application or 2) the calling package is an
7755                // instant application and the provider is not visible to instant applications.
7756                final boolean matchInstantApp =
7757                        (flags & PackageManager.MATCH_INSTANT) != 0;
7758                final boolean matchVisibleToInstantAppOnly =
7759                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7760                final boolean isCallerInstantApp =
7761                        instantAppPkgName != null;
7762                final boolean isTargetSameInstantApp =
7763                        comp.getPackageName().equals(instantAppPkgName);
7764                final boolean isTargetInstantApp =
7765                        (pi.applicationInfo.privateFlags
7766                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7767                final boolean isTargetHiddenFromInstantApp =
7768                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7769                final boolean blockResolution =
7770                        !isTargetSameInstantApp
7771                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7772                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7773                                        && isTargetHiddenFromInstantApp));
7774                if (!blockResolution) {
7775                    final ResolveInfo ri = new ResolveInfo();
7776                    ri.providerInfo = pi;
7777                    list.add(ri);
7778                }
7779            }
7780            return list;
7781        }
7782
7783        // reader
7784        synchronized (mPackages) {
7785            String pkgName = intent.getPackage();
7786            if (pkgName == null) {
7787                return applyPostContentProviderResolutionFilter(
7788                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7789                        instantAppPkgName);
7790            }
7791            final PackageParser.Package pkg = mPackages.get(pkgName);
7792            if (pkg != null) {
7793                return applyPostContentProviderResolutionFilter(
7794                        mProviders.queryIntentForPackage(
7795                        intent, resolvedType, flags, pkg.providers, userId),
7796                        instantAppPkgName);
7797            }
7798            return Collections.emptyList();
7799        }
7800    }
7801
7802    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7803            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7804        if (instantAppPkgName == null) {
7805            return resolveInfos;
7806        }
7807        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7808            final ResolveInfo info = resolveInfos.get(i);
7809            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7810            // allow providers that are defined in the provided package
7811            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7812                if (info.providerInfo.splitName != null
7813                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7814                                info.providerInfo.splitName)) {
7815                    // requested provider is defined in a split that hasn't been installed yet.
7816                    // add the installer to the resolve list
7817                    if (DEBUG_INSTANT) {
7818                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7819                    }
7820                    final ResolveInfo installerInfo = new ResolveInfo(
7821                            mInstantAppInstallerInfo);
7822                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7823                            null /*failureActivity*/,
7824                            info.providerInfo.packageName,
7825                            info.providerInfo.applicationInfo.longVersionCode,
7826                            info.providerInfo.splitName);
7827                    // add a non-generic filter
7828                    installerInfo.filter = new IntentFilter();
7829                    // load resources from the correct package
7830                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7831                    resolveInfos.set(i, installerInfo);
7832                }
7833                continue;
7834            }
7835            // allow providers that have been explicitly exposed to instant applications
7836            if (!isEphemeralApp
7837                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7838                continue;
7839            }
7840            resolveInfos.remove(i);
7841        }
7842        return resolveInfos;
7843    }
7844
7845    @Override
7846    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7847        final int callingUid = Binder.getCallingUid();
7848        if (getInstantAppPackageName(callingUid) != null) {
7849            return ParceledListSlice.emptyList();
7850        }
7851        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7852        flags = updateFlagsForPackage(flags, userId, null);
7853        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7854        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7855                true /* requireFullPermission */, false /* checkShell */,
7856                "get installed packages");
7857
7858        // writer
7859        synchronized (mPackages) {
7860            ArrayList<PackageInfo> list;
7861            if (listUninstalled) {
7862                list = new ArrayList<>(mSettings.mPackages.size());
7863                for (PackageSetting ps : mSettings.mPackages.values()) {
7864                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7865                        continue;
7866                    }
7867                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7868                        continue;
7869                    }
7870                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7871                    if (pi != null) {
7872                        list.add(pi);
7873                    }
7874                }
7875            } else {
7876                list = new ArrayList<>(mPackages.size());
7877                for (PackageParser.Package p : mPackages.values()) {
7878                    final PackageSetting ps = (PackageSetting) p.mExtras;
7879                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7880                        continue;
7881                    }
7882                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7883                        continue;
7884                    }
7885                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7886                            p.mExtras, flags, userId);
7887                    if (pi != null) {
7888                        list.add(pi);
7889                    }
7890                }
7891            }
7892
7893            return new ParceledListSlice<>(list);
7894        }
7895    }
7896
7897    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7898            String[] permissions, boolean[] tmp, int flags, int userId) {
7899        int numMatch = 0;
7900        final PermissionsState permissionsState = ps.getPermissionsState();
7901        for (int i=0; i<permissions.length; i++) {
7902            final String permission = permissions[i];
7903            if (permissionsState.hasPermission(permission, userId)) {
7904                tmp[i] = true;
7905                numMatch++;
7906            } else {
7907                tmp[i] = false;
7908            }
7909        }
7910        if (numMatch == 0) {
7911            return;
7912        }
7913        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7914
7915        // The above might return null in cases of uninstalled apps or install-state
7916        // skew across users/profiles.
7917        if (pi != null) {
7918            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7919                if (numMatch == permissions.length) {
7920                    pi.requestedPermissions = permissions;
7921                } else {
7922                    pi.requestedPermissions = new String[numMatch];
7923                    numMatch = 0;
7924                    for (int i=0; i<permissions.length; i++) {
7925                        if (tmp[i]) {
7926                            pi.requestedPermissions[numMatch] = permissions[i];
7927                            numMatch++;
7928                        }
7929                    }
7930                }
7931            }
7932            list.add(pi);
7933        }
7934    }
7935
7936    @Override
7937    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7938            String[] permissions, int flags, int userId) {
7939        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7940        flags = updateFlagsForPackage(flags, userId, permissions);
7941        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7942                true /* requireFullPermission */, false /* checkShell */,
7943                "get packages holding permissions");
7944        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7945
7946        // writer
7947        synchronized (mPackages) {
7948            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7949            boolean[] tmpBools = new boolean[permissions.length];
7950            if (listUninstalled) {
7951                for (PackageSetting ps : mSettings.mPackages.values()) {
7952                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7953                            userId);
7954                }
7955            } else {
7956                for (PackageParser.Package pkg : mPackages.values()) {
7957                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7958                    if (ps != null) {
7959                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7960                                userId);
7961                    }
7962                }
7963            }
7964
7965            return new ParceledListSlice<PackageInfo>(list);
7966        }
7967    }
7968
7969    @Override
7970    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7971        final int callingUid = Binder.getCallingUid();
7972        if (getInstantAppPackageName(callingUid) != null) {
7973            return ParceledListSlice.emptyList();
7974        }
7975        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7976        flags = updateFlagsForApplication(flags, userId, null);
7977        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7978
7979        // writer
7980        synchronized (mPackages) {
7981            ArrayList<ApplicationInfo> list;
7982            if (listUninstalled) {
7983                list = new ArrayList<>(mSettings.mPackages.size());
7984                for (PackageSetting ps : mSettings.mPackages.values()) {
7985                    ApplicationInfo ai;
7986                    int effectiveFlags = flags;
7987                    if (ps.isSystem()) {
7988                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7989                    }
7990                    if (ps.pkg != null) {
7991                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7992                            continue;
7993                        }
7994                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7995                            continue;
7996                        }
7997                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7998                                ps.readUserState(userId), userId);
7999                        if (ai != null) {
8000                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8001                        }
8002                    } else {
8003                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8004                        // and already converts to externally visible package name
8005                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8006                                callingUid, effectiveFlags, userId);
8007                    }
8008                    if (ai != null) {
8009                        list.add(ai);
8010                    }
8011                }
8012            } else {
8013                list = new ArrayList<>(mPackages.size());
8014                for (PackageParser.Package p : mPackages.values()) {
8015                    if (p.mExtras != null) {
8016                        PackageSetting ps = (PackageSetting) p.mExtras;
8017                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8018                            continue;
8019                        }
8020                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8021                            continue;
8022                        }
8023                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8024                                ps.readUserState(userId), userId);
8025                        if (ai != null) {
8026                            ai.packageName = resolveExternalPackageNameLPr(p);
8027                            list.add(ai);
8028                        }
8029                    }
8030                }
8031            }
8032
8033            return new ParceledListSlice<>(list);
8034        }
8035    }
8036
8037    @Override
8038    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8039        if (HIDE_EPHEMERAL_APIS) {
8040            return null;
8041        }
8042        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8043            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8044                    "getEphemeralApplications");
8045        }
8046        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8047                true /* requireFullPermission */, false /* checkShell */,
8048                "getEphemeralApplications");
8049        synchronized (mPackages) {
8050            List<InstantAppInfo> instantApps = mInstantAppRegistry
8051                    .getInstantAppsLPr(userId);
8052            if (instantApps != null) {
8053                return new ParceledListSlice<>(instantApps);
8054            }
8055        }
8056        return null;
8057    }
8058
8059    @Override
8060    public boolean isInstantApp(String packageName, int userId) {
8061        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8062                true /* requireFullPermission */, false /* checkShell */,
8063                "isInstantApp");
8064        if (HIDE_EPHEMERAL_APIS) {
8065            return false;
8066        }
8067
8068        synchronized (mPackages) {
8069            int callingUid = Binder.getCallingUid();
8070            if (Process.isIsolated(callingUid)) {
8071                callingUid = mIsolatedOwners.get(callingUid);
8072            }
8073            final PackageSetting ps = mSettings.mPackages.get(packageName);
8074            PackageParser.Package pkg = mPackages.get(packageName);
8075            final boolean returnAllowed =
8076                    ps != null
8077                    && (isCallerSameApp(packageName, callingUid)
8078                            || canViewInstantApps(callingUid, userId)
8079                            || mInstantAppRegistry.isInstantAccessGranted(
8080                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8081            if (returnAllowed) {
8082                return ps.getInstantApp(userId);
8083            }
8084        }
8085        return false;
8086    }
8087
8088    @Override
8089    public byte[] getInstantAppCookie(String packageName, int userId) {
8090        if (HIDE_EPHEMERAL_APIS) {
8091            return null;
8092        }
8093
8094        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8095                true /* requireFullPermission */, false /* checkShell */,
8096                "getInstantAppCookie");
8097        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8098            return null;
8099        }
8100        synchronized (mPackages) {
8101            return mInstantAppRegistry.getInstantAppCookieLPw(
8102                    packageName, userId);
8103        }
8104    }
8105
8106    @Override
8107    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8108        if (HIDE_EPHEMERAL_APIS) {
8109            return true;
8110        }
8111
8112        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8113                true /* requireFullPermission */, true /* checkShell */,
8114                "setInstantAppCookie");
8115        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8116            return false;
8117        }
8118        synchronized (mPackages) {
8119            return mInstantAppRegistry.setInstantAppCookieLPw(
8120                    packageName, cookie, userId);
8121        }
8122    }
8123
8124    @Override
8125    public Bitmap getInstantAppIcon(String packageName, int userId) {
8126        if (HIDE_EPHEMERAL_APIS) {
8127            return null;
8128        }
8129
8130        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8131            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8132                    "getInstantAppIcon");
8133        }
8134        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8135                true /* requireFullPermission */, false /* checkShell */,
8136                "getInstantAppIcon");
8137
8138        synchronized (mPackages) {
8139            return mInstantAppRegistry.getInstantAppIconLPw(
8140                    packageName, userId);
8141        }
8142    }
8143
8144    private boolean isCallerSameApp(String packageName, int uid) {
8145        PackageParser.Package pkg = mPackages.get(packageName);
8146        return pkg != null
8147                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8148    }
8149
8150    @Override
8151    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8152        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8153            return ParceledListSlice.emptyList();
8154        }
8155        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8156    }
8157
8158    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8159        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8160
8161        // reader
8162        synchronized (mPackages) {
8163            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8164            final int userId = UserHandle.getCallingUserId();
8165            while (i.hasNext()) {
8166                final PackageParser.Package p = i.next();
8167                if (p.applicationInfo == null) continue;
8168
8169                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8170                        && !p.applicationInfo.isDirectBootAware();
8171                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8172                        && p.applicationInfo.isDirectBootAware();
8173
8174                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8175                        && (!mSafeMode || isSystemApp(p))
8176                        && (matchesUnaware || matchesAware)) {
8177                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8178                    if (ps != null) {
8179                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8180                                ps.readUserState(userId), userId);
8181                        if (ai != null) {
8182                            finalList.add(ai);
8183                        }
8184                    }
8185                }
8186            }
8187        }
8188
8189        return finalList;
8190    }
8191
8192    @Override
8193    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8194        return resolveContentProviderInternal(name, flags, userId);
8195    }
8196
8197    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8198        if (!sUserManager.exists(userId)) return null;
8199        flags = updateFlagsForComponent(flags, userId, name);
8200        final int callingUid = Binder.getCallingUid();
8201        synchronized (mPackages) {
8202            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8203            PackageSetting ps = provider != null
8204                    ? mSettings.mPackages.get(provider.owner.packageName)
8205                    : null;
8206            if (ps != null) {
8207                // provider not enabled
8208                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8209                    return null;
8210                }
8211                final ComponentName component =
8212                        new ComponentName(provider.info.packageName, provider.info.name);
8213                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8214                    return null;
8215                }
8216                return PackageParser.generateProviderInfo(
8217                        provider, flags, ps.readUserState(userId), userId);
8218            }
8219            return null;
8220        }
8221    }
8222
8223    /**
8224     * @deprecated
8225     */
8226    @Deprecated
8227    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8228        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8229            return;
8230        }
8231        // reader
8232        synchronized (mPackages) {
8233            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8234                    .entrySet().iterator();
8235            final int userId = UserHandle.getCallingUserId();
8236            while (i.hasNext()) {
8237                Map.Entry<String, PackageParser.Provider> entry = i.next();
8238                PackageParser.Provider p = entry.getValue();
8239                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8240
8241                if (ps != null && p.syncable
8242                        && (!mSafeMode || (p.info.applicationInfo.flags
8243                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8244                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8245                            ps.readUserState(userId), userId);
8246                    if (info != null) {
8247                        outNames.add(entry.getKey());
8248                        outInfo.add(info);
8249                    }
8250                }
8251            }
8252        }
8253    }
8254
8255    @Override
8256    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8257            int uid, int flags, String metaDataKey) {
8258        final int callingUid = Binder.getCallingUid();
8259        final int userId = processName != null ? UserHandle.getUserId(uid)
8260                : UserHandle.getCallingUserId();
8261        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8262        flags = updateFlagsForComponent(flags, userId, processName);
8263        ArrayList<ProviderInfo> finalList = null;
8264        // reader
8265        synchronized (mPackages) {
8266            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8267            while (i.hasNext()) {
8268                final PackageParser.Provider p = i.next();
8269                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8270                if (ps != null && p.info.authority != null
8271                        && (processName == null
8272                                || (p.info.processName.equals(processName)
8273                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8274                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8275
8276                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8277                    // parameter.
8278                    if (metaDataKey != null
8279                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8280                        continue;
8281                    }
8282                    final ComponentName component =
8283                            new ComponentName(p.info.packageName, p.info.name);
8284                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8285                        continue;
8286                    }
8287                    if (finalList == null) {
8288                        finalList = new ArrayList<ProviderInfo>(3);
8289                    }
8290                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8291                            ps.readUserState(userId), userId);
8292                    if (info != null) {
8293                        finalList.add(info);
8294                    }
8295                }
8296            }
8297        }
8298
8299        if (finalList != null) {
8300            Collections.sort(finalList, mProviderInitOrderSorter);
8301            return new ParceledListSlice<ProviderInfo>(finalList);
8302        }
8303
8304        return ParceledListSlice.emptyList();
8305    }
8306
8307    @Override
8308    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8309        // reader
8310        synchronized (mPackages) {
8311            final int callingUid = Binder.getCallingUid();
8312            final int callingUserId = UserHandle.getUserId(callingUid);
8313            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8314            if (ps == null) return null;
8315            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8316                return null;
8317            }
8318            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8319            return PackageParser.generateInstrumentationInfo(i, flags);
8320        }
8321    }
8322
8323    @Override
8324    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8325            String targetPackage, int flags) {
8326        final int callingUid = Binder.getCallingUid();
8327        final int callingUserId = UserHandle.getUserId(callingUid);
8328        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8329        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8330            return ParceledListSlice.emptyList();
8331        }
8332        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8333    }
8334
8335    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8336            int flags) {
8337        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8338
8339        // reader
8340        synchronized (mPackages) {
8341            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8342            while (i.hasNext()) {
8343                final PackageParser.Instrumentation p = i.next();
8344                if (targetPackage == null
8345                        || targetPackage.equals(p.info.targetPackage)) {
8346                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8347                            flags);
8348                    if (ii != null) {
8349                        finalList.add(ii);
8350                    }
8351                }
8352            }
8353        }
8354
8355        return finalList;
8356    }
8357
8358    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8359        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8360        try {
8361            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8362        } finally {
8363            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8364        }
8365    }
8366
8367    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8368        final File[] files = scanDir.listFiles();
8369        if (ArrayUtils.isEmpty(files)) {
8370            Log.d(TAG, "No files in app dir " + scanDir);
8371            return;
8372        }
8373
8374        if (DEBUG_PACKAGE_SCANNING) {
8375            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8376                    + " flags=0x" + Integer.toHexString(parseFlags));
8377        }
8378        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8379                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8380                mParallelPackageParserCallback)) {
8381            // Submit files for parsing in parallel
8382            int fileCount = 0;
8383            for (File file : files) {
8384                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8385                        && !PackageInstallerService.isStageName(file.getName());
8386                if (!isPackage) {
8387                    // Ignore entries which are not packages
8388                    continue;
8389                }
8390                parallelPackageParser.submit(file, parseFlags);
8391                fileCount++;
8392            }
8393
8394            // Process results one by one
8395            for (; fileCount > 0; fileCount--) {
8396                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8397                Throwable throwable = parseResult.throwable;
8398                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8399
8400                if (throwable == null) {
8401                    // TODO(toddke): move lower in the scan chain
8402                    // Static shared libraries have synthetic package names
8403                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8404                        renameStaticSharedLibraryPackage(parseResult.pkg);
8405                    }
8406                    try {
8407                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8408                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8409                                    currentTime, null);
8410                        }
8411                    } catch (PackageManagerException e) {
8412                        errorCode = e.error;
8413                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8414                    }
8415                } else if (throwable instanceof PackageParser.PackageParserException) {
8416                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8417                            throwable;
8418                    errorCode = e.error;
8419                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8420                } else {
8421                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8422                            + parseResult.scanFile, throwable);
8423                }
8424
8425                // Delete invalid userdata apps
8426                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8427                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8428                    logCriticalInfo(Log.WARN,
8429                            "Deleting invalid package at " + parseResult.scanFile);
8430                    removeCodePathLI(parseResult.scanFile);
8431                }
8432            }
8433        }
8434    }
8435
8436    public static void reportSettingsProblem(int priority, String msg) {
8437        logCriticalInfo(priority, msg);
8438    }
8439
8440    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8441            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8442        // When upgrading from pre-N MR1, verify the package time stamp using the package
8443        // directory and not the APK file.
8444        final long lastModifiedTime = mIsPreNMR1Upgrade
8445                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8446        if (ps != null && !forceCollect
8447                && ps.codePathString.equals(pkg.codePath)
8448                && ps.timeStamp == lastModifiedTime
8449                && !isCompatSignatureUpdateNeeded(pkg)
8450                && !isRecoverSignatureUpdateNeeded(pkg)) {
8451            if (ps.signatures.mSigningDetails.signatures != null
8452                    && ps.signatures.mSigningDetails.signatures.length != 0
8453                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8454                            != SignatureSchemeVersion.UNKNOWN) {
8455                // Optimization: reuse the existing cached signing data
8456                // if the package appears to be unchanged.
8457                pkg.mSigningDetails =
8458                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8459                return;
8460            }
8461
8462            Slog.w(TAG, "PackageSetting for " + ps.name
8463                    + " is missing signatures.  Collecting certs again to recover them.");
8464        } else {
8465            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8466                    (forceCollect ? " (forced)" : ""));
8467        }
8468
8469        try {
8470            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8471            PackageParser.collectCertificates(pkg, skipVerify);
8472        } catch (PackageParserException e) {
8473            throw PackageManagerException.from(e);
8474        } finally {
8475            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8476        }
8477    }
8478
8479    /**
8480     *  Traces a package scan.
8481     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8482     */
8483    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8484            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8485        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8486        try {
8487            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8488        } finally {
8489            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8490        }
8491    }
8492
8493    /**
8494     *  Scans a package and returns the newly parsed package.
8495     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8496     */
8497    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8498            long currentTime, UserHandle user) throws PackageManagerException {
8499        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8500        PackageParser pp = new PackageParser();
8501        pp.setSeparateProcesses(mSeparateProcesses);
8502        pp.setOnlyCoreApps(mOnlyCore);
8503        pp.setDisplayMetrics(mMetrics);
8504        pp.setCallback(mPackageParserCallback);
8505
8506        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8507        final PackageParser.Package pkg;
8508        try {
8509            pkg = pp.parsePackage(scanFile, parseFlags);
8510        } catch (PackageParserException e) {
8511            throw PackageManagerException.from(e);
8512        } finally {
8513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8514        }
8515
8516        // Static shared libraries have synthetic package names
8517        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8518            renameStaticSharedLibraryPackage(pkg);
8519        }
8520
8521        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8522    }
8523
8524    /**
8525     *  Scans a package and returns the newly parsed package.
8526     *  @throws PackageManagerException on a parse error.
8527     */
8528    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8529            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8530            @Nullable UserHandle user)
8531                    throws PackageManagerException {
8532        // If the package has children and this is the first dive in the function
8533        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8534        // packages (parent and children) would be successfully scanned before the
8535        // actual scan since scanning mutates internal state and we want to atomically
8536        // install the package and its children.
8537        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8538            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8539                scanFlags |= SCAN_CHECK_ONLY;
8540            }
8541        } else {
8542            scanFlags &= ~SCAN_CHECK_ONLY;
8543        }
8544
8545        // Scan the parent
8546        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8547                scanFlags, currentTime, user);
8548
8549        // Scan the children
8550        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8551        for (int i = 0; i < childCount; i++) {
8552            PackageParser.Package childPackage = pkg.childPackages.get(i);
8553            addForInitLI(childPackage, parseFlags, scanFlags,
8554                    currentTime, user);
8555        }
8556
8557
8558        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8559            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8560        }
8561
8562        return scannedPkg;
8563    }
8564
8565    /**
8566     * Returns if full apk verification can be skipped for the whole package, including the splits.
8567     */
8568    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8569        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8570            return false;
8571        }
8572        // TODO: Allow base and splits to be verified individually.
8573        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8574            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8575                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8576                    return false;
8577                }
8578            }
8579        }
8580        return true;
8581    }
8582
8583    /**
8584     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8585     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8586     * match one in a trusted source, and should be done separately.
8587     */
8588    private boolean canSkipFullApkVerification(String apkPath) {
8589        byte[] rootHashObserved = null;
8590        try {
8591            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8592            if (rootHashObserved == null) {
8593                return false;  // APK does not contain Merkle tree root hash.
8594            }
8595            synchronized (mInstallLock) {
8596                // Returns whether the observed root hash matches what kernel has.
8597                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8598                return true;
8599            }
8600        } catch (InstallerException | IOException | DigestException |
8601                NoSuchAlgorithmException e) {
8602            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8603        }
8604        return false;
8605    }
8606
8607    /**
8608     * Adds a new package to the internal data structures during platform initialization.
8609     * <p>After adding, the package is known to the system and available for querying.
8610     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8611     * etc...], additional checks are performed. Basic verification [such as ensuring
8612     * matching signatures, checking version codes, etc...] occurs if the package is
8613     * identical to a previously known package. If the package fails a signature check,
8614     * the version installed on /data will be removed. If the version of the new package
8615     * is less than or equal than the version on /data, it will be ignored.
8616     * <p>Regardless of the package location, the results are applied to the internal
8617     * structures and the package is made available to the rest of the system.
8618     * <p>NOTE: The return value should be removed. It's the passed in package object.
8619     */
8620    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8621            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8622            @Nullable UserHandle user)
8623                    throws PackageManagerException {
8624        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8625        final String renamedPkgName;
8626        final PackageSetting disabledPkgSetting;
8627        final boolean isSystemPkgUpdated;
8628        final boolean pkgAlreadyExists;
8629        PackageSetting pkgSetting;
8630
8631        // NOTE: installPackageLI() has the same code to setup the package's
8632        // application info. This probably should be done lower in the call
8633        // stack [such as scanPackageOnly()]. However, we verify the application
8634        // info prior to that [in scanPackageNew()] and thus have to setup
8635        // the application info early.
8636        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8637        pkg.setApplicationInfoCodePath(pkg.codePath);
8638        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8639        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8640        pkg.setApplicationInfoResourcePath(pkg.codePath);
8641        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8642        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8643
8644        synchronized (mPackages) {
8645            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8646            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8647            if (realPkgName != null) {
8648                ensurePackageRenamed(pkg, renamedPkgName);
8649            }
8650            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8651            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8652            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8653            pkgAlreadyExists = pkgSetting != null;
8654            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8655            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8656            isSystemPkgUpdated = disabledPkgSetting != null;
8657
8658            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8659                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8660            }
8661
8662            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8663                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8664                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8665                    : null;
8666            if (DEBUG_PACKAGE_SCANNING
8667                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8668                    && sharedUserSetting != null) {
8669                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8670                        + " (uid=" + sharedUserSetting.userId + "):"
8671                        + " packages=" + sharedUserSetting.packages);
8672            }
8673
8674            if (scanSystemPartition) {
8675                // Potentially prune child packages. If the application on the /system
8676                // partition has been updated via OTA, but, is still disabled by a
8677                // version on /data, cycle through all of its children packages and
8678                // remove children that are no longer defined.
8679                if (isSystemPkgUpdated) {
8680                    final int scannedChildCount = (pkg.childPackages != null)
8681                            ? pkg.childPackages.size() : 0;
8682                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8683                            ? disabledPkgSetting.childPackageNames.size() : 0;
8684                    for (int i = 0; i < disabledChildCount; i++) {
8685                        String disabledChildPackageName =
8686                                disabledPkgSetting.childPackageNames.get(i);
8687                        boolean disabledPackageAvailable = false;
8688                        for (int j = 0; j < scannedChildCount; j++) {
8689                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8690                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8691                                disabledPackageAvailable = true;
8692                                break;
8693                            }
8694                        }
8695                        if (!disabledPackageAvailable) {
8696                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8697                        }
8698                    }
8699                    // we're updating the disabled package, so, scan it as the package setting
8700                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
8701                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8702                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8703                            (pkg == mPlatformPackage), user);
8704                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8705                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8706                }
8707            }
8708        }
8709
8710        final boolean newPkgChangedPaths =
8711                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8712        final boolean newPkgVersionGreater =
8713                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8714        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8715                && newPkgChangedPaths && newPkgVersionGreater;
8716        if (isSystemPkgBetter) {
8717            // The version of the application on /system is greater than the version on
8718            // /data. Switch back to the application on /system.
8719            // It's safe to assume the application on /system will correctly scan. If not,
8720            // there won't be a working copy of the application.
8721            synchronized (mPackages) {
8722                // just remove the loaded entries from package lists
8723                mPackages.remove(pkgSetting.name);
8724            }
8725
8726            logCriticalInfo(Log.WARN,
8727                    "System package updated;"
8728                    + " name: " + pkgSetting.name
8729                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8730                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8731
8732            final InstallArgs args = createInstallArgsForExisting(
8733                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8734                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8735            args.cleanUpResourcesLI();
8736            synchronized (mPackages) {
8737                mSettings.enableSystemPackageLPw(pkgSetting.name);
8738            }
8739        }
8740
8741        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8742            // The version of the application on the /system partition is less than or
8743            // equal to the version on the /data partition. Throw an exception and use
8744            // the application already installed on the /data partition.
8745            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8746                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8747                    + " better than this " + pkg.getLongVersionCode());
8748        }
8749
8750        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8751        // force re-collecting certificate.
8752        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8753                disabledPkgSetting);
8754        // Full APK verification can be skipped during certificate collection, only if the file is
8755        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8756        // cases, only data in Signing Block is verified instead of the whole file.
8757        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8758                (forceCollect && canSkipFullPackageVerification(pkg));
8759        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8760
8761        boolean shouldHideSystemApp = false;
8762        // A new application appeared on /system, but, we already have a copy of
8763        // the application installed on /data.
8764        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8765                && !pkgSetting.isSystem()) {
8766
8767            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8768                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8769                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8770                                    pkg.mSigningDetails,
8771                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8772                logCriticalInfo(Log.WARN,
8773                        "System package signature mismatch;"
8774                        + " name: " + pkgSetting.name);
8775                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8776                        "scanPackageInternalLI")) {
8777                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8778                }
8779                pkgSetting = null;
8780            } else if (newPkgVersionGreater) {
8781                // The application on /system is newer than the application on /data.
8782                // Simply remove the application on /data [keeping application data]
8783                // and replace it with the version on /system.
8784                logCriticalInfo(Log.WARN,
8785                        "System package enabled;"
8786                        + " name: " + pkgSetting.name
8787                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8788                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8789                InstallArgs args = createInstallArgsForExisting(
8790                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8791                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8792                synchronized (mInstallLock) {
8793                    args.cleanUpResourcesLI();
8794                }
8795            } else {
8796                // The application on /system is older than the application on /data. Hide
8797                // the application on /system and the version on /data will be scanned later
8798                // and re-added like an update.
8799                shouldHideSystemApp = true;
8800                logCriticalInfo(Log.INFO,
8801                        "System package disabled;"
8802                        + " name: " + pkgSetting.name
8803                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8804                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8805            }
8806        }
8807
8808        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8809                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8810
8811        if (shouldHideSystemApp) {
8812            synchronized (mPackages) {
8813                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8814            }
8815        }
8816        return scannedPkg;
8817    }
8818
8819    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8820        // Derive the new package synthetic package name
8821        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8822                + pkg.staticSharedLibVersion);
8823    }
8824
8825    private static String fixProcessName(String defProcessName,
8826            String processName) {
8827        if (processName == null) {
8828            return defProcessName;
8829        }
8830        return processName;
8831    }
8832
8833    /**
8834     * Enforces that only the system UID or root's UID can call a method exposed
8835     * via Binder.
8836     *
8837     * @param message used as message if SecurityException is thrown
8838     * @throws SecurityException if the caller is not system or root
8839     */
8840    private static final void enforceSystemOrRoot(String message) {
8841        final int uid = Binder.getCallingUid();
8842        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8843            throw new SecurityException(message);
8844        }
8845    }
8846
8847    @Override
8848    public void performFstrimIfNeeded() {
8849        enforceSystemOrRoot("Only the system can request fstrim");
8850
8851        // Before everything else, see whether we need to fstrim.
8852        try {
8853            IStorageManager sm = PackageHelper.getStorageManager();
8854            if (sm != null) {
8855                boolean doTrim = false;
8856                final long interval = android.provider.Settings.Global.getLong(
8857                        mContext.getContentResolver(),
8858                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8859                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8860                if (interval > 0) {
8861                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8862                    if (timeSinceLast > interval) {
8863                        doTrim = true;
8864                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8865                                + "; running immediately");
8866                    }
8867                }
8868                if (doTrim) {
8869                    final boolean dexOptDialogShown;
8870                    synchronized (mPackages) {
8871                        dexOptDialogShown = mDexOptDialogShown;
8872                    }
8873                    if (!isFirstBoot() && dexOptDialogShown) {
8874                        try {
8875                            ActivityManager.getService().showBootMessage(
8876                                    mContext.getResources().getString(
8877                                            R.string.android_upgrading_fstrim), true);
8878                        } catch (RemoteException e) {
8879                        }
8880                    }
8881                    sm.runMaintenance();
8882                }
8883            } else {
8884                Slog.e(TAG, "storageManager service unavailable!");
8885            }
8886        } catch (RemoteException e) {
8887            // Can't happen; StorageManagerService is local
8888        }
8889    }
8890
8891    @Override
8892    public void updatePackagesIfNeeded() {
8893        enforceSystemOrRoot("Only the system can request package update");
8894
8895        // We need to re-extract after an OTA.
8896        boolean causeUpgrade = isUpgrade();
8897
8898        // First boot or factory reset.
8899        // Note: we also handle devices that are upgrading to N right now as if it is their
8900        //       first boot, as they do not have profile data.
8901        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8902
8903        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8904        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8905
8906        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8907            return;
8908        }
8909
8910        List<PackageParser.Package> pkgs;
8911        synchronized (mPackages) {
8912            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8913        }
8914
8915        final long startTime = System.nanoTime();
8916        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8917                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8918                    false /* bootComplete */);
8919
8920        final int elapsedTimeSeconds =
8921                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8922
8923        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8924        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8925        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8926        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8927        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8928    }
8929
8930    /*
8931     * Return the prebuilt profile path given a package base code path.
8932     */
8933    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8934        return pkg.baseCodePath + ".prof";
8935    }
8936
8937    /**
8938     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8939     * containing statistics about the invocation. The array consists of three elements,
8940     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8941     * and {@code numberOfPackagesFailed}.
8942     */
8943    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8944            final int compilationReason, boolean bootComplete) {
8945
8946        int numberOfPackagesVisited = 0;
8947        int numberOfPackagesOptimized = 0;
8948        int numberOfPackagesSkipped = 0;
8949        int numberOfPackagesFailed = 0;
8950        final int numberOfPackagesToDexopt = pkgs.size();
8951
8952        for (PackageParser.Package pkg : pkgs) {
8953            numberOfPackagesVisited++;
8954
8955            boolean useProfileForDexopt = false;
8956
8957            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8958                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8959                // that are already compiled.
8960                File profileFile = new File(getPrebuildProfilePath(pkg));
8961                // Copy profile if it exists.
8962                if (profileFile.exists()) {
8963                    try {
8964                        // We could also do this lazily before calling dexopt in
8965                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8966                        // is that we don't have a good way to say "do this only once".
8967                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8968                                pkg.applicationInfo.uid, pkg.packageName,
8969                                ArtManager.getProfileName(null))) {
8970                            Log.e(TAG, "Installer failed to copy system profile!");
8971                        } else {
8972                            // Disabled as this causes speed-profile compilation during first boot
8973                            // even if things are already compiled.
8974                            // useProfileForDexopt = true;
8975                        }
8976                    } catch (Exception e) {
8977                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8978                                e);
8979                    }
8980                } else {
8981                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8982                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8983                    // minimize the number off apps being speed-profile compiled during first boot.
8984                    // The other paths will not change the filter.
8985                    if (disabledPs != null && disabledPs.pkg.isStub) {
8986                        // The package is the stub one, remove the stub suffix to get the normal
8987                        // package and APK names.
8988                        String systemProfilePath =
8989                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8990                        profileFile = new File(systemProfilePath);
8991                        // If we have a profile for a compressed APK, copy it to the reference
8992                        // location.
8993                        // Note that copying the profile here will cause it to override the
8994                        // reference profile every OTA even though the existing reference profile
8995                        // may have more data. We can't copy during decompression since the
8996                        // directories are not set up at that point.
8997                        if (profileFile.exists()) {
8998                            try {
8999                                // We could also do this lazily before calling dexopt in
9000                                // PackageDexOptimizer to prevent this happening on first boot. The
9001                                // issue is that we don't have a good way to say "do this only
9002                                // once".
9003                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9004                                        pkg.applicationInfo.uid, pkg.packageName,
9005                                        ArtManager.getProfileName(null))) {
9006                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9007                                } else {
9008                                    useProfileForDexopt = true;
9009                                }
9010                            } catch (Exception e) {
9011                                Log.e(TAG, "Failed to copy profile " +
9012                                        profileFile.getAbsolutePath() + " ", e);
9013                            }
9014                        }
9015                    }
9016                }
9017            }
9018
9019            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9020                if (DEBUG_DEXOPT) {
9021                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9022                }
9023                numberOfPackagesSkipped++;
9024                continue;
9025            }
9026
9027            if (DEBUG_DEXOPT) {
9028                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9029                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9030            }
9031
9032            if (showDialog) {
9033                try {
9034                    ActivityManager.getService().showBootMessage(
9035                            mContext.getResources().getString(R.string.android_upgrading_apk,
9036                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9037                } catch (RemoteException e) {
9038                }
9039                synchronized (mPackages) {
9040                    mDexOptDialogShown = true;
9041                }
9042            }
9043
9044            int pkgCompilationReason = compilationReason;
9045            if (useProfileForDexopt) {
9046                // Use background dexopt mode to try and use the profile. Note that this does not
9047                // guarantee usage of the profile.
9048                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9049            }
9050
9051            // checkProfiles is false to avoid merging profiles during boot which
9052            // might interfere with background compilation (b/28612421).
9053            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9054            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9055            // trade-off worth doing to save boot time work.
9056            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9057            if (compilationReason == REASON_FIRST_BOOT) {
9058                // TODO: This doesn't cover the upgrade case, we should check for this too.
9059                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9060            }
9061            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9062                    pkg.packageName,
9063                    pkgCompilationReason,
9064                    dexoptFlags));
9065
9066            switch (primaryDexOptStaus) {
9067                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9068                    numberOfPackagesOptimized++;
9069                    break;
9070                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9071                    numberOfPackagesSkipped++;
9072                    break;
9073                case PackageDexOptimizer.DEX_OPT_FAILED:
9074                    numberOfPackagesFailed++;
9075                    break;
9076                default:
9077                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9078                    break;
9079            }
9080        }
9081
9082        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9083                numberOfPackagesFailed };
9084    }
9085
9086    @Override
9087    public void notifyPackageUse(String packageName, int reason) {
9088        synchronized (mPackages) {
9089            final int callingUid = Binder.getCallingUid();
9090            final int callingUserId = UserHandle.getUserId(callingUid);
9091            if (getInstantAppPackageName(callingUid) != null) {
9092                if (!isCallerSameApp(packageName, callingUid)) {
9093                    return;
9094                }
9095            } else {
9096                if (isInstantApp(packageName, callingUserId)) {
9097                    return;
9098                }
9099            }
9100            notifyPackageUseLocked(packageName, reason);
9101        }
9102    }
9103
9104    @GuardedBy("mPackages")
9105    private void notifyPackageUseLocked(String packageName, int reason) {
9106        final PackageParser.Package p = mPackages.get(packageName);
9107        if (p == null) {
9108            return;
9109        }
9110        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9111    }
9112
9113    @Override
9114    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9115            List<String> classPaths, String loaderIsa) {
9116        int userId = UserHandle.getCallingUserId();
9117        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9118        if (ai == null) {
9119            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9120                + loadingPackageName + ", user=" + userId);
9121            return;
9122        }
9123        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9124    }
9125
9126    @Override
9127    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9128            IDexModuleRegisterCallback callback) {
9129        int userId = UserHandle.getCallingUserId();
9130        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9131        DexManager.RegisterDexModuleResult result;
9132        if (ai == null) {
9133            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9134                     " calling user. package=" + packageName + ", user=" + userId);
9135            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9136        } else {
9137            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9138        }
9139
9140        if (callback != null) {
9141            mHandler.post(() -> {
9142                try {
9143                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9144                } catch (RemoteException e) {
9145                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9146                }
9147            });
9148        }
9149    }
9150
9151    /**
9152     * Ask the package manager to perform a dex-opt with the given compiler filter.
9153     *
9154     * Note: exposed only for the shell command to allow moving packages explicitly to a
9155     *       definite state.
9156     */
9157    @Override
9158    public boolean performDexOptMode(String packageName,
9159            boolean checkProfiles, String targetCompilerFilter, boolean force,
9160            boolean bootComplete, String splitName) {
9161        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9162                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9163                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9164        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9165                targetCompilerFilter, splitName, flags));
9166    }
9167
9168    /**
9169     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9170     * secondary dex files belonging to the given package.
9171     *
9172     * Note: exposed only for the shell command to allow moving packages explicitly to a
9173     *       definite state.
9174     */
9175    @Override
9176    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9177            boolean force) {
9178        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9179                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9180                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9181                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9182        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9183    }
9184
9185    /*package*/ boolean performDexOpt(DexoptOptions options) {
9186        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9187            return false;
9188        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9189            return false;
9190        }
9191
9192        if (options.isDexoptOnlySecondaryDex()) {
9193            return mDexManager.dexoptSecondaryDex(options);
9194        } else {
9195            int dexoptStatus = performDexOptWithStatus(options);
9196            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9197        }
9198    }
9199
9200    /**
9201     * Perform dexopt on the given package and return one of following result:
9202     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9203     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9204     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9205     */
9206    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9207        return performDexOptTraced(options);
9208    }
9209
9210    private int performDexOptTraced(DexoptOptions options) {
9211        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9212        try {
9213            return performDexOptInternal(options);
9214        } finally {
9215            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9216        }
9217    }
9218
9219    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9220    // if the package can now be considered up to date for the given filter.
9221    private int performDexOptInternal(DexoptOptions options) {
9222        PackageParser.Package p;
9223        synchronized (mPackages) {
9224            p = mPackages.get(options.getPackageName());
9225            if (p == null) {
9226                // Package could not be found. Report failure.
9227                return PackageDexOptimizer.DEX_OPT_FAILED;
9228            }
9229            mPackageUsage.maybeWriteAsync(mPackages);
9230            mCompilerStats.maybeWriteAsync();
9231        }
9232        long callingId = Binder.clearCallingIdentity();
9233        try {
9234            synchronized (mInstallLock) {
9235                return performDexOptInternalWithDependenciesLI(p, options);
9236            }
9237        } finally {
9238            Binder.restoreCallingIdentity(callingId);
9239        }
9240    }
9241
9242    public ArraySet<String> getOptimizablePackages() {
9243        ArraySet<String> pkgs = new ArraySet<String>();
9244        synchronized (mPackages) {
9245            for (PackageParser.Package p : mPackages.values()) {
9246                if (PackageDexOptimizer.canOptimizePackage(p)) {
9247                    pkgs.add(p.packageName);
9248                }
9249            }
9250        }
9251        return pkgs;
9252    }
9253
9254    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9255            DexoptOptions options) {
9256        // Select the dex optimizer based on the force parameter.
9257        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9258        //       allocate an object here.
9259        PackageDexOptimizer pdo = options.isForce()
9260                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9261                : mPackageDexOptimizer;
9262
9263        // Dexopt all dependencies first. Note: we ignore the return value and march on
9264        // on errors.
9265        // Note that we are going to call performDexOpt on those libraries as many times as
9266        // they are referenced in packages. When we do a batch of performDexOpt (for example
9267        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9268        // and the first package that uses the library will dexopt it. The
9269        // others will see that the compiled code for the library is up to date.
9270        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9271        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9272        if (!deps.isEmpty()) {
9273            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9274                    options.getCompilationReason(), options.getCompilerFilter(),
9275                    options.getSplitName(),
9276                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9277            for (PackageParser.Package depPackage : deps) {
9278                // TODO: Analyze and investigate if we (should) profile libraries.
9279                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9280                        getOrCreateCompilerPackageStats(depPackage),
9281                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9282            }
9283        }
9284        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9285                getOrCreateCompilerPackageStats(p),
9286                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9287    }
9288
9289    /**
9290     * Reconcile the information we have about the secondary dex files belonging to
9291     * {@code packagName} and the actual dex files. For all dex files that were
9292     * deleted, update the internal records and delete the generated oat files.
9293     */
9294    @Override
9295    public void reconcileSecondaryDexFiles(String packageName) {
9296        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9297            return;
9298        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9299            return;
9300        }
9301        mDexManager.reconcileSecondaryDexFiles(packageName);
9302    }
9303
9304    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9305    // a reference there.
9306    /*package*/ DexManager getDexManager() {
9307        return mDexManager;
9308    }
9309
9310    /**
9311     * Execute the background dexopt job immediately.
9312     */
9313    @Override
9314    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9315        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9316            return false;
9317        }
9318        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9319    }
9320
9321    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9322        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9323                || p.usesStaticLibraries != null) {
9324            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9325            Set<String> collectedNames = new HashSet<>();
9326            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9327
9328            retValue.remove(p);
9329
9330            return retValue;
9331        } else {
9332            return Collections.emptyList();
9333        }
9334    }
9335
9336    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9337            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9338        if (!collectedNames.contains(p.packageName)) {
9339            collectedNames.add(p.packageName);
9340            collected.add(p);
9341
9342            if (p.usesLibraries != null) {
9343                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9344                        null, collected, collectedNames);
9345            }
9346            if (p.usesOptionalLibraries != null) {
9347                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9348                        null, collected, collectedNames);
9349            }
9350            if (p.usesStaticLibraries != null) {
9351                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9352                        p.usesStaticLibrariesVersions, collected, collectedNames);
9353            }
9354        }
9355    }
9356
9357    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9358            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9359        final int libNameCount = libs.size();
9360        for (int i = 0; i < libNameCount; i++) {
9361            String libName = libs.get(i);
9362            long version = (versions != null && versions.length == libNameCount)
9363                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9364            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9365            if (libPkg != null) {
9366                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9367            }
9368        }
9369    }
9370
9371    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9372        synchronized (mPackages) {
9373            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9374            if (libEntry != null) {
9375                return mPackages.get(libEntry.apk);
9376            }
9377            return null;
9378        }
9379    }
9380
9381    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9382        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9383        if (versionedLib == null) {
9384            return null;
9385        }
9386        return versionedLib.get(version);
9387    }
9388
9389    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9390        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9391                pkg.staticSharedLibName);
9392        if (versionedLib == null) {
9393            return null;
9394        }
9395        long previousLibVersion = -1;
9396        final int versionCount = versionedLib.size();
9397        for (int i = 0; i < versionCount; i++) {
9398            final long libVersion = versionedLib.keyAt(i);
9399            if (libVersion < pkg.staticSharedLibVersion) {
9400                previousLibVersion = Math.max(previousLibVersion, libVersion);
9401            }
9402        }
9403        if (previousLibVersion >= 0) {
9404            return versionedLib.get(previousLibVersion);
9405        }
9406        return null;
9407    }
9408
9409    public void shutdown() {
9410        mPackageUsage.writeNow(mPackages);
9411        mCompilerStats.writeNow();
9412        mDexManager.writePackageDexUsageNow();
9413    }
9414
9415    @Override
9416    public void dumpProfiles(String packageName) {
9417        PackageParser.Package pkg;
9418        synchronized (mPackages) {
9419            pkg = mPackages.get(packageName);
9420            if (pkg == null) {
9421                throw new IllegalArgumentException("Unknown package: " + packageName);
9422            }
9423        }
9424        /* Only the shell, root, or the app user should be able to dump profiles. */
9425        int callingUid = Binder.getCallingUid();
9426        if (callingUid != Process.SHELL_UID &&
9427            callingUid != Process.ROOT_UID &&
9428            callingUid != pkg.applicationInfo.uid) {
9429            throw new SecurityException("dumpProfiles");
9430        }
9431
9432        synchronized (mInstallLock) {
9433            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9434            mArtManagerService.dumpProfiles(pkg);
9435            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9436        }
9437    }
9438
9439    @Override
9440    public void forceDexOpt(String packageName) {
9441        enforceSystemOrRoot("forceDexOpt");
9442
9443        PackageParser.Package pkg;
9444        synchronized (mPackages) {
9445            pkg = mPackages.get(packageName);
9446            if (pkg == null) {
9447                throw new IllegalArgumentException("Unknown package: " + packageName);
9448            }
9449        }
9450
9451        synchronized (mInstallLock) {
9452            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9453
9454            // Whoever is calling forceDexOpt wants a compiled package.
9455            // Don't use profiles since that may cause compilation to be skipped.
9456            final int res = performDexOptInternalWithDependenciesLI(
9457                    pkg,
9458                    new DexoptOptions(packageName,
9459                            getDefaultCompilerFilter(),
9460                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9461
9462            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9463            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9464                throw new IllegalStateException("Failed to dexopt: " + res);
9465            }
9466        }
9467    }
9468
9469    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9470        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9471            Slog.w(TAG, "Unable to update from " + oldPkg.name
9472                    + " to " + newPkg.packageName
9473                    + ": old package not in system partition");
9474            return false;
9475        } else if (mPackages.get(oldPkg.name) != null) {
9476            Slog.w(TAG, "Unable to update from " + oldPkg.name
9477                    + " to " + newPkg.packageName
9478                    + ": old package still exists");
9479            return false;
9480        }
9481        return true;
9482    }
9483
9484    void removeCodePathLI(File codePath) {
9485        if (codePath.isDirectory()) {
9486            try {
9487                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9488            } catch (InstallerException e) {
9489                Slog.w(TAG, "Failed to remove code path", e);
9490            }
9491        } else {
9492            codePath.delete();
9493        }
9494    }
9495
9496    private int[] resolveUserIds(int userId) {
9497        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9498    }
9499
9500    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9501        if (pkg == null) {
9502            Slog.wtf(TAG, "Package was null!", new Throwable());
9503            return;
9504        }
9505        clearAppDataLeafLIF(pkg, userId, flags);
9506        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9507        for (int i = 0; i < childCount; i++) {
9508            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9509        }
9510
9511        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9512    }
9513
9514    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9515        final PackageSetting ps;
9516        synchronized (mPackages) {
9517            ps = mSettings.mPackages.get(pkg.packageName);
9518        }
9519        for (int realUserId : resolveUserIds(userId)) {
9520            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9521            try {
9522                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9523                        ceDataInode);
9524            } catch (InstallerException e) {
9525                Slog.w(TAG, String.valueOf(e));
9526            }
9527        }
9528    }
9529
9530    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9531        if (pkg == null) {
9532            Slog.wtf(TAG, "Package was null!", new Throwable());
9533            return;
9534        }
9535        destroyAppDataLeafLIF(pkg, userId, flags);
9536        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9537        for (int i = 0; i < childCount; i++) {
9538            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9539        }
9540    }
9541
9542    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9543        final PackageSetting ps;
9544        synchronized (mPackages) {
9545            ps = mSettings.mPackages.get(pkg.packageName);
9546        }
9547        for (int realUserId : resolveUserIds(userId)) {
9548            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9549            try {
9550                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9551                        ceDataInode);
9552            } catch (InstallerException e) {
9553                Slog.w(TAG, String.valueOf(e));
9554            }
9555            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9556        }
9557    }
9558
9559    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9560        if (pkg == null) {
9561            Slog.wtf(TAG, "Package was null!", new Throwable());
9562            return;
9563        }
9564        destroyAppProfilesLeafLIF(pkg);
9565        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9566        for (int i = 0; i < childCount; i++) {
9567            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9568        }
9569    }
9570
9571    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9572        try {
9573            mInstaller.destroyAppProfiles(pkg.packageName);
9574        } catch (InstallerException e) {
9575            Slog.w(TAG, String.valueOf(e));
9576        }
9577    }
9578
9579    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9580        if (pkg == null) {
9581            Slog.wtf(TAG, "Package was null!", new Throwable());
9582            return;
9583        }
9584        mArtManagerService.clearAppProfiles(pkg);
9585        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9586        for (int i = 0; i < childCount; i++) {
9587            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9588        }
9589    }
9590
9591    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9592            long lastUpdateTime) {
9593        // Set parent install/update time
9594        PackageSetting ps = (PackageSetting) pkg.mExtras;
9595        if (ps != null) {
9596            ps.firstInstallTime = firstInstallTime;
9597            ps.lastUpdateTime = lastUpdateTime;
9598        }
9599        // Set children install/update time
9600        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9601        for (int i = 0; i < childCount; i++) {
9602            PackageParser.Package childPkg = pkg.childPackages.get(i);
9603            ps = (PackageSetting) childPkg.mExtras;
9604            if (ps != null) {
9605                ps.firstInstallTime = firstInstallTime;
9606                ps.lastUpdateTime = lastUpdateTime;
9607            }
9608        }
9609    }
9610
9611    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9612            SharedLibraryEntry file,
9613            PackageParser.Package changingLib) {
9614        if (file.path != null) {
9615            usesLibraryFiles.add(file.path);
9616            return;
9617        }
9618        PackageParser.Package p = mPackages.get(file.apk);
9619        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9620            // If we are doing this while in the middle of updating a library apk,
9621            // then we need to make sure to use that new apk for determining the
9622            // dependencies here.  (We haven't yet finished committing the new apk
9623            // to the package manager state.)
9624            if (p == null || p.packageName.equals(changingLib.packageName)) {
9625                p = changingLib;
9626            }
9627        }
9628        if (p != null) {
9629            usesLibraryFiles.addAll(p.getAllCodePaths());
9630            if (p.usesLibraryFiles != null) {
9631                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9632            }
9633        }
9634    }
9635
9636    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9637            PackageParser.Package changingLib) throws PackageManagerException {
9638        if (pkg == null) {
9639            return;
9640        }
9641        // The collection used here must maintain the order of addition (so
9642        // that libraries are searched in the correct order) and must have no
9643        // duplicates.
9644        Set<String> usesLibraryFiles = null;
9645        if (pkg.usesLibraries != null) {
9646            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9647                    null, null, pkg.packageName, changingLib, true,
9648                    pkg.applicationInfo.targetSdkVersion, null);
9649        }
9650        if (pkg.usesStaticLibraries != null) {
9651            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9652                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9653                    pkg.packageName, changingLib, true,
9654                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9655        }
9656        if (pkg.usesOptionalLibraries != null) {
9657            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9658                    null, null, pkg.packageName, changingLib, false,
9659                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9660        }
9661        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9662            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9663        } else {
9664            pkg.usesLibraryFiles = null;
9665        }
9666    }
9667
9668    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9669            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9670            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9671            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9672            throws PackageManagerException {
9673        final int libCount = requestedLibraries.size();
9674        for (int i = 0; i < libCount; i++) {
9675            final String libName = requestedLibraries.get(i);
9676            final long libVersion = requiredVersions != null ? requiredVersions[i]
9677                    : SharedLibraryInfo.VERSION_UNDEFINED;
9678            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9679            if (libEntry == null) {
9680                if (required) {
9681                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9682                            "Package " + packageName + " requires unavailable shared library "
9683                                    + libName + "; failing!");
9684                } else if (DEBUG_SHARED_LIBRARIES) {
9685                    Slog.i(TAG, "Package " + packageName
9686                            + " desires unavailable shared library "
9687                            + libName + "; ignoring!");
9688                }
9689            } else {
9690                if (requiredVersions != null && requiredCertDigests != null) {
9691                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9692                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9693                            "Package " + packageName + " requires unavailable static shared"
9694                                    + " library " + libName + " version "
9695                                    + libEntry.info.getLongVersion() + "; failing!");
9696                    }
9697
9698                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9699                    if (libPkg == null) {
9700                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9701                                "Package " + packageName + " requires unavailable static shared"
9702                                        + " library; failing!");
9703                    }
9704
9705                    final String[] expectedCertDigests = requiredCertDigests[i];
9706
9707
9708                    if (expectedCertDigests.length > 1) {
9709
9710                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9711                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9712                                ? PackageUtils.computeSignaturesSha256Digests(
9713                                libPkg.mSigningDetails.signatures)
9714                                : PackageUtils.computeSignaturesSha256Digests(
9715                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9716
9717                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9718                        // target O we don't parse the "additional-certificate" tags similarly
9719                        // how we only consider all certs only for apps targeting O (see above).
9720                        // Therefore, the size check is safe to make.
9721                        if (expectedCertDigests.length != libCertDigests.length) {
9722                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9723                                    "Package " + packageName + " requires differently signed" +
9724                                            " static shared library; failing!");
9725                        }
9726
9727                        // Use a predictable order as signature order may vary
9728                        Arrays.sort(libCertDigests);
9729                        Arrays.sort(expectedCertDigests);
9730
9731                        final int certCount = libCertDigests.length;
9732                        for (int j = 0; j < certCount; j++) {
9733                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9734                                throw new PackageManagerException(
9735                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9736                                        "Package " + packageName + " requires differently signed" +
9737                                                " static shared library; failing!");
9738                            }
9739                        }
9740                    } else {
9741
9742                        // lib signing cert could have rotated beyond the one expected, check to see
9743                        // if the new one has been blessed by the old
9744                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9745                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9746                            throw new PackageManagerException(
9747                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9748                                    "Package " + packageName + " requires differently signed" +
9749                                            " static shared library; failing!");
9750                        }
9751                    }
9752                }
9753
9754                if (outUsedLibraries == null) {
9755                    // Use LinkedHashSet to preserve the order of files added to
9756                    // usesLibraryFiles while eliminating duplicates.
9757                    outUsedLibraries = new LinkedHashSet<>();
9758                }
9759                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9760            }
9761        }
9762        return outUsedLibraries;
9763    }
9764
9765    private static boolean hasString(List<String> list, List<String> which) {
9766        if (list == null) {
9767            return false;
9768        }
9769        for (int i=list.size()-1; i>=0; i--) {
9770            for (int j=which.size()-1; j>=0; j--) {
9771                if (which.get(j).equals(list.get(i))) {
9772                    return true;
9773                }
9774            }
9775        }
9776        return false;
9777    }
9778
9779    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9780            PackageParser.Package changingPkg) {
9781        ArrayList<PackageParser.Package> res = null;
9782        for (PackageParser.Package pkg : mPackages.values()) {
9783            if (changingPkg != null
9784                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9785                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9786                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9787                            changingPkg.staticSharedLibName)) {
9788                return null;
9789            }
9790            if (res == null) {
9791                res = new ArrayList<>();
9792            }
9793            res.add(pkg);
9794            try {
9795                updateSharedLibrariesLPr(pkg, changingPkg);
9796            } catch (PackageManagerException e) {
9797                // If a system app update or an app and a required lib missing we
9798                // delete the package and for updated system apps keep the data as
9799                // it is better for the user to reinstall than to be in an limbo
9800                // state. Also libs disappearing under an app should never happen
9801                // - just in case.
9802                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9803                    final int flags = pkg.isUpdatedSystemApp()
9804                            ? PackageManager.DELETE_KEEP_DATA : 0;
9805                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9806                            flags , null, true, null);
9807                }
9808                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9809            }
9810        }
9811        return res;
9812    }
9813
9814    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9815            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9816            @Nullable UserHandle user) throws PackageManagerException {
9817        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9818        // If the package has children and this is the first dive in the function
9819        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9820        // whether all packages (parent and children) would be successfully scanned
9821        // before the actual scan since scanning mutates internal state and we want
9822        // to atomically install the package and its children.
9823        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9824            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9825                scanFlags |= SCAN_CHECK_ONLY;
9826            }
9827        } else {
9828            scanFlags &= ~SCAN_CHECK_ONLY;
9829        }
9830
9831        final PackageParser.Package scannedPkg;
9832        try {
9833            // Scan the parent
9834            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9835            // Scan the children
9836            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9837            for (int i = 0; i < childCount; i++) {
9838                PackageParser.Package childPkg = pkg.childPackages.get(i);
9839                scanPackageNewLI(childPkg, parseFlags,
9840                        scanFlags, currentTime, user);
9841            }
9842        } finally {
9843            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9844        }
9845
9846        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9847            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9848        }
9849
9850        return scannedPkg;
9851    }
9852
9853    /** The result of a package scan. */
9854    private static class ScanResult {
9855        /** Whether or not the package scan was successful */
9856        public final boolean success;
9857        /**
9858         * The final package settings. This may be the same object passed in
9859         * the {@link ScanRequest}, but, with modified values.
9860         */
9861        @Nullable public final PackageSetting pkgSetting;
9862        /** ABI code paths that have changed in the package scan */
9863        @Nullable public final List<String> changedAbiCodePath;
9864        public ScanResult(
9865                boolean success,
9866                @Nullable PackageSetting pkgSetting,
9867                @Nullable List<String> changedAbiCodePath) {
9868            this.success = success;
9869            this.pkgSetting = pkgSetting;
9870            this.changedAbiCodePath = changedAbiCodePath;
9871        }
9872    }
9873
9874    /** A package to be scanned */
9875    private static class ScanRequest {
9876        /** The parsed package */
9877        @NonNull public final PackageParser.Package pkg;
9878        /** The package this package replaces */
9879        @Nullable public final PackageParser.Package oldPkg;
9880        /** Shared user settings, if the package has a shared user */
9881        @Nullable public final SharedUserSetting sharedUserSetting;
9882        /**
9883         * Package settings of the currently installed version.
9884         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9885         * during scan.
9886         */
9887        @Nullable public final PackageSetting pkgSetting;
9888        /** A copy of the settings for the currently installed version */
9889        @Nullable public final PackageSetting oldPkgSetting;
9890        /** Package settings for the disabled version on the /system partition */
9891        @Nullable public final PackageSetting disabledPkgSetting;
9892        /** Package settings for the installed version under its original package name */
9893        @Nullable public final PackageSetting originalPkgSetting;
9894        /** The real package name of a renamed application */
9895        @Nullable public final String realPkgName;
9896        public final @ParseFlags int parseFlags;
9897        public final @ScanFlags int scanFlags;
9898        /** The user for which the package is being scanned */
9899        @Nullable public final UserHandle user;
9900        /** Whether or not the platform package is being scanned */
9901        public final boolean isPlatformPackage;
9902        public ScanRequest(
9903                @NonNull PackageParser.Package pkg,
9904                @Nullable SharedUserSetting sharedUserSetting,
9905                @Nullable PackageParser.Package oldPkg,
9906                @Nullable PackageSetting pkgSetting,
9907                @Nullable PackageSetting disabledPkgSetting,
9908                @Nullable PackageSetting originalPkgSetting,
9909                @Nullable String realPkgName,
9910                @ParseFlags int parseFlags,
9911                @ScanFlags int scanFlags,
9912                boolean isPlatformPackage,
9913                @Nullable UserHandle user) {
9914            this.pkg = pkg;
9915            this.oldPkg = oldPkg;
9916            this.pkgSetting = pkgSetting;
9917            this.sharedUserSetting = sharedUserSetting;
9918            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9919            this.disabledPkgSetting = disabledPkgSetting;
9920            this.originalPkgSetting = originalPkgSetting;
9921            this.realPkgName = realPkgName;
9922            this.parseFlags = parseFlags;
9923            this.scanFlags = scanFlags;
9924            this.isPlatformPackage = isPlatformPackage;
9925            this.user = user;
9926        }
9927    }
9928
9929    /**
9930     * Returns the actual scan flags depending upon the state of the other settings.
9931     * <p>Updated system applications will not have the following flags set
9932     * by default and need to be adjusted after the fact:
9933     * <ul>
9934     * <li>{@link #SCAN_AS_SYSTEM}</li>
9935     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9936     * <li>{@link #SCAN_AS_OEM}</li>
9937     * <li>{@link #SCAN_AS_VENDOR}</li>
9938     * <li>{@link #SCAN_AS_PRODUCT}</li>
9939     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9940     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9941     * </ul>
9942     */
9943    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9944            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9945            PackageParser.Package pkg) {
9946        if (disabledPkgSetting != null) {
9947            // updated system application, must at least have SCAN_AS_SYSTEM
9948            scanFlags |= SCAN_AS_SYSTEM;
9949            if ((disabledPkgSetting.pkgPrivateFlags
9950                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9951                scanFlags |= SCAN_AS_PRIVILEGED;
9952            }
9953            if ((disabledPkgSetting.pkgPrivateFlags
9954                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9955                scanFlags |= SCAN_AS_OEM;
9956            }
9957            if ((disabledPkgSetting.pkgPrivateFlags
9958                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9959                scanFlags |= SCAN_AS_VENDOR;
9960            }
9961            if ((disabledPkgSetting.pkgPrivateFlags
9962                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9963                scanFlags |= SCAN_AS_PRODUCT;
9964            }
9965        }
9966        if (pkgSetting != null) {
9967            final int userId = ((user == null) ? 0 : user.getIdentifier());
9968            if (pkgSetting.getInstantApp(userId)) {
9969                scanFlags |= SCAN_AS_INSTANT_APP;
9970            }
9971            if (pkgSetting.getVirtulalPreload(userId)) {
9972                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9973            }
9974        }
9975
9976        // Scan as privileged apps that share a user with a priv-app.
9977        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9978                && (pkg.mSharedUserId != null)) {
9979            SharedUserSetting sharedUserSetting = null;
9980            try {
9981                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9982            } catch (PackageManagerException ignore) {}
9983            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9984                // Exempt SharedUsers signed with the platform key.
9985                // TODO(b/72378145) Fix this exemption. Force signature apps
9986                // to whitelist their privileged permissions just like other
9987                // priv-apps.
9988                synchronized (mPackages) {
9989                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9990                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9991                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9992                        scanFlags |= SCAN_AS_PRIVILEGED;
9993                    }
9994                }
9995            }
9996        }
9997
9998        return scanFlags;
9999    }
10000
10001    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10002    // the results / removing app data needs to be moved up a level to the callers of this
10003    // method. Also, we need to solve the problem of potentially creating a new shared user
10004    // setting. That can probably be done later and patch things up after the fact.
10005    @GuardedBy("mInstallLock")
10006    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10007            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10008            @Nullable UserHandle user) throws PackageManagerException {
10009
10010        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10011        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10012        if (realPkgName != null) {
10013            ensurePackageRenamed(pkg, renamedPkgName);
10014        }
10015        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10016        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10017        final PackageSetting disabledPkgSetting =
10018                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10019
10020        if (mTransferedPackages.contains(pkg.packageName)) {
10021            Slog.w(TAG, "Package " + pkg.packageName
10022                    + " was transferred to another, but its .apk remains");
10023        }
10024
10025        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10026        synchronized (mPackages) {
10027            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10028            assertPackageIsValid(pkg, parseFlags, scanFlags);
10029
10030            SharedUserSetting sharedUserSetting = null;
10031            if (pkg.mSharedUserId != null) {
10032                // SIDE EFFECTS; may potentially allocate a new shared user
10033                sharedUserSetting = mSettings.getSharedUserLPw(
10034                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10035                if (DEBUG_PACKAGE_SCANNING) {
10036                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10037                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10038                                + " (uid=" + sharedUserSetting.userId + "):"
10039                                + " packages=" + sharedUserSetting.packages);
10040                }
10041            }
10042
10043            boolean scanSucceeded = false;
10044            try {
10045                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10046                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10047                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10048                        (pkg == mPlatformPackage), user);
10049                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10050                if (result.success) {
10051                    commitScanResultsLocked(request, result);
10052                }
10053                scanSucceeded = true;
10054            } finally {
10055                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10056                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10057                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10058                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10059                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10060                  }
10061            }
10062        }
10063        return pkg;
10064    }
10065
10066    /**
10067     * Commits the package scan and modifies system state.
10068     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10069     * of committing the package, leaving the system in an inconsistent state.
10070     * This needs to be fixed so, once we get to this point, no errors are
10071     * possible and the system is not left in an inconsistent state.
10072     */
10073    @GuardedBy("mPackages")
10074    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10075            throws PackageManagerException {
10076        final PackageParser.Package pkg = request.pkg;
10077        final PackageParser.Package oldPkg = request.oldPkg;
10078        final @ParseFlags int parseFlags = request.parseFlags;
10079        final @ScanFlags int scanFlags = request.scanFlags;
10080        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10081        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10082        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10083        final UserHandle user = request.user;
10084        final String realPkgName = request.realPkgName;
10085        final PackageSetting pkgSetting = result.pkgSetting;
10086        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10087        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10088
10089        if (newPkgSettingCreated) {
10090            if (originalPkgSetting != null) {
10091                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10092            }
10093            // THROWS: when we can't allocate a user id. add call to check if there's
10094            // enough space to ensure we won't throw; otherwise, don't modify state
10095            mSettings.addUserToSettingLPw(pkgSetting);
10096
10097            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10098                mTransferedPackages.add(originalPkgSetting.name);
10099            }
10100        }
10101        // TODO(toddke): Consider a method specifically for modifying the Package object
10102        // post scan; or, moving this stuff out of the Package object since it has nothing
10103        // to do with the package on disk.
10104        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10105        // for creating the application ID. If we did this earlier, we would be saving the
10106        // correct ID.
10107        pkg.applicationInfo.uid = pkgSetting.appId;
10108
10109        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10110
10111        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10112            mTransferedPackages.add(pkg.packageName);
10113        }
10114
10115        // THROWS: when requested libraries that can't be found. it only changes
10116        // the state of the passed in pkg object, so, move to the top of the method
10117        // and allow it to abort
10118        if ((scanFlags & SCAN_BOOTING) == 0
10119                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10120            // Check all shared libraries and map to their actual file path.
10121            // We only do this here for apps not on a system dir, because those
10122            // are the only ones that can fail an install due to this.  We
10123            // will take care of the system apps by updating all of their
10124            // library paths after the scan is done. Also during the initial
10125            // scan don't update any libs as we do this wholesale after all
10126            // apps are scanned to avoid dependency based scanning.
10127            updateSharedLibrariesLPr(pkg, null);
10128        }
10129
10130        // All versions of a static shared library are referenced with the same
10131        // package name. Internally, we use a synthetic package name to allow
10132        // multiple versions of the same shared library to be installed. So,
10133        // we need to generate the synthetic package name of the latest shared
10134        // library in order to compare signatures.
10135        PackageSetting signatureCheckPs = pkgSetting;
10136        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10137            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10138            if (libraryEntry != null) {
10139                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10140            }
10141        }
10142
10143        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10144        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10145            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10146                // We just determined the app is signed correctly, so bring
10147                // over the latest parsed certs.
10148                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10149            } else {
10150                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10151                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10152                            "Package " + pkg.packageName + " upgrade keys do not match the "
10153                                    + "previously installed version");
10154                } else {
10155                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10156                    String msg = "System package " + pkg.packageName
10157                            + " signature changed; retaining data.";
10158                    reportSettingsProblem(Log.WARN, msg);
10159                }
10160            }
10161        } else {
10162            try {
10163                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10164                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10165                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10166                        pkg.mSigningDetails, compareCompat, compareRecover);
10167                // The new KeySets will be re-added later in the scanning process.
10168                if (compatMatch) {
10169                    synchronized (mPackages) {
10170                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10171                    }
10172                }
10173                // We just determined the app is signed correctly, so bring
10174                // over the latest parsed certs.
10175                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10176
10177
10178                // if this is is a sharedUser, check to see if the new package is signed by a newer
10179                // signing certificate than the existing one, and if so, copy over the new details
10180                if (signatureCheckPs.sharedUser != null
10181                        && pkg.mSigningDetails.hasAncestor(
10182                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10183                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10184                }
10185            } catch (PackageManagerException e) {
10186                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10187                    throw e;
10188                }
10189                // The signature has changed, but this package is in the system
10190                // image...  let's recover!
10191                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10192                // If the system app is part of a shared user we allow that shared user to change
10193                // signatures as well in part as part of an OTA.
10194                if (signatureCheckPs.sharedUser != null) {
10195                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10196                }
10197                // File a report about this.
10198                String msg = "System package " + pkg.packageName
10199                        + " signature changed; retaining data.";
10200                reportSettingsProblem(Log.WARN, msg);
10201            } catch (IllegalArgumentException e) {
10202
10203                // should never happen: certs matched when checking, but not when comparing
10204                // old to new for sharedUser
10205                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10206                        "Signing certificates comparison made on incomparable signing details"
10207                        + " but somehow passed verifySignatures!");
10208            }
10209        }
10210
10211        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10212            // This package wants to adopt ownership of permissions from
10213            // another package.
10214            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10215                final String origName = pkg.mAdoptPermissions.get(i);
10216                final PackageSetting orig = mSettings.getPackageLPr(origName);
10217                if (orig != null) {
10218                    if (verifyPackageUpdateLPr(orig, pkg)) {
10219                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10220                                + pkg.packageName);
10221                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10222                    }
10223                }
10224            }
10225        }
10226
10227        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10228            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10229                final String codePathString = changedAbiCodePath.get(i);
10230                try {
10231                    mInstaller.rmdex(codePathString,
10232                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10233                } catch (InstallerException ignored) {
10234                }
10235            }
10236        }
10237
10238        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10239            if (oldPkgSetting != null) {
10240                synchronized (mPackages) {
10241                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10242                }
10243            }
10244        } else {
10245            final int userId = user == null ? 0 : user.getIdentifier();
10246            // Modify state for the given package setting
10247            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10248                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10249            if (pkgSetting.getInstantApp(userId)) {
10250                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10251            }
10252        }
10253    }
10254
10255    /**
10256     * Returns the "real" name of the package.
10257     * <p>This may differ from the package's actual name if the application has already
10258     * been installed under one of this package's original names.
10259     */
10260    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10261            @Nullable String renamedPkgName) {
10262        if (isPackageRenamed(pkg, renamedPkgName)) {
10263            return pkg.mRealPackage;
10264        }
10265        return null;
10266    }
10267
10268    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10269    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10270            @Nullable String renamedPkgName) {
10271        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10272    }
10273
10274    /**
10275     * Returns the original package setting.
10276     * <p>A package can migrate its name during an update. In this scenario, a package
10277     * designates a set of names that it considers as one of its original names.
10278     * <p>An original package must be signed identically and it must have the same
10279     * shared user [if any].
10280     */
10281    @GuardedBy("mPackages")
10282    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10283            @Nullable String renamedPkgName) {
10284        if (!isPackageRenamed(pkg, renamedPkgName)) {
10285            return null;
10286        }
10287        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10288            final PackageSetting originalPs =
10289                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10290            if (originalPs != null) {
10291                // the package is already installed under its original name...
10292                // but, should we use it?
10293                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10294                    // the new package is incompatible with the original
10295                    continue;
10296                } else if (originalPs.sharedUser != null) {
10297                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10298                        // the shared user id is incompatible with the original
10299                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10300                                + " to " + pkg.packageName + ": old uid "
10301                                + originalPs.sharedUser.name
10302                                + " differs from " + pkg.mSharedUserId);
10303                        continue;
10304                    }
10305                    // TODO: Add case when shared user id is added [b/28144775]
10306                } else {
10307                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10308                            + pkg.packageName + " to old name " + originalPs.name);
10309                }
10310                return originalPs;
10311            }
10312        }
10313        return null;
10314    }
10315
10316    /**
10317     * Renames the package if it was installed under a different name.
10318     * <p>When we've already installed the package under an original name, update
10319     * the new package so we can continue to have the old name.
10320     */
10321    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10322            @NonNull String renamedPackageName) {
10323        if (pkg.mOriginalPackages == null
10324                || !pkg.mOriginalPackages.contains(renamedPackageName)
10325                || pkg.packageName.equals(renamedPackageName)) {
10326            return;
10327        }
10328        pkg.setPackageName(renamedPackageName);
10329    }
10330
10331    /**
10332     * Just scans the package without any side effects.
10333     * <p>Not entirely true at the moment. There is still one side effect -- this
10334     * method potentially modifies a live {@link PackageSetting} object representing
10335     * the package being scanned. This will be resolved in the future.
10336     *
10337     * @param request Information about the package to be scanned
10338     * @param isUnderFactoryTest Whether or not the device is under factory test
10339     * @param currentTime The current time, in millis
10340     * @return The results of the scan
10341     */
10342    @GuardedBy("mInstallLock")
10343    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10344            boolean isUnderFactoryTest, long currentTime)
10345                    throws PackageManagerException {
10346        final PackageParser.Package pkg = request.pkg;
10347        PackageSetting pkgSetting = request.pkgSetting;
10348        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10349        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10350        final @ParseFlags int parseFlags = request.parseFlags;
10351        final @ScanFlags int scanFlags = request.scanFlags;
10352        final String realPkgName = request.realPkgName;
10353        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10354        final UserHandle user = request.user;
10355        final boolean isPlatformPackage = request.isPlatformPackage;
10356
10357        List<String> changedAbiCodePath = null;
10358
10359        if (DEBUG_PACKAGE_SCANNING) {
10360            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10361                Log.d(TAG, "Scanning package " + pkg.packageName);
10362        }
10363
10364        if (Build.IS_DEBUGGABLE &&
10365                pkg.isPrivileged() &&
10366                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10367            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10368        }
10369
10370        // Initialize package source and resource directories
10371        final File scanFile = new File(pkg.codePath);
10372        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10373        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10374
10375        // We keep references to the derived CPU Abis from settings in oder to reuse
10376        // them in the case where we're not upgrading or booting for the first time.
10377        String primaryCpuAbiFromSettings = null;
10378        String secondaryCpuAbiFromSettings = null;
10379        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10380
10381        if (!needToDeriveAbi) {
10382            if (pkgSetting != null) {
10383                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10384                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10385            } else {
10386                // Re-scanning a system package after uninstalling updates; need to derive ABI
10387                needToDeriveAbi = true;
10388            }
10389        }
10390
10391        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10392            PackageManagerService.reportSettingsProblem(Log.WARN,
10393                    "Package " + pkg.packageName + " shared user changed from "
10394                            + (pkgSetting.sharedUser != null
10395                            ? pkgSetting.sharedUser.name : "<nothing>")
10396                            + " to "
10397                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10398                            + "; replacing with new");
10399            pkgSetting = null;
10400        }
10401
10402        String[] usesStaticLibraries = null;
10403        if (pkg.usesStaticLibraries != null) {
10404            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10405            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10406        }
10407        final boolean createNewPackage = (pkgSetting == null);
10408        if (createNewPackage) {
10409            final String parentPackageName = (pkg.parentPackage != null)
10410                    ? pkg.parentPackage.packageName : null;
10411            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10412            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10413            // REMOVE SharedUserSetting from method; update in a separate call
10414            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10415                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10416                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10417                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10418                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10419                    user, true /*allowInstall*/, instantApp, virtualPreload,
10420                    parentPackageName, pkg.getChildPackageNames(),
10421                    UserManagerService.getInstance(), usesStaticLibraries,
10422                    pkg.usesStaticLibrariesVersions);
10423        } else {
10424            // REMOVE SharedUserSetting from method; update in a separate call.
10425            //
10426            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10427            // secondaryCpuAbi are not known at this point so we always update them
10428            // to null here, only to reset them at a later point.
10429            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10430                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10431                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10432                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10433                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10434                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10435        }
10436        if (createNewPackage && originalPkgSetting != null) {
10437            // This is the initial transition from the original package, so,
10438            // fix up the new package's name now. We must do this after looking
10439            // up the package under its new name, so getPackageLP takes care of
10440            // fiddling things correctly.
10441            pkg.setPackageName(originalPkgSetting.name);
10442
10443            // File a report about this.
10444            String msg = "New package " + pkgSetting.realName
10445                    + " renamed to replace old package " + pkgSetting.name;
10446            reportSettingsProblem(Log.WARN, msg);
10447        }
10448
10449        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10450        // for existing packages, change the install state; but, only if it's explicitly specified
10451        if (!createNewPackage) {
10452            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10453            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10454            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10455        }
10456
10457        if (disabledPkgSetting != null) {
10458            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10459        }
10460
10461        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10462        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10463        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10464        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10465        // least restrictive selinux domain.
10466        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10467        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10468        // ensures that all packages continue to run in the same selinux domain.
10469        final int targetSdkVersion =
10470            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10471            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10472        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10473        // They currently can be if the sharedUser apps are signed with the platform key.
10474        final boolean isPrivileged = (sharedUserSetting != null) ?
10475            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10476
10477        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10478                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10479        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10480                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10481
10482        pkg.mExtras = pkgSetting;
10483        pkg.applicationInfo.processName = fixProcessName(
10484                pkg.applicationInfo.packageName,
10485                pkg.applicationInfo.processName);
10486
10487        if (!isPlatformPackage) {
10488            // Get all of our default paths setup
10489            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10490        }
10491
10492        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10493
10494        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10495            if (needToDeriveAbi) {
10496                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10497                final boolean extractNativeLibs = !pkg.isLibrary();
10498                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10499                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10500
10501                // Some system apps still use directory structure for native libraries
10502                // in which case we might end up not detecting abi solely based on apk
10503                // structure. Try to detect abi based on directory structure.
10504                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10505                        pkg.applicationInfo.primaryCpuAbi == null) {
10506                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10507                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10508                }
10509            } else {
10510                // This is not a first boot or an upgrade, don't bother deriving the
10511                // ABI during the scan. Instead, trust the value that was stored in the
10512                // package setting.
10513                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10514                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10515
10516                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10517
10518                if (DEBUG_ABI_SELECTION) {
10519                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10520                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10521                            pkg.applicationInfo.secondaryCpuAbi);
10522                }
10523            }
10524        } else {
10525            if ((scanFlags & SCAN_MOVE) != 0) {
10526                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10527                // but we already have this packages package info in the PackageSetting. We just
10528                // use that and derive the native library path based on the new codepath.
10529                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10530                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10531            }
10532
10533            // Set native library paths again. For moves, the path will be updated based on the
10534            // ABIs we've determined above. For non-moves, the path will be updated based on the
10535            // ABIs we determined during compilation, but the path will depend on the final
10536            // package path (after the rename away from the stage path).
10537            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10538        }
10539
10540        // This is a special case for the "system" package, where the ABI is
10541        // dictated by the zygote configuration (and init.rc). We should keep track
10542        // of this ABI so that we can deal with "normal" applications that run under
10543        // the same UID correctly.
10544        if (isPlatformPackage) {
10545            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10546                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10547        }
10548
10549        // If there's a mismatch between the abi-override in the package setting
10550        // and the abiOverride specified for the install. Warn about this because we
10551        // would've already compiled the app without taking the package setting into
10552        // account.
10553        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10554            if (cpuAbiOverride == null && pkg.packageName != null) {
10555                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10556                        " for package " + pkg.packageName);
10557            }
10558        }
10559
10560        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10561        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10562        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10563
10564        // Copy the derived override back to the parsed package, so that we can
10565        // update the package settings accordingly.
10566        pkg.cpuAbiOverride = cpuAbiOverride;
10567
10568        if (DEBUG_ABI_SELECTION) {
10569            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10570                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10571                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10572        }
10573
10574        // Push the derived path down into PackageSettings so we know what to
10575        // clean up at uninstall time.
10576        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10577
10578        if (DEBUG_ABI_SELECTION) {
10579            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10580                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10581                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10582        }
10583
10584        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10585            // We don't do this here during boot because we can do it all
10586            // at once after scanning all existing packages.
10587            //
10588            // We also do this *before* we perform dexopt on this package, so that
10589            // we can avoid redundant dexopts, and also to make sure we've got the
10590            // code and package path correct.
10591            changedAbiCodePath =
10592                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10593        }
10594
10595        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10596                android.Manifest.permission.FACTORY_TEST)) {
10597            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10598        }
10599
10600        if (isSystemApp(pkg)) {
10601            pkgSetting.isOrphaned = true;
10602        }
10603
10604        // Take care of first install / last update times.
10605        final long scanFileTime = getLastModifiedTime(pkg);
10606        if (currentTime != 0) {
10607            if (pkgSetting.firstInstallTime == 0) {
10608                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10609            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10610                pkgSetting.lastUpdateTime = currentTime;
10611            }
10612        } else if (pkgSetting.firstInstallTime == 0) {
10613            // We need *something*.  Take time time stamp of the file.
10614            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10615        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10616            if (scanFileTime != pkgSetting.timeStamp) {
10617                // A package on the system image has changed; consider this
10618                // to be an update.
10619                pkgSetting.lastUpdateTime = scanFileTime;
10620            }
10621        }
10622        pkgSetting.setTimeStamp(scanFileTime);
10623
10624        pkgSetting.pkg = pkg;
10625        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10626        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10627            pkgSetting.versionCode = pkg.getLongVersionCode();
10628        }
10629        // Update volume if needed
10630        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10631        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10632            Slog.i(PackageManagerService.TAG,
10633                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10634                    + " package " + pkg.packageName
10635                    + " volume from " + pkgSetting.volumeUuid
10636                    + " to " + volumeUuid);
10637            pkgSetting.volumeUuid = volumeUuid;
10638        }
10639
10640        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10641    }
10642
10643    /**
10644     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10645     */
10646    private static boolean apkHasCode(String fileName) {
10647        StrictJarFile jarFile = null;
10648        try {
10649            jarFile = new StrictJarFile(fileName,
10650                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10651            return jarFile.findEntry("classes.dex") != null;
10652        } catch (IOException ignore) {
10653        } finally {
10654            try {
10655                if (jarFile != null) {
10656                    jarFile.close();
10657                }
10658            } catch (IOException ignore) {}
10659        }
10660        return false;
10661    }
10662
10663    /**
10664     * Enforces code policy for the package. This ensures that if an APK has
10665     * declared hasCode="true" in its manifest that the APK actually contains
10666     * code.
10667     *
10668     * @throws PackageManagerException If bytecode could not be found when it should exist
10669     */
10670    private static void assertCodePolicy(PackageParser.Package pkg)
10671            throws PackageManagerException {
10672        final boolean shouldHaveCode =
10673                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10674        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10675            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10676                    "Package " + pkg.baseCodePath + " code is missing");
10677        }
10678
10679        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10680            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10681                final boolean splitShouldHaveCode =
10682                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10683                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10684                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10685                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10686                }
10687            }
10688        }
10689    }
10690
10691    /**
10692     * Applies policy to the parsed package based upon the given policy flags.
10693     * Ensures the package is in a good state.
10694     * <p>
10695     * Implementation detail: This method must NOT have any side effect. It would
10696     * ideally be static, but, it requires locks to read system state.
10697     */
10698    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10699            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10700        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10701            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10702            if (pkg.applicationInfo.isDirectBootAware()) {
10703                // we're direct boot aware; set for all components
10704                for (PackageParser.Service s : pkg.services) {
10705                    s.info.encryptionAware = s.info.directBootAware = true;
10706                }
10707                for (PackageParser.Provider p : pkg.providers) {
10708                    p.info.encryptionAware = p.info.directBootAware = true;
10709                }
10710                for (PackageParser.Activity a : pkg.activities) {
10711                    a.info.encryptionAware = a.info.directBootAware = true;
10712                }
10713                for (PackageParser.Activity r : pkg.receivers) {
10714                    r.info.encryptionAware = r.info.directBootAware = true;
10715                }
10716            }
10717            if (compressedFileExists(pkg.codePath)) {
10718                pkg.isStub = true;
10719            }
10720        } else {
10721            // non system apps can't be flagged as core
10722            pkg.coreApp = false;
10723            // clear flags not applicable to regular apps
10724            pkg.applicationInfo.flags &=
10725                    ~ApplicationInfo.FLAG_PERSISTENT;
10726            pkg.applicationInfo.privateFlags &=
10727                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10728            pkg.applicationInfo.privateFlags &=
10729                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10730            // cap permission priorities
10731            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10732                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10733                    pkg.permissionGroups.get(i).info.priority = 0;
10734                }
10735            }
10736        }
10737        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10738            // clear protected broadcasts
10739            pkg.protectedBroadcasts = null;
10740            // ignore export request for single user receivers
10741            if (pkg.receivers != null) {
10742                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10743                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10744                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10745                        receiver.info.exported = false;
10746                    }
10747                }
10748            }
10749            // ignore export request for single user services
10750            if (pkg.services != null) {
10751                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10752                    final PackageParser.Service service = pkg.services.get(i);
10753                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10754                        service.info.exported = false;
10755                    }
10756                }
10757            }
10758            // ignore export request for single user providers
10759            if (pkg.providers != null) {
10760                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10761                    final PackageParser.Provider provider = pkg.providers.get(i);
10762                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10763                        provider.info.exported = false;
10764                    }
10765                }
10766            }
10767        }
10768
10769        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10770            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10771        }
10772
10773        if ((scanFlags & SCAN_AS_OEM) != 0) {
10774            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10775        }
10776
10777        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10778            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10779        }
10780
10781        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10782            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10783        }
10784
10785        // Check if the package is signed with the same key as the platform package.
10786        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10787                (platformPkg != null && compareSignatures(
10788                        platformPkg.mSigningDetails.signatures,
10789                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10790            pkg.applicationInfo.privateFlags |=
10791                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10792        }
10793
10794        if (!isSystemApp(pkg)) {
10795            // Only system apps can use these features.
10796            pkg.mOriginalPackages = null;
10797            pkg.mRealPackage = null;
10798            pkg.mAdoptPermissions = null;
10799        }
10800    }
10801
10802    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10803            throws PackageManagerException {
10804        if (object == null) {
10805            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10806        }
10807        return object;
10808    }
10809
10810    /**
10811     * Asserts the parsed package is valid according to the given policy. If the
10812     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10813     * <p>
10814     * Implementation detail: This method must NOT have any side effects. It would
10815     * ideally be static, but, it requires locks to read system state.
10816     *
10817     * @throws PackageManagerException If the package fails any of the validation checks
10818     */
10819    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10820            final @ScanFlags int scanFlags)
10821                    throws PackageManagerException {
10822        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10823            assertCodePolicy(pkg);
10824        }
10825
10826        if (pkg.applicationInfo.getCodePath() == null ||
10827                pkg.applicationInfo.getResourcePath() == null) {
10828            // Bail out. The resource and code paths haven't been set.
10829            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10830                    "Code and resource paths haven't been set correctly");
10831        }
10832
10833        // Make sure we're not adding any bogus keyset info
10834        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10835        ksms.assertScannedPackageValid(pkg);
10836
10837        synchronized (mPackages) {
10838            // The special "android" package can only be defined once
10839            if (pkg.packageName.equals("android")) {
10840                if (mAndroidApplication != null) {
10841                    Slog.w(TAG, "*************************************************");
10842                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10843                    Slog.w(TAG, " codePath=" + pkg.codePath);
10844                    Slog.w(TAG, "*************************************************");
10845                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10846                            "Core android package being redefined.  Skipping.");
10847                }
10848            }
10849
10850            // A package name must be unique; don't allow duplicates
10851            if (mPackages.containsKey(pkg.packageName)) {
10852                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10853                        "Application package " + pkg.packageName
10854                        + " already installed.  Skipping duplicate.");
10855            }
10856
10857            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10858                // Static libs have a synthetic package name containing the version
10859                // but we still want the base name to be unique.
10860                if (mPackages.containsKey(pkg.manifestPackageName)) {
10861                    throw new PackageManagerException(
10862                            "Duplicate static shared lib provider package");
10863                }
10864
10865                // Static shared libraries should have at least O target SDK
10866                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10867                    throw new PackageManagerException(
10868                            "Packages declaring static-shared libs must target O SDK or higher");
10869                }
10870
10871                // Package declaring static a shared lib cannot be instant apps
10872                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10873                    throw new PackageManagerException(
10874                            "Packages declaring static-shared libs cannot be instant apps");
10875                }
10876
10877                // Package declaring static a shared lib cannot be renamed since the package
10878                // name is synthetic and apps can't code around package manager internals.
10879                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10880                    throw new PackageManagerException(
10881                            "Packages declaring static-shared libs cannot be renamed");
10882                }
10883
10884                // Package declaring static a shared lib cannot declare child packages
10885                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10886                    throw new PackageManagerException(
10887                            "Packages declaring static-shared libs cannot have child packages");
10888                }
10889
10890                // Package declaring static a shared lib cannot declare dynamic libs
10891                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10892                    throw new PackageManagerException(
10893                            "Packages declaring static-shared libs cannot declare dynamic libs");
10894                }
10895
10896                // Package declaring static a shared lib cannot declare shared users
10897                if (pkg.mSharedUserId != null) {
10898                    throw new PackageManagerException(
10899                            "Packages declaring static-shared libs cannot declare shared users");
10900                }
10901
10902                // Static shared libs cannot declare activities
10903                if (!pkg.activities.isEmpty()) {
10904                    throw new PackageManagerException(
10905                            "Static shared libs cannot declare activities");
10906                }
10907
10908                // Static shared libs cannot declare services
10909                if (!pkg.services.isEmpty()) {
10910                    throw new PackageManagerException(
10911                            "Static shared libs cannot declare services");
10912                }
10913
10914                // Static shared libs cannot declare providers
10915                if (!pkg.providers.isEmpty()) {
10916                    throw new PackageManagerException(
10917                            "Static shared libs cannot declare content providers");
10918                }
10919
10920                // Static shared libs cannot declare receivers
10921                if (!pkg.receivers.isEmpty()) {
10922                    throw new PackageManagerException(
10923                            "Static shared libs cannot declare broadcast receivers");
10924                }
10925
10926                // Static shared libs cannot declare permission groups
10927                if (!pkg.permissionGroups.isEmpty()) {
10928                    throw new PackageManagerException(
10929                            "Static shared libs cannot declare permission groups");
10930                }
10931
10932                // Static shared libs cannot declare permissions
10933                if (!pkg.permissions.isEmpty()) {
10934                    throw new PackageManagerException(
10935                            "Static shared libs cannot declare permissions");
10936                }
10937
10938                // Static shared libs cannot declare protected broadcasts
10939                if (pkg.protectedBroadcasts != null) {
10940                    throw new PackageManagerException(
10941                            "Static shared libs cannot declare protected broadcasts");
10942                }
10943
10944                // Static shared libs cannot be overlay targets
10945                if (pkg.mOverlayTarget != null) {
10946                    throw new PackageManagerException(
10947                            "Static shared libs cannot be overlay targets");
10948                }
10949
10950                // The version codes must be ordered as lib versions
10951                long minVersionCode = Long.MIN_VALUE;
10952                long maxVersionCode = Long.MAX_VALUE;
10953
10954                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10955                        pkg.staticSharedLibName);
10956                if (versionedLib != null) {
10957                    final int versionCount = versionedLib.size();
10958                    for (int i = 0; i < versionCount; i++) {
10959                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10960                        final long libVersionCode = libInfo.getDeclaringPackage()
10961                                .getLongVersionCode();
10962                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10963                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10964                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10965                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10966                        } else {
10967                            minVersionCode = maxVersionCode = libVersionCode;
10968                            break;
10969                        }
10970                    }
10971                }
10972                if (pkg.getLongVersionCode() < minVersionCode
10973                        || pkg.getLongVersionCode() > maxVersionCode) {
10974                    throw new PackageManagerException("Static shared"
10975                            + " lib version codes must be ordered as lib versions");
10976                }
10977            }
10978
10979            // Only privileged apps and updated privileged apps can add child packages.
10980            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10981                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10982                    throw new PackageManagerException("Only privileged apps can add child "
10983                            + "packages. Ignoring package " + pkg.packageName);
10984                }
10985                final int childCount = pkg.childPackages.size();
10986                for (int i = 0; i < childCount; i++) {
10987                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10988                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10989                            childPkg.packageName)) {
10990                        throw new PackageManagerException("Can't override child of "
10991                                + "another disabled app. Ignoring package " + pkg.packageName);
10992                    }
10993                }
10994            }
10995
10996            // If we're only installing presumed-existing packages, require that the
10997            // scanned APK is both already known and at the path previously established
10998            // for it.  Previously unknown packages we pick up normally, but if we have an
10999            // a priori expectation about this package's install presence, enforce it.
11000            // With a singular exception for new system packages. When an OTA contains
11001            // a new system package, we allow the codepath to change from a system location
11002            // to the user-installed location. If we don't allow this change, any newer,
11003            // user-installed version of the application will be ignored.
11004            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11005                if (mExpectingBetter.containsKey(pkg.packageName)) {
11006                    logCriticalInfo(Log.WARN,
11007                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11008                } else {
11009                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11010                    if (known != null) {
11011                        if (DEBUG_PACKAGE_SCANNING) {
11012                            Log.d(TAG, "Examining " + pkg.codePath
11013                                    + " and requiring known paths " + known.codePathString
11014                                    + " & " + known.resourcePathString);
11015                        }
11016                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11017                                || !pkg.applicationInfo.getResourcePath().equals(
11018                                        known.resourcePathString)) {
11019                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11020                                    "Application package " + pkg.packageName
11021                                    + " found at " + pkg.applicationInfo.getCodePath()
11022                                    + " but expected at " + known.codePathString
11023                                    + "; ignoring.");
11024                        }
11025                    } else {
11026                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11027                                "Application package " + pkg.packageName
11028                                + " not found; ignoring.");
11029                    }
11030                }
11031            }
11032
11033            // Verify that this new package doesn't have any content providers
11034            // that conflict with existing packages.  Only do this if the
11035            // package isn't already installed, since we don't want to break
11036            // things that are installed.
11037            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11038                final int N = pkg.providers.size();
11039                int i;
11040                for (i=0; i<N; i++) {
11041                    PackageParser.Provider p = pkg.providers.get(i);
11042                    if (p.info.authority != null) {
11043                        String names[] = p.info.authority.split(";");
11044                        for (int j = 0; j < names.length; j++) {
11045                            if (mProvidersByAuthority.containsKey(names[j])) {
11046                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11047                                final String otherPackageName =
11048                                        ((other != null && other.getComponentName() != null) ?
11049                                                other.getComponentName().getPackageName() : "?");
11050                                throw new PackageManagerException(
11051                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11052                                        "Can't install because provider name " + names[j]
11053                                                + " (in package " + pkg.applicationInfo.packageName
11054                                                + ") is already used by " + otherPackageName);
11055                            }
11056                        }
11057                    }
11058                }
11059            }
11060
11061            // Verify that packages sharing a user with a privileged app are marked as privileged.
11062            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11063                SharedUserSetting sharedUserSetting = null;
11064                try {
11065                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11066                } catch (PackageManagerException ignore) {}
11067                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11068                    // Exempt SharedUsers signed with the platform key.
11069                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11070                    if ((platformPkgSetting.signatures.mSigningDetails
11071                            != PackageParser.SigningDetails.UNKNOWN)
11072                            && (compareSignatures(
11073                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11074                                    pkg.mSigningDetails.signatures)
11075                                            != PackageManager.SIGNATURE_MATCH)) {
11076                        throw new PackageManagerException("Apps that share a user with a " +
11077                                "privileged app must themselves be marked as privileged. " +
11078                                pkg.packageName + " shares privileged user " +
11079                                pkg.mSharedUserId + ".");
11080                    }
11081                }
11082            }
11083
11084            // Apply policies specific for runtime resource overlays (RROs).
11085            if (pkg.mOverlayTarget != null) {
11086                // System overlays have some restrictions on their use of the 'static' state.
11087                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11088                    // We are scanning a system overlay. This can be the first scan of the
11089                    // system/vendor/oem partition, or an update to the system overlay.
11090                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11091                        // This must be an update to a system overlay.
11092                        final PackageSetting previousPkg = assertNotNull(
11093                                mSettings.getPackageLPr(pkg.packageName),
11094                                "previous package state not present");
11095
11096                        // Static overlays cannot be updated.
11097                        if (previousPkg.pkg.mOverlayIsStatic) {
11098                            throw new PackageManagerException("Overlay " + pkg.packageName +
11099                                    " is static and cannot be upgraded.");
11100                        // Non-static overlays cannot be converted to static overlays.
11101                        } else if (pkg.mOverlayIsStatic) {
11102                            throw new PackageManagerException("Overlay " + pkg.packageName +
11103                                    " cannot be upgraded into a static overlay.");
11104                        }
11105                    }
11106                } else {
11107                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11108                    if (pkg.mOverlayIsStatic) {
11109                        throw new PackageManagerException("Overlay " + pkg.packageName +
11110                                " is static but not pre-installed.");
11111                    }
11112
11113                    // The only case where we allow installation of a non-system overlay is when
11114                    // its signature is signed with the platform certificate.
11115                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11116                    if ((platformPkgSetting.signatures.mSigningDetails
11117                            != PackageParser.SigningDetails.UNKNOWN)
11118                            && (compareSignatures(
11119                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11120                                    pkg.mSigningDetails.signatures)
11121                                            != PackageManager.SIGNATURE_MATCH)) {
11122                        throw new PackageManagerException("Overlay " + pkg.packageName +
11123                                " must be signed with the platform certificate.");
11124                    }
11125                }
11126            }
11127        }
11128    }
11129
11130    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11131            int type, String declaringPackageName, long declaringVersionCode) {
11132        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11133        if (versionedLib == null) {
11134            versionedLib = new LongSparseArray<>();
11135            mSharedLibraries.put(name, versionedLib);
11136            if (type == SharedLibraryInfo.TYPE_STATIC) {
11137                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11138            }
11139        } else if (versionedLib.indexOfKey(version) >= 0) {
11140            return false;
11141        }
11142        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11143                version, type, declaringPackageName, declaringVersionCode);
11144        versionedLib.put(version, libEntry);
11145        return true;
11146    }
11147
11148    private boolean removeSharedLibraryLPw(String name, long version) {
11149        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11150        if (versionedLib == null) {
11151            return false;
11152        }
11153        final int libIdx = versionedLib.indexOfKey(version);
11154        if (libIdx < 0) {
11155            return false;
11156        }
11157        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11158        versionedLib.remove(version);
11159        if (versionedLib.size() <= 0) {
11160            mSharedLibraries.remove(name);
11161            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11162                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11163                        .getPackageName());
11164            }
11165        }
11166        return true;
11167    }
11168
11169    /**
11170     * Adds a scanned package to the system. When this method is finished, the package will
11171     * be available for query, resolution, etc...
11172     */
11173    private void commitPackageSettings(PackageParser.Package pkg,
11174            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11175            final @ScanFlags int scanFlags, boolean chatty) {
11176        final String pkgName = pkg.packageName;
11177        if (mCustomResolverComponentName != null &&
11178                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11179            setUpCustomResolverActivity(pkg);
11180        }
11181
11182        if (pkg.packageName.equals("android")) {
11183            synchronized (mPackages) {
11184                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11185                    // Set up information for our fall-back user intent resolution activity.
11186                    mPlatformPackage = pkg;
11187                    pkg.mVersionCode = mSdkVersion;
11188                    pkg.mVersionCodeMajor = 0;
11189                    mAndroidApplication = pkg.applicationInfo;
11190                    if (!mResolverReplaced) {
11191                        mResolveActivity.applicationInfo = mAndroidApplication;
11192                        mResolveActivity.name = ResolverActivity.class.getName();
11193                        mResolveActivity.packageName = mAndroidApplication.packageName;
11194                        mResolveActivity.processName = "system:ui";
11195                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11196                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11197                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11198                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11199                        mResolveActivity.exported = true;
11200                        mResolveActivity.enabled = true;
11201                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11202                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11203                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11204                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11205                                | ActivityInfo.CONFIG_ORIENTATION
11206                                | ActivityInfo.CONFIG_KEYBOARD
11207                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11208                        mResolveInfo.activityInfo = mResolveActivity;
11209                        mResolveInfo.priority = 0;
11210                        mResolveInfo.preferredOrder = 0;
11211                        mResolveInfo.match = 0;
11212                        mResolveComponentName = new ComponentName(
11213                                mAndroidApplication.packageName, mResolveActivity.name);
11214                    }
11215                }
11216            }
11217        }
11218
11219        ArrayList<PackageParser.Package> clientLibPkgs = null;
11220        // writer
11221        synchronized (mPackages) {
11222            boolean hasStaticSharedLibs = false;
11223
11224            // Any app can add new static shared libraries
11225            if (pkg.staticSharedLibName != null) {
11226                // Static shared libs don't allow renaming as they have synthetic package
11227                // names to allow install of multiple versions, so use name from manifest.
11228                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11229                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11230                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11231                    hasStaticSharedLibs = true;
11232                } else {
11233                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11234                                + pkg.staticSharedLibName + " already exists; skipping");
11235                }
11236                // Static shared libs cannot be updated once installed since they
11237                // use synthetic package name which includes the version code, so
11238                // not need to update other packages's shared lib dependencies.
11239            }
11240
11241            if (!hasStaticSharedLibs
11242                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11243                // Only system apps can add new dynamic shared libraries.
11244                if (pkg.libraryNames != null) {
11245                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11246                        String name = pkg.libraryNames.get(i);
11247                        boolean allowed = false;
11248                        if (pkg.isUpdatedSystemApp()) {
11249                            // New library entries can only be added through the
11250                            // system image.  This is important to get rid of a lot
11251                            // of nasty edge cases: for example if we allowed a non-
11252                            // system update of the app to add a library, then uninstalling
11253                            // the update would make the library go away, and assumptions
11254                            // we made such as through app install filtering would now
11255                            // have allowed apps on the device which aren't compatible
11256                            // with it.  Better to just have the restriction here, be
11257                            // conservative, and create many fewer cases that can negatively
11258                            // impact the user experience.
11259                            final PackageSetting sysPs = mSettings
11260                                    .getDisabledSystemPkgLPr(pkg.packageName);
11261                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11262                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11263                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11264                                        allowed = true;
11265                                        break;
11266                                    }
11267                                }
11268                            }
11269                        } else {
11270                            allowed = true;
11271                        }
11272                        if (allowed) {
11273                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11274                                    SharedLibraryInfo.VERSION_UNDEFINED,
11275                                    SharedLibraryInfo.TYPE_DYNAMIC,
11276                                    pkg.packageName, pkg.getLongVersionCode())) {
11277                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11278                                        + name + " already exists; skipping");
11279                            }
11280                        } else {
11281                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11282                                    + name + " that is not declared on system image; skipping");
11283                        }
11284                    }
11285
11286                    if ((scanFlags & SCAN_BOOTING) == 0) {
11287                        // If we are not booting, we need to update any applications
11288                        // that are clients of our shared library.  If we are booting,
11289                        // this will all be done once the scan is complete.
11290                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11291                    }
11292                }
11293            }
11294        }
11295
11296        if ((scanFlags & SCAN_BOOTING) != 0) {
11297            // No apps can run during boot scan, so they don't need to be frozen
11298        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11299            // Caller asked to not kill app, so it's probably not frozen
11300        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11301            // Caller asked us to ignore frozen check for some reason; they
11302            // probably didn't know the package name
11303        } else {
11304            // We're doing major surgery on this package, so it better be frozen
11305            // right now to keep it from launching
11306            checkPackageFrozen(pkgName);
11307        }
11308
11309        // Also need to kill any apps that are dependent on the library.
11310        if (clientLibPkgs != null) {
11311            for (int i=0; i<clientLibPkgs.size(); i++) {
11312                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11313                killApplication(clientPkg.applicationInfo.packageName,
11314                        clientPkg.applicationInfo.uid, "update lib");
11315            }
11316        }
11317
11318        // writer
11319        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11320
11321        synchronized (mPackages) {
11322            // We don't expect installation to fail beyond this point
11323
11324            // Add the new setting to mSettings
11325            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11326            // Add the new setting to mPackages
11327            mPackages.put(pkg.applicationInfo.packageName, pkg);
11328            // Make sure we don't accidentally delete its data.
11329            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11330            while (iter.hasNext()) {
11331                PackageCleanItem item = iter.next();
11332                if (pkgName.equals(item.packageName)) {
11333                    iter.remove();
11334                }
11335            }
11336
11337            // Add the package's KeySets to the global KeySetManagerService
11338            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11339            ksms.addScannedPackageLPw(pkg);
11340
11341            int N = pkg.providers.size();
11342            StringBuilder r = null;
11343            int i;
11344            for (i=0; i<N; i++) {
11345                PackageParser.Provider p = pkg.providers.get(i);
11346                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11347                        p.info.processName);
11348                mProviders.addProvider(p);
11349                p.syncable = p.info.isSyncable;
11350                if (p.info.authority != null) {
11351                    String names[] = p.info.authority.split(";");
11352                    p.info.authority = null;
11353                    for (int j = 0; j < names.length; j++) {
11354                        if (j == 1 && p.syncable) {
11355                            // We only want the first authority for a provider to possibly be
11356                            // syncable, so if we already added this provider using a different
11357                            // authority clear the syncable flag. We copy the provider before
11358                            // changing it because the mProviders object contains a reference
11359                            // to a provider that we don't want to change.
11360                            // Only do this for the second authority since the resulting provider
11361                            // object can be the same for all future authorities for this provider.
11362                            p = new PackageParser.Provider(p);
11363                            p.syncable = false;
11364                        }
11365                        if (!mProvidersByAuthority.containsKey(names[j])) {
11366                            mProvidersByAuthority.put(names[j], p);
11367                            if (p.info.authority == null) {
11368                                p.info.authority = names[j];
11369                            } else {
11370                                p.info.authority = p.info.authority + ";" + names[j];
11371                            }
11372                            if (DEBUG_PACKAGE_SCANNING) {
11373                                if (chatty)
11374                                    Log.d(TAG, "Registered content provider: " + names[j]
11375                                            + ", className = " + p.info.name + ", isSyncable = "
11376                                            + p.info.isSyncable);
11377                            }
11378                        } else {
11379                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11380                            Slog.w(TAG, "Skipping provider name " + names[j] +
11381                                    " (in package " + pkg.applicationInfo.packageName +
11382                                    "): name already used by "
11383                                    + ((other != null && other.getComponentName() != null)
11384                                            ? other.getComponentName().getPackageName() : "?"));
11385                        }
11386                    }
11387                }
11388                if (chatty) {
11389                    if (r == null) {
11390                        r = new StringBuilder(256);
11391                    } else {
11392                        r.append(' ');
11393                    }
11394                    r.append(p.info.name);
11395                }
11396            }
11397            if (r != null) {
11398                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11399            }
11400
11401            N = pkg.services.size();
11402            r = null;
11403            for (i=0; i<N; i++) {
11404                PackageParser.Service s = pkg.services.get(i);
11405                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11406                        s.info.processName);
11407                mServices.addService(s);
11408                if (chatty) {
11409                    if (r == null) {
11410                        r = new StringBuilder(256);
11411                    } else {
11412                        r.append(' ');
11413                    }
11414                    r.append(s.info.name);
11415                }
11416            }
11417            if (r != null) {
11418                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11419            }
11420
11421            N = pkg.receivers.size();
11422            r = null;
11423            for (i=0; i<N; i++) {
11424                PackageParser.Activity a = pkg.receivers.get(i);
11425                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11426                        a.info.processName);
11427                mReceivers.addActivity(a, "receiver");
11428                if (chatty) {
11429                    if (r == null) {
11430                        r = new StringBuilder(256);
11431                    } else {
11432                        r.append(' ');
11433                    }
11434                    r.append(a.info.name);
11435                }
11436            }
11437            if (r != null) {
11438                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11439            }
11440
11441            N = pkg.activities.size();
11442            r = null;
11443            for (i=0; i<N; i++) {
11444                PackageParser.Activity a = pkg.activities.get(i);
11445                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11446                        a.info.processName);
11447                mActivities.addActivity(a, "activity");
11448                if (chatty) {
11449                    if (r == null) {
11450                        r = new StringBuilder(256);
11451                    } else {
11452                        r.append(' ');
11453                    }
11454                    r.append(a.info.name);
11455                }
11456            }
11457            if (r != null) {
11458                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11459            }
11460
11461            // Don't allow ephemeral applications to define new permissions groups.
11462            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11463                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11464                        + " ignored: instant apps cannot define new permission groups.");
11465            } else {
11466                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11467            }
11468
11469            // Don't allow ephemeral applications to define new permissions.
11470            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11471                Slog.w(TAG, "Permissions from package " + pkg.packageName
11472                        + " ignored: instant apps cannot define new permissions.");
11473            } else {
11474                mPermissionManager.addAllPermissions(pkg, chatty);
11475            }
11476
11477            N = pkg.instrumentation.size();
11478            r = null;
11479            for (i=0; i<N; i++) {
11480                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11481                a.info.packageName = pkg.applicationInfo.packageName;
11482                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11483                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11484                a.info.splitNames = pkg.splitNames;
11485                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11486                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11487                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11488                a.info.dataDir = pkg.applicationInfo.dataDir;
11489                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11490                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11491                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11492                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11493                mInstrumentation.put(a.getComponentName(), a);
11494                if (chatty) {
11495                    if (r == null) {
11496                        r = new StringBuilder(256);
11497                    } else {
11498                        r.append(' ');
11499                    }
11500                    r.append(a.info.name);
11501                }
11502            }
11503            if (r != null) {
11504                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11505            }
11506
11507            if (pkg.protectedBroadcasts != null) {
11508                N = pkg.protectedBroadcasts.size();
11509                synchronized (mProtectedBroadcasts) {
11510                    for (i = 0; i < N; i++) {
11511                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11512                    }
11513                }
11514            }
11515
11516            if (oldPkg != null) {
11517                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11518                // revoke callbacks from this method might need to kill apps which need the
11519                // mPackages lock on a different thread. This would dead lock.
11520                //
11521                // Hence create a copy of all package names and pass it into
11522                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11523                // revoked. If a new package is added before the async code runs the permission
11524                // won't be granted yet, hence new packages are no problem.
11525                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11526
11527                AsyncTask.execute(() ->
11528                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11529                                allPackageNames, mPermissionCallback));
11530            }
11531        }
11532
11533        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11534    }
11535
11536    /**
11537     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11538     * is derived purely on the basis of the contents of {@code scanFile} and
11539     * {@code cpuAbiOverride}.
11540     *
11541     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11542     */
11543    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11544            boolean extractLibs)
11545                    throws PackageManagerException {
11546        // Give ourselves some initial paths; we'll come back for another
11547        // pass once we've determined ABI below.
11548        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11549
11550        // We would never need to extract libs for forward-locked and external packages,
11551        // since the container service will do it for us. We shouldn't attempt to
11552        // extract libs from system app when it was not updated.
11553        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11554                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11555            extractLibs = false;
11556        }
11557
11558        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11559        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11560
11561        NativeLibraryHelper.Handle handle = null;
11562        try {
11563            handle = NativeLibraryHelper.Handle.create(pkg);
11564            // TODO(multiArch): This can be null for apps that didn't go through the
11565            // usual installation process. We can calculate it again, like we
11566            // do during install time.
11567            //
11568            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11569            // unnecessary.
11570            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11571
11572            // Null out the abis so that they can be recalculated.
11573            pkg.applicationInfo.primaryCpuAbi = null;
11574            pkg.applicationInfo.secondaryCpuAbi = null;
11575            if (isMultiArch(pkg.applicationInfo)) {
11576                // Warn if we've set an abiOverride for multi-lib packages..
11577                // By definition, we need to copy both 32 and 64 bit libraries for
11578                // such packages.
11579                if (pkg.cpuAbiOverride != null
11580                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11581                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11582                }
11583
11584                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11585                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11586                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11587                    if (extractLibs) {
11588                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11589                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11590                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11591                                useIsaSpecificSubdirs);
11592                    } else {
11593                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11594                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11595                    }
11596                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11597                }
11598
11599                // Shared library native code should be in the APK zip aligned
11600                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11601                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11602                            "Shared library native lib extraction not supported");
11603                }
11604
11605                maybeThrowExceptionForMultiArchCopy(
11606                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11607
11608                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11609                    if (extractLibs) {
11610                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11611                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11612                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11613                                useIsaSpecificSubdirs);
11614                    } else {
11615                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11616                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11617                    }
11618                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11619                }
11620
11621                maybeThrowExceptionForMultiArchCopy(
11622                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11623
11624                if (abi64 >= 0) {
11625                    // Shared library native libs should be in the APK zip aligned
11626                    if (extractLibs && pkg.isLibrary()) {
11627                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11628                                "Shared library native lib extraction not supported");
11629                    }
11630                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11631                }
11632
11633                if (abi32 >= 0) {
11634                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11635                    if (abi64 >= 0) {
11636                        if (pkg.use32bitAbi) {
11637                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11638                            pkg.applicationInfo.primaryCpuAbi = abi;
11639                        } else {
11640                            pkg.applicationInfo.secondaryCpuAbi = abi;
11641                        }
11642                    } else {
11643                        pkg.applicationInfo.primaryCpuAbi = abi;
11644                    }
11645                }
11646            } else {
11647                String[] abiList = (cpuAbiOverride != null) ?
11648                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11649
11650                // Enable gross and lame hacks for apps that are built with old
11651                // SDK tools. We must scan their APKs for renderscript bitcode and
11652                // not launch them if it's present. Don't bother checking on devices
11653                // that don't have 64 bit support.
11654                boolean needsRenderScriptOverride = false;
11655                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11656                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11657                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11658                    needsRenderScriptOverride = true;
11659                }
11660
11661                final int copyRet;
11662                if (extractLibs) {
11663                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11664                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11665                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11666                } else {
11667                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11668                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11669                }
11670                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11671
11672                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11673                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11674                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11675                }
11676
11677                if (copyRet >= 0) {
11678                    // Shared libraries that have native libs must be multi-architecture
11679                    if (pkg.isLibrary()) {
11680                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11681                                "Shared library with native libs must be multiarch");
11682                    }
11683                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11684                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11685                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11686                } else if (needsRenderScriptOverride) {
11687                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11688                }
11689            }
11690        } catch (IOException ioe) {
11691            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11692        } finally {
11693            IoUtils.closeQuietly(handle);
11694        }
11695
11696        // Now that we've calculated the ABIs and determined if it's an internal app,
11697        // we will go ahead and populate the nativeLibraryPath.
11698        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11699    }
11700
11701    /**
11702     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11703     * i.e, so that all packages can be run inside a single process if required.
11704     *
11705     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11706     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11707     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11708     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11709     * updating a package that belongs to a shared user.
11710     *
11711     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11712     * adds unnecessary complexity.
11713     */
11714    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11715            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11716        List<String> changedAbiCodePath = null;
11717        String requiredInstructionSet = null;
11718        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11719            requiredInstructionSet = VMRuntime.getInstructionSet(
11720                     scannedPackage.applicationInfo.primaryCpuAbi);
11721        }
11722
11723        PackageSetting requirer = null;
11724        for (PackageSetting ps : packagesForUser) {
11725            // If packagesForUser contains scannedPackage, we skip it. This will happen
11726            // when scannedPackage is an update of an existing package. Without this check,
11727            // we will never be able to change the ABI of any package belonging to a shared
11728            // user, even if it's compatible with other packages.
11729            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11730                if (ps.primaryCpuAbiString == null) {
11731                    continue;
11732                }
11733
11734                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11735                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11736                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11737                    // this but there's not much we can do.
11738                    String errorMessage = "Instruction set mismatch, "
11739                            + ((requirer == null) ? "[caller]" : requirer)
11740                            + " requires " + requiredInstructionSet + " whereas " + ps
11741                            + " requires " + instructionSet;
11742                    Slog.w(TAG, errorMessage);
11743                }
11744
11745                if (requiredInstructionSet == null) {
11746                    requiredInstructionSet = instructionSet;
11747                    requirer = ps;
11748                }
11749            }
11750        }
11751
11752        if (requiredInstructionSet != null) {
11753            String adjustedAbi;
11754            if (requirer != null) {
11755                // requirer != null implies that either scannedPackage was null or that scannedPackage
11756                // did not require an ABI, in which case we have to adjust scannedPackage to match
11757                // the ABI of the set (which is the same as requirer's ABI)
11758                adjustedAbi = requirer.primaryCpuAbiString;
11759                if (scannedPackage != null) {
11760                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11761                }
11762            } else {
11763                // requirer == null implies that we're updating all ABIs in the set to
11764                // match scannedPackage.
11765                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11766            }
11767
11768            for (PackageSetting ps : packagesForUser) {
11769                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11770                    if (ps.primaryCpuAbiString != null) {
11771                        continue;
11772                    }
11773
11774                    ps.primaryCpuAbiString = adjustedAbi;
11775                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11776                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11777                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11778                        if (DEBUG_ABI_SELECTION) {
11779                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11780                                    + " (requirer="
11781                                    + (requirer != null ? requirer.pkg : "null")
11782                                    + ", scannedPackage="
11783                                    + (scannedPackage != null ? scannedPackage : "null")
11784                                    + ")");
11785                        }
11786                        if (changedAbiCodePath == null) {
11787                            changedAbiCodePath = new ArrayList<>();
11788                        }
11789                        changedAbiCodePath.add(ps.codePathString);
11790                    }
11791                }
11792            }
11793        }
11794        return changedAbiCodePath;
11795    }
11796
11797    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11798        synchronized (mPackages) {
11799            mResolverReplaced = true;
11800            // Set up information for custom user intent resolution activity.
11801            mResolveActivity.applicationInfo = pkg.applicationInfo;
11802            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11803            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11804            mResolveActivity.processName = pkg.applicationInfo.packageName;
11805            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11806            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11807                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11808            mResolveActivity.theme = 0;
11809            mResolveActivity.exported = true;
11810            mResolveActivity.enabled = true;
11811            mResolveInfo.activityInfo = mResolveActivity;
11812            mResolveInfo.priority = 0;
11813            mResolveInfo.preferredOrder = 0;
11814            mResolveInfo.match = 0;
11815            mResolveComponentName = mCustomResolverComponentName;
11816            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11817                    mResolveComponentName);
11818        }
11819    }
11820
11821    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11822        if (installerActivity == null) {
11823            if (DEBUG_INSTANT) {
11824                Slog.d(TAG, "Clear ephemeral installer activity");
11825            }
11826            mInstantAppInstallerActivity = null;
11827            return;
11828        }
11829
11830        if (DEBUG_INSTANT) {
11831            Slog.d(TAG, "Set ephemeral installer activity: "
11832                    + installerActivity.getComponentName());
11833        }
11834        // Set up information for ephemeral installer activity
11835        mInstantAppInstallerActivity = installerActivity;
11836        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11837                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11838        mInstantAppInstallerActivity.exported = true;
11839        mInstantAppInstallerActivity.enabled = true;
11840        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11841        mInstantAppInstallerInfo.priority = 1;
11842        mInstantAppInstallerInfo.preferredOrder = 1;
11843        mInstantAppInstallerInfo.isDefault = true;
11844        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11845                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11846    }
11847
11848    private static String calculateBundledApkRoot(final String codePathString) {
11849        final File codePath = new File(codePathString);
11850        final File codeRoot;
11851        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11852            codeRoot = Environment.getRootDirectory();
11853        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11854            codeRoot = Environment.getOemDirectory();
11855        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11856            codeRoot = Environment.getVendorDirectory();
11857        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11858            codeRoot = Environment.getOdmDirectory();
11859        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11860            codeRoot = Environment.getProductDirectory();
11861        } else {
11862            // Unrecognized code path; take its top real segment as the apk root:
11863            // e.g. /something/app/blah.apk => /something
11864            try {
11865                File f = codePath.getCanonicalFile();
11866                File parent = f.getParentFile();    // non-null because codePath is a file
11867                File tmp;
11868                while ((tmp = parent.getParentFile()) != null) {
11869                    f = parent;
11870                    parent = tmp;
11871                }
11872                codeRoot = f;
11873                Slog.w(TAG, "Unrecognized code path "
11874                        + codePath + " - using " + codeRoot);
11875            } catch (IOException e) {
11876                // Can't canonicalize the code path -- shenanigans?
11877                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11878                return Environment.getRootDirectory().getPath();
11879            }
11880        }
11881        return codeRoot.getPath();
11882    }
11883
11884    /**
11885     * Derive and set the location of native libraries for the given package,
11886     * which varies depending on where and how the package was installed.
11887     */
11888    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11889        final ApplicationInfo info = pkg.applicationInfo;
11890        final String codePath = pkg.codePath;
11891        final File codeFile = new File(codePath);
11892        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11893        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11894
11895        info.nativeLibraryRootDir = null;
11896        info.nativeLibraryRootRequiresIsa = false;
11897        info.nativeLibraryDir = null;
11898        info.secondaryNativeLibraryDir = null;
11899
11900        if (isApkFile(codeFile)) {
11901            // Monolithic install
11902            if (bundledApp) {
11903                // If "/system/lib64/apkname" exists, assume that is the per-package
11904                // native library directory to use; otherwise use "/system/lib/apkname".
11905                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11906                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11907                        getPrimaryInstructionSet(info));
11908
11909                // This is a bundled system app so choose the path based on the ABI.
11910                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11911                // is just the default path.
11912                final String apkName = deriveCodePathName(codePath);
11913                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11914                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11915                        apkName).getAbsolutePath();
11916
11917                if (info.secondaryCpuAbi != null) {
11918                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11919                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11920                            secondaryLibDir, apkName).getAbsolutePath();
11921                }
11922            } else if (asecApp) {
11923                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11924                        .getAbsolutePath();
11925            } else {
11926                final String apkName = deriveCodePathName(codePath);
11927                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11928                        .getAbsolutePath();
11929            }
11930
11931            info.nativeLibraryRootRequiresIsa = false;
11932            info.nativeLibraryDir = info.nativeLibraryRootDir;
11933        } else {
11934            // Cluster install
11935            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11936            info.nativeLibraryRootRequiresIsa = true;
11937
11938            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11939                    getPrimaryInstructionSet(info)).getAbsolutePath();
11940
11941            if (info.secondaryCpuAbi != null) {
11942                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11943                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11944            }
11945        }
11946    }
11947
11948    /**
11949     * Calculate the abis and roots for a bundled app. These can uniquely
11950     * be determined from the contents of the system partition, i.e whether
11951     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11952     * of this information, and instead assume that the system was built
11953     * sensibly.
11954     */
11955    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11956                                           PackageSetting pkgSetting) {
11957        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11958
11959        // If "/system/lib64/apkname" exists, assume that is the per-package
11960        // native library directory to use; otherwise use "/system/lib/apkname".
11961        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11962        setBundledAppAbi(pkg, apkRoot, apkName);
11963        // pkgSetting might be null during rescan following uninstall of updates
11964        // to a bundled app, so accommodate that possibility.  The settings in
11965        // that case will be established later from the parsed package.
11966        //
11967        // If the settings aren't null, sync them up with what we've just derived.
11968        // note that apkRoot isn't stored in the package settings.
11969        if (pkgSetting != null) {
11970            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11971            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11972        }
11973    }
11974
11975    /**
11976     * Deduces the ABI of a bundled app and sets the relevant fields on the
11977     * parsed pkg object.
11978     *
11979     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11980     *        under which system libraries are installed.
11981     * @param apkName the name of the installed package.
11982     */
11983    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11984        final File codeFile = new File(pkg.codePath);
11985
11986        final boolean has64BitLibs;
11987        final boolean has32BitLibs;
11988        if (isApkFile(codeFile)) {
11989            // Monolithic install
11990            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11991            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11992        } else {
11993            // Cluster install
11994            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11995            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11996                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11997                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11998                has64BitLibs = (new File(rootDir, isa)).exists();
11999            } else {
12000                has64BitLibs = false;
12001            }
12002            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12003                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12004                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12005                has32BitLibs = (new File(rootDir, isa)).exists();
12006            } else {
12007                has32BitLibs = false;
12008            }
12009        }
12010
12011        if (has64BitLibs && !has32BitLibs) {
12012            // The package has 64 bit libs, but not 32 bit libs. Its primary
12013            // ABI should be 64 bit. We can safely assume here that the bundled
12014            // native libraries correspond to the most preferred ABI in the list.
12015
12016            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12017            pkg.applicationInfo.secondaryCpuAbi = null;
12018        } else if (has32BitLibs && !has64BitLibs) {
12019            // The package has 32 bit libs but not 64 bit libs. Its primary
12020            // ABI should be 32 bit.
12021
12022            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12023            pkg.applicationInfo.secondaryCpuAbi = null;
12024        } else if (has32BitLibs && has64BitLibs) {
12025            // The application has both 64 and 32 bit bundled libraries. We check
12026            // here that the app declares multiArch support, and warn if it doesn't.
12027            //
12028            // We will be lenient here and record both ABIs. The primary will be the
12029            // ABI that's higher on the list, i.e, a device that's configured to prefer
12030            // 64 bit apps will see a 64 bit primary ABI,
12031
12032            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12033                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12034            }
12035
12036            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12037                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12038                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12039            } else {
12040                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12041                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12042            }
12043        } else {
12044            pkg.applicationInfo.primaryCpuAbi = null;
12045            pkg.applicationInfo.secondaryCpuAbi = null;
12046        }
12047    }
12048
12049    private void killApplication(String pkgName, int appId, String reason) {
12050        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12051    }
12052
12053    private void killApplication(String pkgName, int appId, int userId, String reason) {
12054        // Request the ActivityManager to kill the process(only for existing packages)
12055        // so that we do not end up in a confused state while the user is still using the older
12056        // version of the application while the new one gets installed.
12057        final long token = Binder.clearCallingIdentity();
12058        try {
12059            IActivityManager am = ActivityManager.getService();
12060            if (am != null) {
12061                try {
12062                    am.killApplication(pkgName, appId, userId, reason);
12063                } catch (RemoteException e) {
12064                }
12065            }
12066        } finally {
12067            Binder.restoreCallingIdentity(token);
12068        }
12069    }
12070
12071    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12072        // Remove the parent package setting
12073        PackageSetting ps = (PackageSetting) pkg.mExtras;
12074        if (ps != null) {
12075            removePackageLI(ps, chatty);
12076        }
12077        // Remove the child package setting
12078        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12079        for (int i = 0; i < childCount; i++) {
12080            PackageParser.Package childPkg = pkg.childPackages.get(i);
12081            ps = (PackageSetting) childPkg.mExtras;
12082            if (ps != null) {
12083                removePackageLI(ps, chatty);
12084            }
12085        }
12086    }
12087
12088    void removePackageLI(PackageSetting ps, boolean chatty) {
12089        if (DEBUG_INSTALL) {
12090            if (chatty)
12091                Log.d(TAG, "Removing package " + ps.name);
12092        }
12093
12094        // writer
12095        synchronized (mPackages) {
12096            mPackages.remove(ps.name);
12097            final PackageParser.Package pkg = ps.pkg;
12098            if (pkg != null) {
12099                cleanPackageDataStructuresLILPw(pkg, chatty);
12100            }
12101        }
12102    }
12103
12104    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12105        if (DEBUG_INSTALL) {
12106            if (chatty)
12107                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12108        }
12109
12110        // writer
12111        synchronized (mPackages) {
12112            // Remove the parent package
12113            mPackages.remove(pkg.applicationInfo.packageName);
12114            cleanPackageDataStructuresLILPw(pkg, chatty);
12115
12116            // Remove the child packages
12117            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12118            for (int i = 0; i < childCount; i++) {
12119                PackageParser.Package childPkg = pkg.childPackages.get(i);
12120                mPackages.remove(childPkg.applicationInfo.packageName);
12121                cleanPackageDataStructuresLILPw(childPkg, chatty);
12122            }
12123        }
12124    }
12125
12126    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12127        int N = pkg.providers.size();
12128        StringBuilder r = null;
12129        int i;
12130        for (i=0; i<N; i++) {
12131            PackageParser.Provider p = pkg.providers.get(i);
12132            mProviders.removeProvider(p);
12133            if (p.info.authority == null) {
12134
12135                /* There was another ContentProvider with this authority when
12136                 * this app was installed so this authority is null,
12137                 * Ignore it as we don't have to unregister the provider.
12138                 */
12139                continue;
12140            }
12141            String names[] = p.info.authority.split(";");
12142            for (int j = 0; j < names.length; j++) {
12143                if (mProvidersByAuthority.get(names[j]) == p) {
12144                    mProvidersByAuthority.remove(names[j]);
12145                    if (DEBUG_REMOVE) {
12146                        if (chatty)
12147                            Log.d(TAG, "Unregistered content provider: " + names[j]
12148                                    + ", className = " + p.info.name + ", isSyncable = "
12149                                    + p.info.isSyncable);
12150                    }
12151                }
12152            }
12153            if (DEBUG_REMOVE && chatty) {
12154                if (r == null) {
12155                    r = new StringBuilder(256);
12156                } else {
12157                    r.append(' ');
12158                }
12159                r.append(p.info.name);
12160            }
12161        }
12162        if (r != null) {
12163            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12164        }
12165
12166        N = pkg.services.size();
12167        r = null;
12168        for (i=0; i<N; i++) {
12169            PackageParser.Service s = pkg.services.get(i);
12170            mServices.removeService(s);
12171            if (chatty) {
12172                if (r == null) {
12173                    r = new StringBuilder(256);
12174                } else {
12175                    r.append(' ');
12176                }
12177                r.append(s.info.name);
12178            }
12179        }
12180        if (r != null) {
12181            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12182        }
12183
12184        N = pkg.receivers.size();
12185        r = null;
12186        for (i=0; i<N; i++) {
12187            PackageParser.Activity a = pkg.receivers.get(i);
12188            mReceivers.removeActivity(a, "receiver");
12189            if (DEBUG_REMOVE && chatty) {
12190                if (r == null) {
12191                    r = new StringBuilder(256);
12192                } else {
12193                    r.append(' ');
12194                }
12195                r.append(a.info.name);
12196            }
12197        }
12198        if (r != null) {
12199            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12200        }
12201
12202        N = pkg.activities.size();
12203        r = null;
12204        for (i=0; i<N; i++) {
12205            PackageParser.Activity a = pkg.activities.get(i);
12206            mActivities.removeActivity(a, "activity");
12207            if (DEBUG_REMOVE && chatty) {
12208                if (r == null) {
12209                    r = new StringBuilder(256);
12210                } else {
12211                    r.append(' ');
12212                }
12213                r.append(a.info.name);
12214            }
12215        }
12216        if (r != null) {
12217            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12218        }
12219
12220        mPermissionManager.removeAllPermissions(pkg, chatty);
12221
12222        N = pkg.instrumentation.size();
12223        r = null;
12224        for (i=0; i<N; i++) {
12225            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12226            mInstrumentation.remove(a.getComponentName());
12227            if (DEBUG_REMOVE && chatty) {
12228                if (r == null) {
12229                    r = new StringBuilder(256);
12230                } else {
12231                    r.append(' ');
12232                }
12233                r.append(a.info.name);
12234            }
12235        }
12236        if (r != null) {
12237            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12238        }
12239
12240        r = null;
12241        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12242            // Only system apps can hold shared libraries.
12243            if (pkg.libraryNames != null) {
12244                for (i = 0; i < pkg.libraryNames.size(); i++) {
12245                    String name = pkg.libraryNames.get(i);
12246                    if (removeSharedLibraryLPw(name, 0)) {
12247                        if (DEBUG_REMOVE && chatty) {
12248                            if (r == null) {
12249                                r = new StringBuilder(256);
12250                            } else {
12251                                r.append(' ');
12252                            }
12253                            r.append(name);
12254                        }
12255                    }
12256                }
12257            }
12258        }
12259
12260        r = null;
12261
12262        // Any package can hold static shared libraries.
12263        if (pkg.staticSharedLibName != null) {
12264            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12265                if (DEBUG_REMOVE && chatty) {
12266                    if (r == null) {
12267                        r = new StringBuilder(256);
12268                    } else {
12269                        r.append(' ');
12270                    }
12271                    r.append(pkg.staticSharedLibName);
12272                }
12273            }
12274        }
12275
12276        if (r != null) {
12277            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12278        }
12279    }
12280
12281
12282    final class ActivityIntentResolver
12283            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12284        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12285                boolean defaultOnly, int userId) {
12286            if (!sUserManager.exists(userId)) return null;
12287            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12288            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12289        }
12290
12291        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12292                int userId) {
12293            if (!sUserManager.exists(userId)) return null;
12294            mFlags = flags;
12295            return super.queryIntent(intent, resolvedType,
12296                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12297                    userId);
12298        }
12299
12300        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12301                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12302            if (!sUserManager.exists(userId)) return null;
12303            if (packageActivities == null) {
12304                return null;
12305            }
12306            mFlags = flags;
12307            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12308            final int N = packageActivities.size();
12309            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12310                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12311
12312            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12313            for (int i = 0; i < N; ++i) {
12314                intentFilters = packageActivities.get(i).intents;
12315                if (intentFilters != null && intentFilters.size() > 0) {
12316                    PackageParser.ActivityIntentInfo[] array =
12317                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12318                    intentFilters.toArray(array);
12319                    listCut.add(array);
12320                }
12321            }
12322            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12323        }
12324
12325        /**
12326         * Finds a privileged activity that matches the specified activity names.
12327         */
12328        private PackageParser.Activity findMatchingActivity(
12329                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12330            for (PackageParser.Activity sysActivity : activityList) {
12331                if (sysActivity.info.name.equals(activityInfo.name)) {
12332                    return sysActivity;
12333                }
12334                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12335                    return sysActivity;
12336                }
12337                if (sysActivity.info.targetActivity != null) {
12338                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12339                        return sysActivity;
12340                    }
12341                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12342                        return sysActivity;
12343                    }
12344                }
12345            }
12346            return null;
12347        }
12348
12349        public class IterGenerator<E> {
12350            public Iterator<E> generate(ActivityIntentInfo info) {
12351                return null;
12352            }
12353        }
12354
12355        public class ActionIterGenerator extends IterGenerator<String> {
12356            @Override
12357            public Iterator<String> generate(ActivityIntentInfo info) {
12358                return info.actionsIterator();
12359            }
12360        }
12361
12362        public class CategoriesIterGenerator extends IterGenerator<String> {
12363            @Override
12364            public Iterator<String> generate(ActivityIntentInfo info) {
12365                return info.categoriesIterator();
12366            }
12367        }
12368
12369        public class SchemesIterGenerator extends IterGenerator<String> {
12370            @Override
12371            public Iterator<String> generate(ActivityIntentInfo info) {
12372                return info.schemesIterator();
12373            }
12374        }
12375
12376        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12377            @Override
12378            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12379                return info.authoritiesIterator();
12380            }
12381        }
12382
12383        /**
12384         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12385         * MODIFIED. Do not pass in a list that should not be changed.
12386         */
12387        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12388                IterGenerator<T> generator, Iterator<T> searchIterator) {
12389            // loop through the set of actions; every one must be found in the intent filter
12390            while (searchIterator.hasNext()) {
12391                // we must have at least one filter in the list to consider a match
12392                if (intentList.size() == 0) {
12393                    break;
12394                }
12395
12396                final T searchAction = searchIterator.next();
12397
12398                // loop through the set of intent filters
12399                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12400                while (intentIter.hasNext()) {
12401                    final ActivityIntentInfo intentInfo = intentIter.next();
12402                    boolean selectionFound = false;
12403
12404                    // loop through the intent filter's selection criteria; at least one
12405                    // of them must match the searched criteria
12406                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12407                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12408                        final T intentSelection = intentSelectionIter.next();
12409                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12410                            selectionFound = true;
12411                            break;
12412                        }
12413                    }
12414
12415                    // the selection criteria wasn't found in this filter's set; this filter
12416                    // is not a potential match
12417                    if (!selectionFound) {
12418                        intentIter.remove();
12419                    }
12420                }
12421            }
12422        }
12423
12424        private boolean isProtectedAction(ActivityIntentInfo filter) {
12425            final Iterator<String> actionsIter = filter.actionsIterator();
12426            while (actionsIter != null && actionsIter.hasNext()) {
12427                final String filterAction = actionsIter.next();
12428                if (PROTECTED_ACTIONS.contains(filterAction)) {
12429                    return true;
12430                }
12431            }
12432            return false;
12433        }
12434
12435        /**
12436         * Adjusts the priority of the given intent filter according to policy.
12437         * <p>
12438         * <ul>
12439         * <li>The priority for non privileged applications is capped to '0'</li>
12440         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12441         * <li>The priority for unbundled updates to privileged applications is capped to the
12442         *      priority defined on the system partition</li>
12443         * </ul>
12444         * <p>
12445         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12446         * allowed to obtain any priority on any action.
12447         */
12448        private void adjustPriority(
12449                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12450            // nothing to do; priority is fine as-is
12451            if (intent.getPriority() <= 0) {
12452                return;
12453            }
12454
12455            final ActivityInfo activityInfo = intent.activity.info;
12456            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12457
12458            final boolean privilegedApp =
12459                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12460            if (!privilegedApp) {
12461                // non-privileged applications can never define a priority >0
12462                if (DEBUG_FILTERS) {
12463                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12464                            + " package: " + applicationInfo.packageName
12465                            + " activity: " + intent.activity.className
12466                            + " origPrio: " + intent.getPriority());
12467                }
12468                intent.setPriority(0);
12469                return;
12470            }
12471
12472            if (systemActivities == null) {
12473                // the system package is not disabled; we're parsing the system partition
12474                if (isProtectedAction(intent)) {
12475                    if (mDeferProtectedFilters) {
12476                        // We can't deal with these just yet. No component should ever obtain a
12477                        // >0 priority for a protected actions, with ONE exception -- the setup
12478                        // wizard. The setup wizard, however, cannot be known until we're able to
12479                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12480                        // until all intent filters have been processed. Chicken, meet egg.
12481                        // Let the filter temporarily have a high priority and rectify the
12482                        // priorities after all system packages have been scanned.
12483                        mProtectedFilters.add(intent);
12484                        if (DEBUG_FILTERS) {
12485                            Slog.i(TAG, "Protected action; save for later;"
12486                                    + " package: " + applicationInfo.packageName
12487                                    + " activity: " + intent.activity.className
12488                                    + " origPrio: " + intent.getPriority());
12489                        }
12490                        return;
12491                    } else {
12492                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12493                            Slog.i(TAG, "No setup wizard;"
12494                                + " All protected intents capped to priority 0");
12495                        }
12496                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12497                            if (DEBUG_FILTERS) {
12498                                Slog.i(TAG, "Found setup wizard;"
12499                                    + " allow priority " + intent.getPriority() + ";"
12500                                    + " package: " + intent.activity.info.packageName
12501                                    + " activity: " + intent.activity.className
12502                                    + " priority: " + intent.getPriority());
12503                            }
12504                            // setup wizard gets whatever it wants
12505                            return;
12506                        }
12507                        if (DEBUG_FILTERS) {
12508                            Slog.i(TAG, "Protected action; cap priority to 0;"
12509                                    + " package: " + intent.activity.info.packageName
12510                                    + " activity: " + intent.activity.className
12511                                    + " origPrio: " + intent.getPriority());
12512                        }
12513                        intent.setPriority(0);
12514                        return;
12515                    }
12516                }
12517                // privileged apps on the system image get whatever priority they request
12518                return;
12519            }
12520
12521            // privileged app unbundled update ... try to find the same activity
12522            final PackageParser.Activity foundActivity =
12523                    findMatchingActivity(systemActivities, activityInfo);
12524            if (foundActivity == null) {
12525                // this is a new activity; it cannot obtain >0 priority
12526                if (DEBUG_FILTERS) {
12527                    Slog.i(TAG, "New activity; cap priority to 0;"
12528                            + " package: " + applicationInfo.packageName
12529                            + " activity: " + intent.activity.className
12530                            + " origPrio: " + intent.getPriority());
12531                }
12532                intent.setPriority(0);
12533                return;
12534            }
12535
12536            // found activity, now check for filter equivalence
12537
12538            // a shallow copy is enough; we modify the list, not its contents
12539            final List<ActivityIntentInfo> intentListCopy =
12540                    new ArrayList<>(foundActivity.intents);
12541            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12542
12543            // find matching action subsets
12544            final Iterator<String> actionsIterator = intent.actionsIterator();
12545            if (actionsIterator != null) {
12546                getIntentListSubset(
12547                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12548                if (intentListCopy.size() == 0) {
12549                    // no more intents to match; we're not equivalent
12550                    if (DEBUG_FILTERS) {
12551                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12552                                + " package: " + applicationInfo.packageName
12553                                + " activity: " + intent.activity.className
12554                                + " origPrio: " + intent.getPriority());
12555                    }
12556                    intent.setPriority(0);
12557                    return;
12558                }
12559            }
12560
12561            // find matching category subsets
12562            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12563            if (categoriesIterator != null) {
12564                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12565                        categoriesIterator);
12566                if (intentListCopy.size() == 0) {
12567                    // no more intents to match; we're not equivalent
12568                    if (DEBUG_FILTERS) {
12569                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12570                                + " package: " + applicationInfo.packageName
12571                                + " activity: " + intent.activity.className
12572                                + " origPrio: " + intent.getPriority());
12573                    }
12574                    intent.setPriority(0);
12575                    return;
12576                }
12577            }
12578
12579            // find matching schemes subsets
12580            final Iterator<String> schemesIterator = intent.schemesIterator();
12581            if (schemesIterator != null) {
12582                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12583                        schemesIterator);
12584                if (intentListCopy.size() == 0) {
12585                    // no more intents to match; we're not equivalent
12586                    if (DEBUG_FILTERS) {
12587                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12588                                + " package: " + applicationInfo.packageName
12589                                + " activity: " + intent.activity.className
12590                                + " origPrio: " + intent.getPriority());
12591                    }
12592                    intent.setPriority(0);
12593                    return;
12594                }
12595            }
12596
12597            // find matching authorities subsets
12598            final Iterator<IntentFilter.AuthorityEntry>
12599                    authoritiesIterator = intent.authoritiesIterator();
12600            if (authoritiesIterator != null) {
12601                getIntentListSubset(intentListCopy,
12602                        new AuthoritiesIterGenerator(),
12603                        authoritiesIterator);
12604                if (intentListCopy.size() == 0) {
12605                    // no more intents to match; we're not equivalent
12606                    if (DEBUG_FILTERS) {
12607                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12608                                + " package: " + applicationInfo.packageName
12609                                + " activity: " + intent.activity.className
12610                                + " origPrio: " + intent.getPriority());
12611                    }
12612                    intent.setPriority(0);
12613                    return;
12614                }
12615            }
12616
12617            // we found matching filter(s); app gets the max priority of all intents
12618            int cappedPriority = 0;
12619            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12620                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12621            }
12622            if (intent.getPriority() > cappedPriority) {
12623                if (DEBUG_FILTERS) {
12624                    Slog.i(TAG, "Found matching filter(s);"
12625                            + " cap priority to " + cappedPriority + ";"
12626                            + " package: " + applicationInfo.packageName
12627                            + " activity: " + intent.activity.className
12628                            + " origPrio: " + intent.getPriority());
12629                }
12630                intent.setPriority(cappedPriority);
12631                return;
12632            }
12633            // all this for nothing; the requested priority was <= what was on the system
12634        }
12635
12636        public final void addActivity(PackageParser.Activity a, String type) {
12637            mActivities.put(a.getComponentName(), a);
12638            if (DEBUG_SHOW_INFO)
12639                Log.v(
12640                TAG, "  " + type + " " +
12641                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12642            if (DEBUG_SHOW_INFO)
12643                Log.v(TAG, "    Class=" + a.info.name);
12644            final int NI = a.intents.size();
12645            for (int j=0; j<NI; j++) {
12646                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12647                if ("activity".equals(type)) {
12648                    final PackageSetting ps =
12649                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12650                    final List<PackageParser.Activity> systemActivities =
12651                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12652                    adjustPriority(systemActivities, intent);
12653                }
12654                if (DEBUG_SHOW_INFO) {
12655                    Log.v(TAG, "    IntentFilter:");
12656                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12657                }
12658                if (!intent.debugCheck()) {
12659                    Log.w(TAG, "==> For Activity " + a.info.name);
12660                }
12661                addFilter(intent);
12662            }
12663        }
12664
12665        public final void removeActivity(PackageParser.Activity a, String type) {
12666            mActivities.remove(a.getComponentName());
12667            if (DEBUG_SHOW_INFO) {
12668                Log.v(TAG, "  " + type + " "
12669                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12670                                : a.info.name) + ":");
12671                Log.v(TAG, "    Class=" + a.info.name);
12672            }
12673            final int NI = a.intents.size();
12674            for (int j=0; j<NI; j++) {
12675                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12676                if (DEBUG_SHOW_INFO) {
12677                    Log.v(TAG, "    IntentFilter:");
12678                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12679                }
12680                removeFilter(intent);
12681            }
12682        }
12683
12684        @Override
12685        protected boolean allowFilterResult(
12686                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12687            ActivityInfo filterAi = filter.activity.info;
12688            for (int i=dest.size()-1; i>=0; i--) {
12689                ActivityInfo destAi = dest.get(i).activityInfo;
12690                if (destAi.name == filterAi.name
12691                        && destAi.packageName == filterAi.packageName) {
12692                    return false;
12693                }
12694            }
12695            return true;
12696        }
12697
12698        @Override
12699        protected ActivityIntentInfo[] newArray(int size) {
12700            return new ActivityIntentInfo[size];
12701        }
12702
12703        @Override
12704        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12705            if (!sUserManager.exists(userId)) return true;
12706            PackageParser.Package p = filter.activity.owner;
12707            if (p != null) {
12708                PackageSetting ps = (PackageSetting)p.mExtras;
12709                if (ps != null) {
12710                    // System apps are never considered stopped for purposes of
12711                    // filtering, because there may be no way for the user to
12712                    // actually re-launch them.
12713                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12714                            && ps.getStopped(userId);
12715                }
12716            }
12717            return false;
12718        }
12719
12720        @Override
12721        protected boolean isPackageForFilter(String packageName,
12722                PackageParser.ActivityIntentInfo info) {
12723            return packageName.equals(info.activity.owner.packageName);
12724        }
12725
12726        @Override
12727        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12728                int match, int userId) {
12729            if (!sUserManager.exists(userId)) return null;
12730            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12731                return null;
12732            }
12733            final PackageParser.Activity activity = info.activity;
12734            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12735            if (ps == null) {
12736                return null;
12737            }
12738            final PackageUserState userState = ps.readUserState(userId);
12739            ActivityInfo ai =
12740                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12741            if (ai == null) {
12742                return null;
12743            }
12744            final boolean matchExplicitlyVisibleOnly =
12745                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12746            final boolean matchVisibleToInstantApp =
12747                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12748            final boolean componentVisible =
12749                    matchVisibleToInstantApp
12750                    && info.isVisibleToInstantApp()
12751                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12752            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12753            // throw out filters that aren't visible to ephemeral apps
12754            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12755                return null;
12756            }
12757            // throw out instant app filters if we're not explicitly requesting them
12758            if (!matchInstantApp && userState.instantApp) {
12759                return null;
12760            }
12761            // throw out instant app filters if updates are available; will trigger
12762            // instant app resolution
12763            if (userState.instantApp && ps.isUpdateAvailable()) {
12764                return null;
12765            }
12766            final ResolveInfo res = new ResolveInfo();
12767            res.activityInfo = ai;
12768            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12769                res.filter = info;
12770            }
12771            if (info != null) {
12772                res.handleAllWebDataURI = info.handleAllWebDataURI();
12773            }
12774            res.priority = info.getPriority();
12775            res.preferredOrder = activity.owner.mPreferredOrder;
12776            //System.out.println("Result: " + res.activityInfo.className +
12777            //                   " = " + res.priority);
12778            res.match = match;
12779            res.isDefault = info.hasDefault;
12780            res.labelRes = info.labelRes;
12781            res.nonLocalizedLabel = info.nonLocalizedLabel;
12782            if (userNeedsBadging(userId)) {
12783                res.noResourceId = true;
12784            } else {
12785                res.icon = info.icon;
12786            }
12787            res.iconResourceId = info.icon;
12788            res.system = res.activityInfo.applicationInfo.isSystemApp();
12789            res.isInstantAppAvailable = userState.instantApp;
12790            return res;
12791        }
12792
12793        @Override
12794        protected void sortResults(List<ResolveInfo> results) {
12795            Collections.sort(results, mResolvePrioritySorter);
12796        }
12797
12798        @Override
12799        protected void dumpFilter(PrintWriter out, String prefix,
12800                PackageParser.ActivityIntentInfo filter) {
12801            out.print(prefix); out.print(
12802                    Integer.toHexString(System.identityHashCode(filter.activity)));
12803                    out.print(' ');
12804                    filter.activity.printComponentShortName(out);
12805                    out.print(" filter ");
12806                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12807        }
12808
12809        @Override
12810        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12811            return filter.activity;
12812        }
12813
12814        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12815            PackageParser.Activity activity = (PackageParser.Activity)label;
12816            out.print(prefix); out.print(
12817                    Integer.toHexString(System.identityHashCode(activity)));
12818                    out.print(' ');
12819                    activity.printComponentShortName(out);
12820            if (count > 1) {
12821                out.print(" ("); out.print(count); out.print(" filters)");
12822            }
12823            out.println();
12824        }
12825
12826        // Keys are String (activity class name), values are Activity.
12827        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12828                = new ArrayMap<ComponentName, PackageParser.Activity>();
12829        private int mFlags;
12830    }
12831
12832    private final class ServiceIntentResolver
12833            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12834        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12835                boolean defaultOnly, int userId) {
12836            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12837            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12838        }
12839
12840        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12841                int userId) {
12842            if (!sUserManager.exists(userId)) return null;
12843            mFlags = flags;
12844            return super.queryIntent(intent, resolvedType,
12845                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12846                    userId);
12847        }
12848
12849        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12850                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12851            if (!sUserManager.exists(userId)) return null;
12852            if (packageServices == null) {
12853                return null;
12854            }
12855            mFlags = flags;
12856            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12857            final int N = packageServices.size();
12858            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12859                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12860
12861            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12862            for (int i = 0; i < N; ++i) {
12863                intentFilters = packageServices.get(i).intents;
12864                if (intentFilters != null && intentFilters.size() > 0) {
12865                    PackageParser.ServiceIntentInfo[] array =
12866                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12867                    intentFilters.toArray(array);
12868                    listCut.add(array);
12869                }
12870            }
12871            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12872        }
12873
12874        public final void addService(PackageParser.Service s) {
12875            mServices.put(s.getComponentName(), s);
12876            if (DEBUG_SHOW_INFO) {
12877                Log.v(TAG, "  "
12878                        + (s.info.nonLocalizedLabel != null
12879                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12880                Log.v(TAG, "    Class=" + s.info.name);
12881            }
12882            final int NI = s.intents.size();
12883            int j;
12884            for (j=0; j<NI; j++) {
12885                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12886                if (DEBUG_SHOW_INFO) {
12887                    Log.v(TAG, "    IntentFilter:");
12888                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12889                }
12890                if (!intent.debugCheck()) {
12891                    Log.w(TAG, "==> For Service " + s.info.name);
12892                }
12893                addFilter(intent);
12894            }
12895        }
12896
12897        public final void removeService(PackageParser.Service s) {
12898            mServices.remove(s.getComponentName());
12899            if (DEBUG_SHOW_INFO) {
12900                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12901                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12902                Log.v(TAG, "    Class=" + s.info.name);
12903            }
12904            final int NI = s.intents.size();
12905            int j;
12906            for (j=0; j<NI; j++) {
12907                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12908                if (DEBUG_SHOW_INFO) {
12909                    Log.v(TAG, "    IntentFilter:");
12910                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12911                }
12912                removeFilter(intent);
12913            }
12914        }
12915
12916        @Override
12917        protected boolean allowFilterResult(
12918                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12919            ServiceInfo filterSi = filter.service.info;
12920            for (int i=dest.size()-1; i>=0; i--) {
12921                ServiceInfo destAi = dest.get(i).serviceInfo;
12922                if (destAi.name == filterSi.name
12923                        && destAi.packageName == filterSi.packageName) {
12924                    return false;
12925                }
12926            }
12927            return true;
12928        }
12929
12930        @Override
12931        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12932            return new PackageParser.ServiceIntentInfo[size];
12933        }
12934
12935        @Override
12936        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12937            if (!sUserManager.exists(userId)) return true;
12938            PackageParser.Package p = filter.service.owner;
12939            if (p != null) {
12940                PackageSetting ps = (PackageSetting)p.mExtras;
12941                if (ps != null) {
12942                    // System apps are never considered stopped for purposes of
12943                    // filtering, because there may be no way for the user to
12944                    // actually re-launch them.
12945                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12946                            && ps.getStopped(userId);
12947                }
12948            }
12949            return false;
12950        }
12951
12952        @Override
12953        protected boolean isPackageForFilter(String packageName,
12954                PackageParser.ServiceIntentInfo info) {
12955            return packageName.equals(info.service.owner.packageName);
12956        }
12957
12958        @Override
12959        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12960                int match, int userId) {
12961            if (!sUserManager.exists(userId)) return null;
12962            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12963            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12964                return null;
12965            }
12966            final PackageParser.Service service = info.service;
12967            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12968            if (ps == null) {
12969                return null;
12970            }
12971            final PackageUserState userState = ps.readUserState(userId);
12972            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12973                    userState, userId);
12974            if (si == null) {
12975                return null;
12976            }
12977            final boolean matchVisibleToInstantApp =
12978                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12979            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12980            // throw out filters that aren't visible to ephemeral apps
12981            if (matchVisibleToInstantApp
12982                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12983                return null;
12984            }
12985            // throw out ephemeral filters if we're not explicitly requesting them
12986            if (!isInstantApp && userState.instantApp) {
12987                return null;
12988            }
12989            // throw out instant app filters if updates are available; will trigger
12990            // instant app resolution
12991            if (userState.instantApp && ps.isUpdateAvailable()) {
12992                return null;
12993            }
12994            final ResolveInfo res = new ResolveInfo();
12995            res.serviceInfo = si;
12996            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12997                res.filter = filter;
12998            }
12999            res.priority = info.getPriority();
13000            res.preferredOrder = service.owner.mPreferredOrder;
13001            res.match = match;
13002            res.isDefault = info.hasDefault;
13003            res.labelRes = info.labelRes;
13004            res.nonLocalizedLabel = info.nonLocalizedLabel;
13005            res.icon = info.icon;
13006            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13007            return res;
13008        }
13009
13010        @Override
13011        protected void sortResults(List<ResolveInfo> results) {
13012            Collections.sort(results, mResolvePrioritySorter);
13013        }
13014
13015        @Override
13016        protected void dumpFilter(PrintWriter out, String prefix,
13017                PackageParser.ServiceIntentInfo filter) {
13018            out.print(prefix); out.print(
13019                    Integer.toHexString(System.identityHashCode(filter.service)));
13020                    out.print(' ');
13021                    filter.service.printComponentShortName(out);
13022                    out.print(" filter ");
13023                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13024                    if (filter.service.info.permission != null) {
13025                        out.print(" permission "); out.println(filter.service.info.permission);
13026                    } else {
13027                        out.println();
13028                    }
13029        }
13030
13031        @Override
13032        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13033            return filter.service;
13034        }
13035
13036        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13037            PackageParser.Service service = (PackageParser.Service)label;
13038            out.print(prefix); out.print(
13039                    Integer.toHexString(System.identityHashCode(service)));
13040                    out.print(' ');
13041                    service.printComponentShortName(out);
13042            if (count > 1) {
13043                out.print(" ("); out.print(count); out.print(" filters)");
13044            }
13045            out.println();
13046        }
13047
13048//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13049//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13050//            final List<ResolveInfo> retList = Lists.newArrayList();
13051//            while (i.hasNext()) {
13052//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13053//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13054//                    retList.add(resolveInfo);
13055//                }
13056//            }
13057//            return retList;
13058//        }
13059
13060        // Keys are String (activity class name), values are Activity.
13061        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13062                = new ArrayMap<ComponentName, PackageParser.Service>();
13063        private int mFlags;
13064    }
13065
13066    private final class ProviderIntentResolver
13067            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13068        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13069                boolean defaultOnly, int userId) {
13070            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13071            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13072        }
13073
13074        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13075                int userId) {
13076            if (!sUserManager.exists(userId))
13077                return null;
13078            mFlags = flags;
13079            return super.queryIntent(intent, resolvedType,
13080                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13081                    userId);
13082        }
13083
13084        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13085                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13086            if (!sUserManager.exists(userId))
13087                return null;
13088            if (packageProviders == null) {
13089                return null;
13090            }
13091            mFlags = flags;
13092            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13093            final int N = packageProviders.size();
13094            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13095                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13096
13097            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13098            for (int i = 0; i < N; ++i) {
13099                intentFilters = packageProviders.get(i).intents;
13100                if (intentFilters != null && intentFilters.size() > 0) {
13101                    PackageParser.ProviderIntentInfo[] array =
13102                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13103                    intentFilters.toArray(array);
13104                    listCut.add(array);
13105                }
13106            }
13107            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13108        }
13109
13110        public final void addProvider(PackageParser.Provider p) {
13111            if (mProviders.containsKey(p.getComponentName())) {
13112                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13113                return;
13114            }
13115
13116            mProviders.put(p.getComponentName(), p);
13117            if (DEBUG_SHOW_INFO) {
13118                Log.v(TAG, "  "
13119                        + (p.info.nonLocalizedLabel != null
13120                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13121                Log.v(TAG, "    Class=" + p.info.name);
13122            }
13123            final int NI = p.intents.size();
13124            int j;
13125            for (j = 0; j < NI; j++) {
13126                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13127                if (DEBUG_SHOW_INFO) {
13128                    Log.v(TAG, "    IntentFilter:");
13129                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13130                }
13131                if (!intent.debugCheck()) {
13132                    Log.w(TAG, "==> For Provider " + p.info.name);
13133                }
13134                addFilter(intent);
13135            }
13136        }
13137
13138        public final void removeProvider(PackageParser.Provider p) {
13139            mProviders.remove(p.getComponentName());
13140            if (DEBUG_SHOW_INFO) {
13141                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13142                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13143                Log.v(TAG, "    Class=" + p.info.name);
13144            }
13145            final int NI = p.intents.size();
13146            int j;
13147            for (j = 0; j < NI; j++) {
13148                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13149                if (DEBUG_SHOW_INFO) {
13150                    Log.v(TAG, "    IntentFilter:");
13151                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13152                }
13153                removeFilter(intent);
13154            }
13155        }
13156
13157        @Override
13158        protected boolean allowFilterResult(
13159                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13160            ProviderInfo filterPi = filter.provider.info;
13161            for (int i = dest.size() - 1; i >= 0; i--) {
13162                ProviderInfo destPi = dest.get(i).providerInfo;
13163                if (destPi.name == filterPi.name
13164                        && destPi.packageName == filterPi.packageName) {
13165                    return false;
13166                }
13167            }
13168            return true;
13169        }
13170
13171        @Override
13172        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13173            return new PackageParser.ProviderIntentInfo[size];
13174        }
13175
13176        @Override
13177        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13178            if (!sUserManager.exists(userId))
13179                return true;
13180            PackageParser.Package p = filter.provider.owner;
13181            if (p != null) {
13182                PackageSetting ps = (PackageSetting) p.mExtras;
13183                if (ps != null) {
13184                    // System apps are never considered stopped for purposes of
13185                    // filtering, because there may be no way for the user to
13186                    // actually re-launch them.
13187                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13188                            && ps.getStopped(userId);
13189                }
13190            }
13191            return false;
13192        }
13193
13194        @Override
13195        protected boolean isPackageForFilter(String packageName,
13196                PackageParser.ProviderIntentInfo info) {
13197            return packageName.equals(info.provider.owner.packageName);
13198        }
13199
13200        @Override
13201        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13202                int match, int userId) {
13203            if (!sUserManager.exists(userId))
13204                return null;
13205            final PackageParser.ProviderIntentInfo info = filter;
13206            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13207                return null;
13208            }
13209            final PackageParser.Provider provider = info.provider;
13210            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13211            if (ps == null) {
13212                return null;
13213            }
13214            final PackageUserState userState = ps.readUserState(userId);
13215            final boolean matchVisibleToInstantApp =
13216                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13217            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13218            // throw out filters that aren't visible to instant applications
13219            if (matchVisibleToInstantApp
13220                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13221                return null;
13222            }
13223            // throw out instant application filters if we're not explicitly requesting them
13224            if (!isInstantApp && userState.instantApp) {
13225                return null;
13226            }
13227            // throw out instant application filters if updates are available; will trigger
13228            // instant application resolution
13229            if (userState.instantApp && ps.isUpdateAvailable()) {
13230                return null;
13231            }
13232            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13233                    userState, userId);
13234            if (pi == null) {
13235                return null;
13236            }
13237            final ResolveInfo res = new ResolveInfo();
13238            res.providerInfo = pi;
13239            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13240                res.filter = filter;
13241            }
13242            res.priority = info.getPriority();
13243            res.preferredOrder = provider.owner.mPreferredOrder;
13244            res.match = match;
13245            res.isDefault = info.hasDefault;
13246            res.labelRes = info.labelRes;
13247            res.nonLocalizedLabel = info.nonLocalizedLabel;
13248            res.icon = info.icon;
13249            res.system = res.providerInfo.applicationInfo.isSystemApp();
13250            return res;
13251        }
13252
13253        @Override
13254        protected void sortResults(List<ResolveInfo> results) {
13255            Collections.sort(results, mResolvePrioritySorter);
13256        }
13257
13258        @Override
13259        protected void dumpFilter(PrintWriter out, String prefix,
13260                PackageParser.ProviderIntentInfo filter) {
13261            out.print(prefix);
13262            out.print(
13263                    Integer.toHexString(System.identityHashCode(filter.provider)));
13264            out.print(' ');
13265            filter.provider.printComponentShortName(out);
13266            out.print(" filter ");
13267            out.println(Integer.toHexString(System.identityHashCode(filter)));
13268        }
13269
13270        @Override
13271        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13272            return filter.provider;
13273        }
13274
13275        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13276            PackageParser.Provider provider = (PackageParser.Provider)label;
13277            out.print(prefix); out.print(
13278                    Integer.toHexString(System.identityHashCode(provider)));
13279                    out.print(' ');
13280                    provider.printComponentShortName(out);
13281            if (count > 1) {
13282                out.print(" ("); out.print(count); out.print(" filters)");
13283            }
13284            out.println();
13285        }
13286
13287        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13288                = new ArrayMap<ComponentName, PackageParser.Provider>();
13289        private int mFlags;
13290    }
13291
13292    static final class InstantAppIntentResolver
13293            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13294            AuxiliaryResolveInfo.AuxiliaryFilter> {
13295        /**
13296         * The result that has the highest defined order. Ordering applies on a
13297         * per-package basis. Mapping is from package name to Pair of order and
13298         * EphemeralResolveInfo.
13299         * <p>
13300         * NOTE: This is implemented as a field variable for convenience and efficiency.
13301         * By having a field variable, we're able to track filter ordering as soon as
13302         * a non-zero order is defined. Otherwise, multiple loops across the result set
13303         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13304         * this needs to be contained entirely within {@link #filterResults}.
13305         */
13306        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13307
13308        @Override
13309        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13310            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13311        }
13312
13313        @Override
13314        protected boolean isPackageForFilter(String packageName,
13315                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13316            return true;
13317        }
13318
13319        @Override
13320        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13321                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13322            if (!sUserManager.exists(userId)) {
13323                return null;
13324            }
13325            final String packageName = responseObj.resolveInfo.getPackageName();
13326            final Integer order = responseObj.getOrder();
13327            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13328                    mOrderResult.get(packageName);
13329            // ordering is enabled and this item's order isn't high enough
13330            if (lastOrderResult != null && lastOrderResult.first >= order) {
13331                return null;
13332            }
13333            final InstantAppResolveInfo res = responseObj.resolveInfo;
13334            if (order > 0) {
13335                // non-zero order, enable ordering
13336                mOrderResult.put(packageName, new Pair<>(order, res));
13337            }
13338            return responseObj;
13339        }
13340
13341        @Override
13342        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13343            // only do work if ordering is enabled [most of the time it won't be]
13344            if (mOrderResult.size() == 0) {
13345                return;
13346            }
13347            int resultSize = results.size();
13348            for (int i = 0; i < resultSize; i++) {
13349                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13350                final String packageName = info.getPackageName();
13351                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13352                if (savedInfo == null) {
13353                    // package doesn't having ordering
13354                    continue;
13355                }
13356                if (savedInfo.second == info) {
13357                    // circled back to the highest ordered item; remove from order list
13358                    mOrderResult.remove(packageName);
13359                    if (mOrderResult.size() == 0) {
13360                        // no more ordered items
13361                        break;
13362                    }
13363                    continue;
13364                }
13365                // item has a worse order, remove it from the result list
13366                results.remove(i);
13367                resultSize--;
13368                i--;
13369            }
13370        }
13371    }
13372
13373    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13374            new Comparator<ResolveInfo>() {
13375        public int compare(ResolveInfo r1, ResolveInfo r2) {
13376            int v1 = r1.priority;
13377            int v2 = r2.priority;
13378            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13379            if (v1 != v2) {
13380                return (v1 > v2) ? -1 : 1;
13381            }
13382            v1 = r1.preferredOrder;
13383            v2 = r2.preferredOrder;
13384            if (v1 != v2) {
13385                return (v1 > v2) ? -1 : 1;
13386            }
13387            if (r1.isDefault != r2.isDefault) {
13388                return r1.isDefault ? -1 : 1;
13389            }
13390            v1 = r1.match;
13391            v2 = r2.match;
13392            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13393            if (v1 != v2) {
13394                return (v1 > v2) ? -1 : 1;
13395            }
13396            if (r1.system != r2.system) {
13397                return r1.system ? -1 : 1;
13398            }
13399            if (r1.activityInfo != null) {
13400                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13401            }
13402            if (r1.serviceInfo != null) {
13403                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13404            }
13405            if (r1.providerInfo != null) {
13406                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13407            }
13408            return 0;
13409        }
13410    };
13411
13412    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13413            new Comparator<ProviderInfo>() {
13414        public int compare(ProviderInfo p1, ProviderInfo p2) {
13415            final int v1 = p1.initOrder;
13416            final int v2 = p2.initOrder;
13417            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13418        }
13419    };
13420
13421    @Override
13422    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13423            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13424            final int[] userIds, int[] instantUserIds) {
13425        mHandler.post(new Runnable() {
13426            @Override
13427            public void run() {
13428                try {
13429                    final IActivityManager am = ActivityManager.getService();
13430                    if (am == null) return;
13431                    final int[] resolvedUserIds;
13432                    if (userIds == null) {
13433                        resolvedUserIds = am.getRunningUserIds();
13434                    } else {
13435                        resolvedUserIds = userIds;
13436                    }
13437                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13438                            resolvedUserIds, false);
13439                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13440                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13441                                instantUserIds, true);
13442                    }
13443                } catch (RemoteException ex) {
13444                }
13445            }
13446        });
13447    }
13448
13449    @Override
13450    public void notifyPackageAdded(String packageName) {
13451        final PackageListObserver[] observers;
13452        synchronized (mPackages) {
13453            if (mPackageListObservers.size() == 0) {
13454                return;
13455            }
13456            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13457        }
13458        for (int i = observers.length - 1; i >= 0; --i) {
13459            observers[i].onPackageAdded(packageName);
13460        }
13461    }
13462
13463    @Override
13464    public void notifyPackageRemoved(String packageName) {
13465        final PackageListObserver[] observers;
13466        synchronized (mPackages) {
13467            if (mPackageListObservers.size() == 0) {
13468                return;
13469            }
13470            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13471        }
13472        for (int i = observers.length - 1; i >= 0; --i) {
13473            observers[i].onPackageRemoved(packageName);
13474        }
13475    }
13476
13477    /**
13478     * Sends a broadcast for the given action.
13479     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13480     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13481     * the system and applications allowed to see instant applications to receive package
13482     * lifecycle events for instant applications.
13483     */
13484    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13485            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13486            int[] userIds, boolean isInstantApp)
13487                    throws RemoteException {
13488        for (int id : userIds) {
13489            final Intent intent = new Intent(action,
13490                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13491            final String[] requiredPermissions =
13492                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13493            if (extras != null) {
13494                intent.putExtras(extras);
13495            }
13496            if (targetPkg != null) {
13497                intent.setPackage(targetPkg);
13498            }
13499            // Modify the UID when posting to other users
13500            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13501            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13502                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13503                intent.putExtra(Intent.EXTRA_UID, uid);
13504            }
13505            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13506            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13507            if (DEBUG_BROADCASTS) {
13508                RuntimeException here = new RuntimeException("here");
13509                here.fillInStackTrace();
13510                Slog.d(TAG, "Sending to user " + id + ": "
13511                        + intent.toShortString(false, true, false, false)
13512                        + " " + intent.getExtras(), here);
13513            }
13514            am.broadcastIntent(null, intent, null, finishedReceiver,
13515                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13516                    null, finishedReceiver != null, false, id);
13517        }
13518    }
13519
13520    /**
13521     * Check if the external storage media is available. This is true if there
13522     * is a mounted external storage medium or if the external storage is
13523     * emulated.
13524     */
13525    private boolean isExternalMediaAvailable() {
13526        return mMediaMounted || Environment.isExternalStorageEmulated();
13527    }
13528
13529    @Override
13530    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13531        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13532            return null;
13533        }
13534        if (!isExternalMediaAvailable()) {
13535                // If the external storage is no longer mounted at this point,
13536                // the caller may not have been able to delete all of this
13537                // packages files and can not delete any more.  Bail.
13538            return null;
13539        }
13540        synchronized (mPackages) {
13541            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13542            if (lastPackage != null) {
13543                pkgs.remove(lastPackage);
13544            }
13545            if (pkgs.size() > 0) {
13546                return pkgs.get(0);
13547            }
13548        }
13549        return null;
13550    }
13551
13552    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13553        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13554                userId, andCode ? 1 : 0, packageName);
13555        if (mSystemReady) {
13556            msg.sendToTarget();
13557        } else {
13558            if (mPostSystemReadyMessages == null) {
13559                mPostSystemReadyMessages = new ArrayList<>();
13560            }
13561            mPostSystemReadyMessages.add(msg);
13562        }
13563    }
13564
13565    void startCleaningPackages() {
13566        // reader
13567        if (!isExternalMediaAvailable()) {
13568            return;
13569        }
13570        synchronized (mPackages) {
13571            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13572                return;
13573            }
13574        }
13575        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13576        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13577        IActivityManager am = ActivityManager.getService();
13578        if (am != null) {
13579            int dcsUid = -1;
13580            synchronized (mPackages) {
13581                if (!mDefaultContainerWhitelisted) {
13582                    mDefaultContainerWhitelisted = true;
13583                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13584                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13585                }
13586            }
13587            try {
13588                if (dcsUid > 0) {
13589                    am.backgroundWhitelistUid(dcsUid);
13590                }
13591                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13592                        UserHandle.USER_SYSTEM);
13593            } catch (RemoteException e) {
13594            }
13595        }
13596    }
13597
13598    /**
13599     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13600     * it is acting on behalf on an enterprise or the user).
13601     *
13602     * Note that the ordering of the conditionals in this method is important. The checks we perform
13603     * are as follows, in this order:
13604     *
13605     * 1) If the install is being performed by a system app, we can trust the app to have set the
13606     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13607     *    what it is.
13608     * 2) If the install is being performed by a device or profile owner app, the install reason
13609     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13610     *    set the install reason correctly. If the app targets an older SDK version where install
13611     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13612     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13613     * 3) In all other cases, the install is being performed by a regular app that is neither part
13614     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13615     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13616     *    set to enterprise policy and if so, change it to unknown instead.
13617     */
13618    private int fixUpInstallReason(String installerPackageName, int installerUid,
13619            int installReason) {
13620        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13621                == PERMISSION_GRANTED) {
13622            // If the install is being performed by a system app, we trust that app to have set the
13623            // install reason correctly.
13624            return installReason;
13625        }
13626
13627        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13628            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13629        if (dpm != null) {
13630            ComponentName owner = null;
13631            try {
13632                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13633                if (owner == null) {
13634                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13635                }
13636            } catch (RemoteException e) {
13637            }
13638            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13639                // If the install is being performed by a device or profile owner, the install
13640                // reason should be enterprise policy.
13641                return PackageManager.INSTALL_REASON_POLICY;
13642            }
13643        }
13644
13645        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13646            // If the install is being performed by a regular app (i.e. neither system app nor
13647            // device or profile owner), we have no reason to believe that the app is acting on
13648            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13649            // change it to unknown instead.
13650            return PackageManager.INSTALL_REASON_UNKNOWN;
13651        }
13652
13653        // If the install is being performed by a regular app and the install reason was set to any
13654        // value but enterprise policy, leave the install reason unchanged.
13655        return installReason;
13656    }
13657
13658    /**
13659     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13660     * install commit.
13661     */
13662    void earlyBindToDefContainer() {
13663        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13664    }
13665
13666    void installStage(String packageName, File stagedDir,
13667            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13668            String installerPackageName, int installerUid, UserHandle user,
13669            PackageParser.SigningDetails signingDetails) {
13670        if (DEBUG_INSTANT) {
13671            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13672                Slog.d(TAG, "Ephemeral install of " + packageName);
13673            }
13674        }
13675        final VerificationInfo verificationInfo = new VerificationInfo(
13676                sessionParams.originatingUri, sessionParams.referrerUri,
13677                sessionParams.originatingUid, installerUid);
13678
13679        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13680
13681        final Message msg = mHandler.obtainMessage(INIT_COPY);
13682        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13683                sessionParams.installReason);
13684        final InstallParams params = new InstallParams(origin, null, observer,
13685                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13686                verificationInfo, user, sessionParams.abiOverride,
13687                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13688        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13689        msg.obj = params;
13690
13691        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13692                System.identityHashCode(msg.obj));
13693        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13694                System.identityHashCode(msg.obj));
13695
13696        mHandler.sendMessage(msg);
13697    }
13698
13699    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13700            int userId) {
13701        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13702        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13703        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13704        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13705        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13706                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13707
13708        // Send a session commit broadcast
13709        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13710        info.installReason = pkgSetting.getInstallReason(userId);
13711        info.appPackageName = packageName;
13712        sendSessionCommitBroadcast(info, userId);
13713    }
13714
13715    @Override
13716    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13717            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13718        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13719            return;
13720        }
13721        Bundle extras = new Bundle(1);
13722        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13723        final int uid = UserHandle.getUid(
13724                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13725        extras.putInt(Intent.EXTRA_UID, uid);
13726
13727        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13728                packageName, extras, 0, null, null, userIds, instantUserIds);
13729        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13730            mHandler.post(() -> {
13731                        for (int userId : userIds) {
13732                            sendBootCompletedBroadcastToSystemApp(
13733                                    packageName, includeStopped, userId);
13734                        }
13735                    }
13736            );
13737        }
13738    }
13739
13740    /**
13741     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13742     * automatically without needing an explicit launch.
13743     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13744     */
13745    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13746            int userId) {
13747        // If user is not running, the app didn't miss any broadcast
13748        if (!mUserManagerInternal.isUserRunning(userId)) {
13749            return;
13750        }
13751        final IActivityManager am = ActivityManager.getService();
13752        try {
13753            // Deliver LOCKED_BOOT_COMPLETED first
13754            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13755                    .setPackage(packageName);
13756            if (includeStopped) {
13757                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13758            }
13759            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13760            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13761                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13762
13763            // Deliver BOOT_COMPLETED only if user is unlocked
13764            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13765                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13766                if (includeStopped) {
13767                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13768                }
13769                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13770                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13771            }
13772        } catch (RemoteException e) {
13773            throw e.rethrowFromSystemServer();
13774        }
13775    }
13776
13777    @Override
13778    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13779            int userId) {
13780        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13781        PackageSetting pkgSetting;
13782        final int callingUid = Binder.getCallingUid();
13783        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13784                true /* requireFullPermission */, true /* checkShell */,
13785                "setApplicationHiddenSetting for user " + userId);
13786
13787        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13788            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13789            return false;
13790        }
13791
13792        long callingId = Binder.clearCallingIdentity();
13793        try {
13794            boolean sendAdded = false;
13795            boolean sendRemoved = false;
13796            // writer
13797            synchronized (mPackages) {
13798                pkgSetting = mSettings.mPackages.get(packageName);
13799                if (pkgSetting == null) {
13800                    return false;
13801                }
13802                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13803                    return false;
13804                }
13805                // Do not allow "android" is being disabled
13806                if ("android".equals(packageName)) {
13807                    Slog.w(TAG, "Cannot hide package: android");
13808                    return false;
13809                }
13810                // Cannot hide static shared libs as they are considered
13811                // a part of the using app (emulating static linking). Also
13812                // static libs are installed always on internal storage.
13813                PackageParser.Package pkg = mPackages.get(packageName);
13814                if (pkg != null && pkg.staticSharedLibName != null) {
13815                    Slog.w(TAG, "Cannot hide package: " + packageName
13816                            + " providing static shared library: "
13817                            + pkg.staticSharedLibName);
13818                    return false;
13819                }
13820                // Only allow protected packages to hide themselves.
13821                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13822                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13823                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13824                    return false;
13825                }
13826
13827                if (pkgSetting.getHidden(userId) != hidden) {
13828                    pkgSetting.setHidden(hidden, userId);
13829                    mSettings.writePackageRestrictionsLPr(userId);
13830                    if (hidden) {
13831                        sendRemoved = true;
13832                    } else {
13833                        sendAdded = true;
13834                    }
13835                }
13836            }
13837            if (sendAdded) {
13838                sendPackageAddedForUser(packageName, pkgSetting, userId);
13839                return true;
13840            }
13841            if (sendRemoved) {
13842                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13843                        "hiding pkg");
13844                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13845                return true;
13846            }
13847        } finally {
13848            Binder.restoreCallingIdentity(callingId);
13849        }
13850        return false;
13851    }
13852
13853    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13854            int userId) {
13855        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13856        info.removedPackage = packageName;
13857        info.installerPackageName = pkgSetting.installerPackageName;
13858        info.removedUsers = new int[] {userId};
13859        info.broadcastUsers = new int[] {userId};
13860        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13861        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13862    }
13863
13864    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13865            PersistableBundle launcherExtras) {
13866        if (pkgList.length > 0) {
13867            Bundle extras = new Bundle(1);
13868            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13869            if (launcherExtras != null) {
13870                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13871                        new Bundle(launcherExtras.deepCopy()));
13872            }
13873            sendPackageBroadcast(
13874                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13875                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13876                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13877                    new int[] {userId}, null);
13878        }
13879    }
13880
13881    /**
13882     * Returns true if application is not found or there was an error. Otherwise it returns
13883     * the hidden state of the package for the given user.
13884     */
13885    @Override
13886    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13888        final int callingUid = Binder.getCallingUid();
13889        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13890                true /* requireFullPermission */, false /* checkShell */,
13891                "getApplicationHidden for user " + userId);
13892        PackageSetting ps;
13893        long callingId = Binder.clearCallingIdentity();
13894        try {
13895            // writer
13896            synchronized (mPackages) {
13897                ps = mSettings.mPackages.get(packageName);
13898                if (ps == null) {
13899                    return true;
13900                }
13901                if (filterAppAccessLPr(ps, callingUid, userId)) {
13902                    return true;
13903                }
13904                return ps.getHidden(userId);
13905            }
13906        } finally {
13907            Binder.restoreCallingIdentity(callingId);
13908        }
13909    }
13910
13911    /**
13912     * @hide
13913     */
13914    @Override
13915    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13916            int installReason) {
13917        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13918                null);
13919        PackageSetting pkgSetting;
13920        final int callingUid = Binder.getCallingUid();
13921        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13922                true /* requireFullPermission */, true /* checkShell */,
13923                "installExistingPackage for user " + userId);
13924        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13925            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13926        }
13927
13928        long callingId = Binder.clearCallingIdentity();
13929        try {
13930            boolean installed = false;
13931            final boolean instantApp =
13932                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13933            final boolean fullApp =
13934                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13935
13936            // writer
13937            synchronized (mPackages) {
13938                pkgSetting = mSettings.mPackages.get(packageName);
13939                if (pkgSetting == null) {
13940                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13941                }
13942                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13943                    // only allow the existing package to be used if it's installed as a full
13944                    // application for at least one user
13945                    boolean installAllowed = false;
13946                    for (int checkUserId : sUserManager.getUserIds()) {
13947                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13948                        if (installAllowed) {
13949                            break;
13950                        }
13951                    }
13952                    if (!installAllowed) {
13953                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13954                    }
13955                }
13956                if (!pkgSetting.getInstalled(userId)) {
13957                    pkgSetting.setInstalled(true, userId);
13958                    pkgSetting.setHidden(false, userId);
13959                    pkgSetting.setInstallReason(installReason, userId);
13960                    mSettings.writePackageRestrictionsLPr(userId);
13961                    mSettings.writeKernelMappingLPr(pkgSetting);
13962                    installed = true;
13963                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13964                    // upgrade app from instant to full; we don't allow app downgrade
13965                    installed = true;
13966                }
13967                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13968            }
13969
13970            if (installed) {
13971                if (pkgSetting.pkg != null) {
13972                    synchronized (mInstallLock) {
13973                        // We don't need to freeze for a brand new install
13974                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13975                    }
13976                }
13977                sendPackageAddedForUser(packageName, pkgSetting, userId);
13978                synchronized (mPackages) {
13979                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13980                }
13981            }
13982        } finally {
13983            Binder.restoreCallingIdentity(callingId);
13984        }
13985
13986        return PackageManager.INSTALL_SUCCEEDED;
13987    }
13988
13989    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13990            boolean instantApp, boolean fullApp) {
13991        // no state specified; do nothing
13992        if (!instantApp && !fullApp) {
13993            return;
13994        }
13995        if (userId != UserHandle.USER_ALL) {
13996            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13997                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13998            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13999                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14000            }
14001        } else {
14002            for (int currentUserId : sUserManager.getUserIds()) {
14003                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14004                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14005                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14006                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14007                }
14008            }
14009        }
14010    }
14011
14012    boolean isUserRestricted(int userId, String restrictionKey) {
14013        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14014        if (restrictions.getBoolean(restrictionKey, false)) {
14015            Log.w(TAG, "User is restricted: " + restrictionKey);
14016            return true;
14017        }
14018        return false;
14019    }
14020
14021    @Override
14022    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14023            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14024            String callingPackage, int userId) {
14025        try {
14026            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14027        } catch (SecurityException e) {
14028            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14029                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14030                            + Manifest.permission.MANAGE_USERS);
14031        }
14032        final int callingUid = Binder.getCallingUid();
14033        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14034                true /* requireFullPermission */, true /* checkShell */,
14035                "setPackagesSuspended for user " + userId);
14036        if (callingUid != Process.ROOT_UID &&
14037                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
14038            throw new IllegalArgumentException("CallingPackage " + callingPackage + " does not"
14039                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
14040        }
14041
14042        if (ArrayUtils.isEmpty(packageNames)) {
14043            return packageNames;
14044        }
14045
14046        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14047        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14048        final long callingId = Binder.clearCallingIdentity();
14049        try {
14050            synchronized (mPackages) {
14051                for (int i = 0; i < packageNames.length; i++) {
14052                    final String packageName = packageNames[i];
14053                    if (callingPackage.equals(packageName)) {
14054                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14055                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14056                        unactionedPackages.add(packageName);
14057                        continue;
14058                    }
14059                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14060                    if (pkgSetting == null
14061                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14062                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14063                                + ". Skipping suspending/un-suspending.");
14064                        unactionedPackages.add(packageName);
14065                        continue;
14066                    }
14067                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14068                        unactionedPackages.add(packageName);
14069                        continue;
14070                    }
14071                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14072                            launcherExtras, userId);
14073                    changedPackagesList.add(packageName);
14074                }
14075            }
14076        } finally {
14077            Binder.restoreCallingIdentity(callingId);
14078        }
14079        if (!changedPackagesList.isEmpty()) {
14080            final String[] changedPackages = changedPackagesList.toArray(
14081                    new String[changedPackagesList.size()]);
14082            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14083            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14084            synchronized (mPackages) {
14085                scheduleWritePackageRestrictionsLocked(userId);
14086            }
14087        }
14088        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14089    }
14090
14091    @Override
14092    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14093        final int callingUid = Binder.getCallingUid();
14094        if (getPackageUid(packageName, 0, userId) != callingUid) {
14095            throw new SecurityException("Calling package " + packageName
14096                    + " does not belong to calling uid " + callingUid);
14097        }
14098        synchronized (mPackages) {
14099            final PackageSetting ps = mSettings.mPackages.get(packageName);
14100            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14101                throw new IllegalArgumentException("Unknown target package: " + packageName);
14102            }
14103            final PackageUserState packageUserState = ps.readUserState(userId);
14104            if (packageUserState.suspended) {
14105                return packageUserState.suspendedAppExtras;
14106            }
14107            return null;
14108        }
14109    }
14110
14111    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14112            PersistableBundle appExtras, int userId) {
14113        final String action;
14114        final Bundle intentExtras = new Bundle();
14115        if (suspended) {
14116            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14117            if (appExtras != null) {
14118                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14119                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14120            }
14121        } else {
14122            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14123        }
14124        mHandler.post(new Runnable() {
14125            @Override
14126            public void run() {
14127                try {
14128                    final IActivityManager am = ActivityManager.getService();
14129                    if (am == null) {
14130                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14131                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14132                        return;
14133                    }
14134                    final int[] targetUserIds = new int[] {userId};
14135                    for (String packageName : affectedPackages) {
14136                        doSendBroadcast(am, action, null, intentExtras,
14137                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14138                                targetUserIds, false);
14139                    }
14140                } catch (RemoteException ex) {
14141                    // Shouldn't happen as AMS is in the same process.
14142                }
14143            }
14144        });
14145    }
14146
14147    @Override
14148    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14149        final int callingUid = Binder.getCallingUid();
14150        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14151                true /* requireFullPermission */, false /* checkShell */,
14152                "isPackageSuspendedForUser for user " + userId);
14153        synchronized (mPackages) {
14154            final PackageSetting ps = mSettings.mPackages.get(packageName);
14155            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14156                throw new IllegalArgumentException("Unknown target package: " + packageName);
14157            }
14158            return ps.getSuspended(userId);
14159        }
14160    }
14161
14162    void onSuspendingPackageRemoved(String packageName, int removedForUser) {
14163        final int[] userIds = (removedForUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14164                : new int[] {removedForUser};
14165        for (int userId : userIds) {
14166            List<String> affectedPackages = new ArrayList<>();
14167            synchronized (mPackages) {
14168                for (PackageSetting ps : mSettings.mPackages.values()) {
14169                    final PackageUserState pus = ps.readUserState(userId);
14170                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14171                        ps.setSuspended(false, null, null, null, null, userId);
14172                        affectedPackages.add(ps.name);
14173                    }
14174                }
14175            }
14176            if (!affectedPackages.isEmpty()) {
14177                final String[] packageArray = affectedPackages.toArray(
14178                        new String[affectedPackages.size()]);
14179                sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14180                sendPackagesSuspendedForUser(packageArray, userId, false, null);
14181            }
14182        }
14183    }
14184
14185    @GuardedBy("mPackages")
14186    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14187        if (isPackageDeviceAdmin(packageName, userId)) {
14188            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14189                    + "\": has an active device admin");
14190            return false;
14191        }
14192
14193        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14194        if (packageName.equals(activeLauncherPackageName)) {
14195            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14196                    + "\": contains the active launcher");
14197            return false;
14198        }
14199
14200        if (packageName.equals(mRequiredInstallerPackage)) {
14201            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14202                    + "\": required for package installation");
14203            return false;
14204        }
14205
14206        if (packageName.equals(mRequiredUninstallerPackage)) {
14207            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14208                    + "\": required for package uninstallation");
14209            return false;
14210        }
14211
14212        if (packageName.equals(mRequiredVerifierPackage)) {
14213            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14214                    + "\": required for package verification");
14215            return false;
14216        }
14217
14218        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14219            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14220                    + "\": is the default dialer");
14221            return false;
14222        }
14223
14224        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14225            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14226                    + "\": protected package");
14227            return false;
14228        }
14229
14230        // Cannot suspend static shared libs as they are considered
14231        // a part of the using app (emulating static linking). Also
14232        // static libs are installed always on internal storage.
14233        PackageParser.Package pkg = mPackages.get(packageName);
14234        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14235            Slog.w(TAG, "Cannot suspend package: " + packageName
14236                    + " providing static shared library: "
14237                    + pkg.staticSharedLibName);
14238            return false;
14239        }
14240
14241        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14242            Slog.w(TAG, "Cannot suspend package: " + packageName);
14243            return false;
14244        }
14245
14246        return true;
14247    }
14248
14249    private String getActiveLauncherPackageName(int userId) {
14250        Intent intent = new Intent(Intent.ACTION_MAIN);
14251        intent.addCategory(Intent.CATEGORY_HOME);
14252        ResolveInfo resolveInfo = resolveIntent(
14253                intent,
14254                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14255                PackageManager.MATCH_DEFAULT_ONLY,
14256                userId);
14257
14258        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14259    }
14260
14261    private String getDefaultDialerPackageName(int userId) {
14262        synchronized (mPackages) {
14263            return mSettings.getDefaultDialerPackageNameLPw(userId);
14264        }
14265    }
14266
14267    @Override
14268    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14269        mContext.enforceCallingOrSelfPermission(
14270                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14271                "Only package verification agents can verify applications");
14272
14273        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14274        final PackageVerificationResponse response = new PackageVerificationResponse(
14275                verificationCode, Binder.getCallingUid());
14276        msg.arg1 = id;
14277        msg.obj = response;
14278        mHandler.sendMessage(msg);
14279    }
14280
14281    @Override
14282    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14283            long millisecondsToDelay) {
14284        mContext.enforceCallingOrSelfPermission(
14285                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14286                "Only package verification agents can extend verification timeouts");
14287
14288        final PackageVerificationState state = mPendingVerification.get(id);
14289        final PackageVerificationResponse response = new PackageVerificationResponse(
14290                verificationCodeAtTimeout, Binder.getCallingUid());
14291
14292        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14293            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14294        }
14295        if (millisecondsToDelay < 0) {
14296            millisecondsToDelay = 0;
14297        }
14298        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14299                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14300            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14301        }
14302
14303        if ((state != null) && !state.timeoutExtended()) {
14304            state.extendTimeout();
14305
14306            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14307            msg.arg1 = id;
14308            msg.obj = response;
14309            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14310        }
14311    }
14312
14313    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14314            int verificationCode, UserHandle user) {
14315        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14316        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14317        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14318        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14319        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14320
14321        mContext.sendBroadcastAsUser(intent, user,
14322                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14323    }
14324
14325    private ComponentName matchComponentForVerifier(String packageName,
14326            List<ResolveInfo> receivers) {
14327        ActivityInfo targetReceiver = null;
14328
14329        final int NR = receivers.size();
14330        for (int i = 0; i < NR; i++) {
14331            final ResolveInfo info = receivers.get(i);
14332            if (info.activityInfo == null) {
14333                continue;
14334            }
14335
14336            if (packageName.equals(info.activityInfo.packageName)) {
14337                targetReceiver = info.activityInfo;
14338                break;
14339            }
14340        }
14341
14342        if (targetReceiver == null) {
14343            return null;
14344        }
14345
14346        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14347    }
14348
14349    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14350            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14351        if (pkgInfo.verifiers.length == 0) {
14352            return null;
14353        }
14354
14355        final int N = pkgInfo.verifiers.length;
14356        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14357        for (int i = 0; i < N; i++) {
14358            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14359
14360            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14361                    receivers);
14362            if (comp == null) {
14363                continue;
14364            }
14365
14366            final int verifierUid = getUidForVerifier(verifierInfo);
14367            if (verifierUid == -1) {
14368                continue;
14369            }
14370
14371            if (DEBUG_VERIFY) {
14372                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14373                        + " with the correct signature");
14374            }
14375            sufficientVerifiers.add(comp);
14376            verificationState.addSufficientVerifier(verifierUid);
14377        }
14378
14379        return sufficientVerifiers;
14380    }
14381
14382    private int getUidForVerifier(VerifierInfo verifierInfo) {
14383        synchronized (mPackages) {
14384            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14385            if (pkg == null) {
14386                return -1;
14387            } else if (pkg.mSigningDetails.signatures.length != 1) {
14388                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14389                        + " has more than one signature; ignoring");
14390                return -1;
14391            }
14392
14393            /*
14394             * If the public key of the package's signature does not match
14395             * our expected public key, then this is a different package and
14396             * we should skip.
14397             */
14398
14399            final byte[] expectedPublicKey;
14400            try {
14401                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14402                final PublicKey publicKey = verifierSig.getPublicKey();
14403                expectedPublicKey = publicKey.getEncoded();
14404            } catch (CertificateException e) {
14405                return -1;
14406            }
14407
14408            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14409
14410            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14411                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14412                        + " does not have the expected public key; ignoring");
14413                return -1;
14414            }
14415
14416            return pkg.applicationInfo.uid;
14417        }
14418    }
14419
14420    @Override
14421    public void finishPackageInstall(int token, boolean didLaunch) {
14422        enforceSystemOrRoot("Only the system is allowed to finish installs");
14423
14424        if (DEBUG_INSTALL) {
14425            Slog.v(TAG, "BM finishing package install for " + token);
14426        }
14427        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14428
14429        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14430        mHandler.sendMessage(msg);
14431    }
14432
14433    /**
14434     * Get the verification agent timeout.  Used for both the APK verifier and the
14435     * intent filter verifier.
14436     *
14437     * @return verification timeout in milliseconds
14438     */
14439    private long getVerificationTimeout() {
14440        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14441                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14442                DEFAULT_VERIFICATION_TIMEOUT);
14443    }
14444
14445    /**
14446     * Get the default verification agent response code.
14447     *
14448     * @return default verification response code
14449     */
14450    private int getDefaultVerificationResponse(UserHandle user) {
14451        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14452            return PackageManager.VERIFICATION_REJECT;
14453        }
14454        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14455                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14456                DEFAULT_VERIFICATION_RESPONSE);
14457    }
14458
14459    /**
14460     * Check whether or not package verification has been enabled.
14461     *
14462     * @return true if verification should be performed
14463     */
14464    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14465        if (!DEFAULT_VERIFY_ENABLE) {
14466            return false;
14467        }
14468
14469        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14470
14471        // Check if installing from ADB
14472        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14473            // Do not run verification in a test harness environment
14474            if (ActivityManager.isRunningInTestHarness()) {
14475                return false;
14476            }
14477            if (ensureVerifyAppsEnabled) {
14478                return true;
14479            }
14480            // Check if the developer does not want package verification for ADB installs
14481            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14482                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14483                return false;
14484            }
14485        } else {
14486            // only when not installed from ADB, skip verification for instant apps when
14487            // the installer and verifier are the same.
14488            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14489                if (mInstantAppInstallerActivity != null
14490                        && mInstantAppInstallerActivity.packageName.equals(
14491                                mRequiredVerifierPackage)) {
14492                    try {
14493                        mContext.getSystemService(AppOpsManager.class)
14494                                .checkPackage(installerUid, mRequiredVerifierPackage);
14495                        if (DEBUG_VERIFY) {
14496                            Slog.i(TAG, "disable verification for instant app");
14497                        }
14498                        return false;
14499                    } catch (SecurityException ignore) { }
14500                }
14501            }
14502        }
14503
14504        if (ensureVerifyAppsEnabled) {
14505            return true;
14506        }
14507
14508        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14509                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14510    }
14511
14512    @Override
14513    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14514            throws RemoteException {
14515        mContext.enforceCallingOrSelfPermission(
14516                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14517                "Only intentfilter verification agents can verify applications");
14518
14519        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14520        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14521                Binder.getCallingUid(), verificationCode, failedDomains);
14522        msg.arg1 = id;
14523        msg.obj = response;
14524        mHandler.sendMessage(msg);
14525    }
14526
14527    @Override
14528    public int getIntentVerificationStatus(String packageName, int userId) {
14529        final int callingUid = Binder.getCallingUid();
14530        if (UserHandle.getUserId(callingUid) != userId) {
14531            mContext.enforceCallingOrSelfPermission(
14532                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14533                    "getIntentVerificationStatus" + userId);
14534        }
14535        if (getInstantAppPackageName(callingUid) != null) {
14536            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14537        }
14538        synchronized (mPackages) {
14539            final PackageSetting ps = mSettings.mPackages.get(packageName);
14540            if (ps == null
14541                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14542                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14543            }
14544            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14545        }
14546    }
14547
14548    @Override
14549    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14550        mContext.enforceCallingOrSelfPermission(
14551                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14552
14553        boolean result = false;
14554        synchronized (mPackages) {
14555            final PackageSetting ps = mSettings.mPackages.get(packageName);
14556            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14557                return false;
14558            }
14559            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14560        }
14561        if (result) {
14562            scheduleWritePackageRestrictionsLocked(userId);
14563        }
14564        return result;
14565    }
14566
14567    @Override
14568    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14569            String packageName) {
14570        final int callingUid = Binder.getCallingUid();
14571        if (getInstantAppPackageName(callingUid) != null) {
14572            return ParceledListSlice.emptyList();
14573        }
14574        synchronized (mPackages) {
14575            final PackageSetting ps = mSettings.mPackages.get(packageName);
14576            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14577                return ParceledListSlice.emptyList();
14578            }
14579            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14580        }
14581    }
14582
14583    @Override
14584    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14585        if (TextUtils.isEmpty(packageName)) {
14586            return ParceledListSlice.emptyList();
14587        }
14588        final int callingUid = Binder.getCallingUid();
14589        final int callingUserId = UserHandle.getUserId(callingUid);
14590        synchronized (mPackages) {
14591            PackageParser.Package pkg = mPackages.get(packageName);
14592            if (pkg == null || pkg.activities == null) {
14593                return ParceledListSlice.emptyList();
14594            }
14595            if (pkg.mExtras == null) {
14596                return ParceledListSlice.emptyList();
14597            }
14598            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14599            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14600                return ParceledListSlice.emptyList();
14601            }
14602            final int count = pkg.activities.size();
14603            ArrayList<IntentFilter> result = new ArrayList<>();
14604            for (int n=0; n<count; n++) {
14605                PackageParser.Activity activity = pkg.activities.get(n);
14606                if (activity.intents != null && activity.intents.size() > 0) {
14607                    result.addAll(activity.intents);
14608                }
14609            }
14610            return new ParceledListSlice<>(result);
14611        }
14612    }
14613
14614    @Override
14615    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14616        mContext.enforceCallingOrSelfPermission(
14617                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14618        if (UserHandle.getCallingUserId() != userId) {
14619            mContext.enforceCallingOrSelfPermission(
14620                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14621        }
14622
14623        synchronized (mPackages) {
14624            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14625            if (packageName != null) {
14626                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14627                        packageName, userId);
14628            }
14629            return result;
14630        }
14631    }
14632
14633    @Override
14634    public String getDefaultBrowserPackageName(int userId) {
14635        if (UserHandle.getCallingUserId() != userId) {
14636            mContext.enforceCallingOrSelfPermission(
14637                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14638        }
14639        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14640            return null;
14641        }
14642        synchronized (mPackages) {
14643            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14644        }
14645    }
14646
14647    /**
14648     * Get the "allow unknown sources" setting.
14649     *
14650     * @return the current "allow unknown sources" setting
14651     */
14652    private int getUnknownSourcesSettings() {
14653        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14654                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14655                -1);
14656    }
14657
14658    @Override
14659    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14660        final int callingUid = Binder.getCallingUid();
14661        if (getInstantAppPackageName(callingUid) != null) {
14662            return;
14663        }
14664        // writer
14665        synchronized (mPackages) {
14666            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14667            if (targetPackageSetting == null
14668                    || filterAppAccessLPr(
14669                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14670                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14671            }
14672
14673            PackageSetting installerPackageSetting;
14674            if (installerPackageName != null) {
14675                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14676                if (installerPackageSetting == null) {
14677                    throw new IllegalArgumentException("Unknown installer package: "
14678                            + installerPackageName);
14679                }
14680            } else {
14681                installerPackageSetting = null;
14682            }
14683
14684            Signature[] callerSignature;
14685            Object obj = mSettings.getUserIdLPr(callingUid);
14686            if (obj != null) {
14687                if (obj instanceof SharedUserSetting) {
14688                    callerSignature =
14689                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14690                } else if (obj instanceof PackageSetting) {
14691                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14692                } else {
14693                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14694                }
14695            } else {
14696                throw new SecurityException("Unknown calling UID: " + callingUid);
14697            }
14698
14699            // Verify: can't set installerPackageName to a package that is
14700            // not signed with the same cert as the caller.
14701            if (installerPackageSetting != null) {
14702                if (compareSignatures(callerSignature,
14703                        installerPackageSetting.signatures.mSigningDetails.signatures)
14704                        != PackageManager.SIGNATURE_MATCH) {
14705                    throw new SecurityException(
14706                            "Caller does not have same cert as new installer package "
14707                            + installerPackageName);
14708                }
14709            }
14710
14711            // Verify: if target already has an installer package, it must
14712            // be signed with the same cert as the caller.
14713            if (targetPackageSetting.installerPackageName != null) {
14714                PackageSetting setting = mSettings.mPackages.get(
14715                        targetPackageSetting.installerPackageName);
14716                // If the currently set package isn't valid, then it's always
14717                // okay to change it.
14718                if (setting != null) {
14719                    if (compareSignatures(callerSignature,
14720                            setting.signatures.mSigningDetails.signatures)
14721                            != PackageManager.SIGNATURE_MATCH) {
14722                        throw new SecurityException(
14723                                "Caller does not have same cert as old installer package "
14724                                + targetPackageSetting.installerPackageName);
14725                    }
14726                }
14727            }
14728
14729            // Okay!
14730            targetPackageSetting.installerPackageName = installerPackageName;
14731            if (installerPackageName != null) {
14732                mSettings.mInstallerPackages.add(installerPackageName);
14733            }
14734            scheduleWriteSettingsLocked();
14735        }
14736    }
14737
14738    @Override
14739    public void setApplicationCategoryHint(String packageName, int categoryHint,
14740            String callerPackageName) {
14741        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14742            throw new SecurityException("Instant applications don't have access to this method");
14743        }
14744        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14745                callerPackageName);
14746        synchronized (mPackages) {
14747            PackageSetting ps = mSettings.mPackages.get(packageName);
14748            if (ps == null) {
14749                throw new IllegalArgumentException("Unknown target package " + packageName);
14750            }
14751            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14752                throw new IllegalArgumentException("Unknown target package " + packageName);
14753            }
14754            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14755                throw new IllegalArgumentException("Calling package " + callerPackageName
14756                        + " is not installer for " + packageName);
14757            }
14758
14759            if (ps.categoryHint != categoryHint) {
14760                ps.categoryHint = categoryHint;
14761                scheduleWriteSettingsLocked();
14762            }
14763        }
14764    }
14765
14766    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14767        // Queue up an async operation since the package installation may take a little while.
14768        mHandler.post(new Runnable() {
14769            public void run() {
14770                mHandler.removeCallbacks(this);
14771                 // Result object to be returned
14772                PackageInstalledInfo res = new PackageInstalledInfo();
14773                res.setReturnCode(currentStatus);
14774                res.uid = -1;
14775                res.pkg = null;
14776                res.removedInfo = null;
14777                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14778                    args.doPreInstall(res.returnCode);
14779                    synchronized (mInstallLock) {
14780                        installPackageTracedLI(args, res);
14781                    }
14782                    args.doPostInstall(res.returnCode, res.uid);
14783                }
14784
14785                // A restore should be performed at this point if (a) the install
14786                // succeeded, (b) the operation is not an update, and (c) the new
14787                // package has not opted out of backup participation.
14788                final boolean update = res.removedInfo != null
14789                        && res.removedInfo.removedPackage != null;
14790                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14791                boolean doRestore = !update
14792                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14793
14794                // Set up the post-install work request bookkeeping.  This will be used
14795                // and cleaned up by the post-install event handling regardless of whether
14796                // there's a restore pass performed.  Token values are >= 1.
14797                int token;
14798                if (mNextInstallToken < 0) mNextInstallToken = 1;
14799                token = mNextInstallToken++;
14800
14801                PostInstallData data = new PostInstallData(args, res);
14802                mRunningInstalls.put(token, data);
14803                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14804
14805                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14806                    // Pass responsibility to the Backup Manager.  It will perform a
14807                    // restore if appropriate, then pass responsibility back to the
14808                    // Package Manager to run the post-install observer callbacks
14809                    // and broadcasts.
14810                    IBackupManager bm = IBackupManager.Stub.asInterface(
14811                            ServiceManager.getService(Context.BACKUP_SERVICE));
14812                    if (bm != null) {
14813                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14814                                + " to BM for possible restore");
14815                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14816                        try {
14817                            // TODO: http://b/22388012
14818                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14819                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14820                            } else {
14821                                doRestore = false;
14822                            }
14823                        } catch (RemoteException e) {
14824                            // can't happen; the backup manager is local
14825                        } catch (Exception e) {
14826                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14827                            doRestore = false;
14828                        }
14829                    } else {
14830                        Slog.e(TAG, "Backup Manager not found!");
14831                        doRestore = false;
14832                    }
14833                }
14834
14835                if (!doRestore) {
14836                    // No restore possible, or the Backup Manager was mysteriously not
14837                    // available -- just fire the post-install work request directly.
14838                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14839
14840                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14841
14842                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14843                    mHandler.sendMessage(msg);
14844                }
14845            }
14846        });
14847    }
14848
14849    /**
14850     * Callback from PackageSettings whenever an app is first transitioned out of the
14851     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14852     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14853     * here whether the app is the target of an ongoing install, and only send the
14854     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14855     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14856     * handling.
14857     */
14858    void notifyFirstLaunch(final String packageName, final String installerPackage,
14859            final int userId) {
14860        // Serialize this with the rest of the install-process message chain.  In the
14861        // restore-at-install case, this Runnable will necessarily run before the
14862        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14863        // are coherent.  In the non-restore case, the app has already completed install
14864        // and been launched through some other means, so it is not in a problematic
14865        // state for observers to see the FIRST_LAUNCH signal.
14866        mHandler.post(new Runnable() {
14867            @Override
14868            public void run() {
14869                for (int i = 0; i < mRunningInstalls.size(); i++) {
14870                    final PostInstallData data = mRunningInstalls.valueAt(i);
14871                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14872                        continue;
14873                    }
14874                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14875                        // right package; but is it for the right user?
14876                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14877                            if (userId == data.res.newUsers[uIndex]) {
14878                                if (DEBUG_BACKUP) {
14879                                    Slog.i(TAG, "Package " + packageName
14880                                            + " being restored so deferring FIRST_LAUNCH");
14881                                }
14882                                return;
14883                            }
14884                        }
14885                    }
14886                }
14887                // didn't find it, so not being restored
14888                if (DEBUG_BACKUP) {
14889                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14890                }
14891                final boolean isInstantApp = isInstantApp(packageName, userId);
14892                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14893                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14894                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14895            }
14896        });
14897    }
14898
14899    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14900            int[] userIds, int[] instantUserIds) {
14901        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14902                installerPkg, null, userIds, instantUserIds);
14903    }
14904
14905    private abstract class HandlerParams {
14906        private static final int MAX_RETRIES = 4;
14907
14908        /**
14909         * Number of times startCopy() has been attempted and had a non-fatal
14910         * error.
14911         */
14912        private int mRetries = 0;
14913
14914        /** User handle for the user requesting the information or installation. */
14915        private final UserHandle mUser;
14916        String traceMethod;
14917        int traceCookie;
14918
14919        HandlerParams(UserHandle user) {
14920            mUser = user;
14921        }
14922
14923        UserHandle getUser() {
14924            return mUser;
14925        }
14926
14927        HandlerParams setTraceMethod(String traceMethod) {
14928            this.traceMethod = traceMethod;
14929            return this;
14930        }
14931
14932        HandlerParams setTraceCookie(int traceCookie) {
14933            this.traceCookie = traceCookie;
14934            return this;
14935        }
14936
14937        final boolean startCopy() {
14938            boolean res;
14939            try {
14940                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14941
14942                if (++mRetries > MAX_RETRIES) {
14943                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14944                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14945                    handleServiceError();
14946                    return false;
14947                } else {
14948                    handleStartCopy();
14949                    res = true;
14950                }
14951            } catch (RemoteException e) {
14952                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14953                mHandler.sendEmptyMessage(MCS_RECONNECT);
14954                res = false;
14955            }
14956            handleReturnCode();
14957            return res;
14958        }
14959
14960        final void serviceError() {
14961            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14962            handleServiceError();
14963            handleReturnCode();
14964        }
14965
14966        abstract void handleStartCopy() throws RemoteException;
14967        abstract void handleServiceError();
14968        abstract void handleReturnCode();
14969    }
14970
14971    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14972        for (File path : paths) {
14973            try {
14974                mcs.clearDirectory(path.getAbsolutePath());
14975            } catch (RemoteException e) {
14976            }
14977        }
14978    }
14979
14980    static class OriginInfo {
14981        /**
14982         * Location where install is coming from, before it has been
14983         * copied/renamed into place. This could be a single monolithic APK
14984         * file, or a cluster directory. This location may be untrusted.
14985         */
14986        final File file;
14987
14988        /**
14989         * Flag indicating that {@link #file} or {@link #cid} has already been
14990         * staged, meaning downstream users don't need to defensively copy the
14991         * contents.
14992         */
14993        final boolean staged;
14994
14995        /**
14996         * Flag indicating that {@link #file} or {@link #cid} is an already
14997         * installed app that is being moved.
14998         */
14999        final boolean existing;
15000
15001        final String resolvedPath;
15002        final File resolvedFile;
15003
15004        static OriginInfo fromNothing() {
15005            return new OriginInfo(null, false, false);
15006        }
15007
15008        static OriginInfo fromUntrustedFile(File file) {
15009            return new OriginInfo(file, false, false);
15010        }
15011
15012        static OriginInfo fromExistingFile(File file) {
15013            return new OriginInfo(file, false, true);
15014        }
15015
15016        static OriginInfo fromStagedFile(File file) {
15017            return new OriginInfo(file, true, false);
15018        }
15019
15020        private OriginInfo(File file, boolean staged, boolean existing) {
15021            this.file = file;
15022            this.staged = staged;
15023            this.existing = existing;
15024
15025            if (file != null) {
15026                resolvedPath = file.getAbsolutePath();
15027                resolvedFile = file;
15028            } else {
15029                resolvedPath = null;
15030                resolvedFile = null;
15031            }
15032        }
15033    }
15034
15035    static class MoveInfo {
15036        final int moveId;
15037        final String fromUuid;
15038        final String toUuid;
15039        final String packageName;
15040        final String dataAppName;
15041        final int appId;
15042        final String seinfo;
15043        final int targetSdkVersion;
15044
15045        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15046                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15047            this.moveId = moveId;
15048            this.fromUuid = fromUuid;
15049            this.toUuid = toUuid;
15050            this.packageName = packageName;
15051            this.dataAppName = dataAppName;
15052            this.appId = appId;
15053            this.seinfo = seinfo;
15054            this.targetSdkVersion = targetSdkVersion;
15055        }
15056    }
15057
15058    static class VerificationInfo {
15059        /** A constant used to indicate that a uid value is not present. */
15060        public static final int NO_UID = -1;
15061
15062        /** URI referencing where the package was downloaded from. */
15063        final Uri originatingUri;
15064
15065        /** HTTP referrer URI associated with the originatingURI. */
15066        final Uri referrer;
15067
15068        /** UID of the application that the install request originated from. */
15069        final int originatingUid;
15070
15071        /** UID of application requesting the install */
15072        final int installerUid;
15073
15074        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15075            this.originatingUri = originatingUri;
15076            this.referrer = referrer;
15077            this.originatingUid = originatingUid;
15078            this.installerUid = installerUid;
15079        }
15080    }
15081
15082    class InstallParams extends HandlerParams {
15083        final OriginInfo origin;
15084        final MoveInfo move;
15085        final IPackageInstallObserver2 observer;
15086        int installFlags;
15087        final String installerPackageName;
15088        final String volumeUuid;
15089        private InstallArgs mArgs;
15090        private int mRet;
15091        final String packageAbiOverride;
15092        final String[] grantedRuntimePermissions;
15093        final VerificationInfo verificationInfo;
15094        final PackageParser.SigningDetails signingDetails;
15095        final int installReason;
15096
15097        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15098                int installFlags, String installerPackageName, String volumeUuid,
15099                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15100                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15101            super(user);
15102            this.origin = origin;
15103            this.move = move;
15104            this.observer = observer;
15105            this.installFlags = installFlags;
15106            this.installerPackageName = installerPackageName;
15107            this.volumeUuid = volumeUuid;
15108            this.verificationInfo = verificationInfo;
15109            this.packageAbiOverride = packageAbiOverride;
15110            this.grantedRuntimePermissions = grantedPermissions;
15111            this.signingDetails = signingDetails;
15112            this.installReason = installReason;
15113        }
15114
15115        @Override
15116        public String toString() {
15117            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15118                    + " file=" + origin.file + "}";
15119        }
15120
15121        private int installLocationPolicy(PackageInfoLite pkgLite) {
15122            String packageName = pkgLite.packageName;
15123            int installLocation = pkgLite.installLocation;
15124            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15125            // reader
15126            synchronized (mPackages) {
15127                // Currently installed package which the new package is attempting to replace or
15128                // null if no such package is installed.
15129                PackageParser.Package installedPkg = mPackages.get(packageName);
15130                // Package which currently owns the data which the new package will own if installed.
15131                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15132                // will be null whereas dataOwnerPkg will contain information about the package
15133                // which was uninstalled while keeping its data.
15134                PackageParser.Package dataOwnerPkg = installedPkg;
15135                if (dataOwnerPkg  == null) {
15136                    PackageSetting ps = mSettings.mPackages.get(packageName);
15137                    if (ps != null) {
15138                        dataOwnerPkg = ps.pkg;
15139                    }
15140                }
15141
15142                if (dataOwnerPkg != null) {
15143                    // If installed, the package will get access to data left on the device by its
15144                    // predecessor. As a security measure, this is permited only if this is not a
15145                    // version downgrade or if the predecessor package is marked as debuggable and
15146                    // a downgrade is explicitly requested.
15147                    //
15148                    // On debuggable platform builds, downgrades are permitted even for
15149                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15150                    // not offer security guarantees and thus it's OK to disable some security
15151                    // mechanisms to make debugging/testing easier on those builds. However, even on
15152                    // debuggable builds downgrades of packages are permitted only if requested via
15153                    // installFlags. This is because we aim to keep the behavior of debuggable
15154                    // platform builds as close as possible to the behavior of non-debuggable
15155                    // platform builds.
15156                    final boolean downgradeRequested =
15157                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15158                    final boolean packageDebuggable =
15159                                (dataOwnerPkg.applicationInfo.flags
15160                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15161                    final boolean downgradePermitted =
15162                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15163                    if (!downgradePermitted) {
15164                        try {
15165                            checkDowngrade(dataOwnerPkg, pkgLite);
15166                        } catch (PackageManagerException e) {
15167                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15168                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15169                        }
15170                    }
15171                }
15172
15173                if (installedPkg != null) {
15174                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15175                        // Check for updated system application.
15176                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15177                            if (onSd) {
15178                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15179                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15180                            }
15181                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15182                        } else {
15183                            if (onSd) {
15184                                // Install flag overrides everything.
15185                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15186                            }
15187                            // If current upgrade specifies particular preference
15188                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15189                                // Application explicitly specified internal.
15190                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15191                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15192                                // App explictly prefers external. Let policy decide
15193                            } else {
15194                                // Prefer previous location
15195                                if (isExternal(installedPkg)) {
15196                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15197                                }
15198                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15199                            }
15200                        }
15201                    } else {
15202                        // Invalid install. Return error code
15203                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15204                    }
15205                }
15206            }
15207            // All the special cases have been taken care of.
15208            // Return result based on recommended install location.
15209            if (onSd) {
15210                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15211            }
15212            return pkgLite.recommendedInstallLocation;
15213        }
15214
15215        /*
15216         * Invoke remote method to get package information and install
15217         * location values. Override install location based on default
15218         * policy if needed and then create install arguments based
15219         * on the install location.
15220         */
15221        public void handleStartCopy() throws RemoteException {
15222            int ret = PackageManager.INSTALL_SUCCEEDED;
15223
15224            // If we're already staged, we've firmly committed to an install location
15225            if (origin.staged) {
15226                if (origin.file != null) {
15227                    installFlags |= PackageManager.INSTALL_INTERNAL;
15228                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15229                } else {
15230                    throw new IllegalStateException("Invalid stage location");
15231                }
15232            }
15233
15234            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15235            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15236            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15237            PackageInfoLite pkgLite = null;
15238
15239            if (onInt && onSd) {
15240                // Check if both bits are set.
15241                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15242                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15243            } else if (onSd && ephemeral) {
15244                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15245                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15246            } else {
15247                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15248                        packageAbiOverride);
15249
15250                if (DEBUG_INSTANT && ephemeral) {
15251                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15252                }
15253
15254                /*
15255                 * If we have too little free space, try to free cache
15256                 * before giving up.
15257                 */
15258                if (!origin.staged && pkgLite.recommendedInstallLocation
15259                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15260                    // TODO: focus freeing disk space on the target device
15261                    final StorageManager storage = StorageManager.from(mContext);
15262                    final long lowThreshold = storage.getStorageLowBytes(
15263                            Environment.getDataDirectory());
15264
15265                    final long sizeBytes = mContainerService.calculateInstalledSize(
15266                            origin.resolvedPath, packageAbiOverride);
15267
15268                    try {
15269                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15270                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15271                                installFlags, packageAbiOverride);
15272                    } catch (InstallerException e) {
15273                        Slog.w(TAG, "Failed to free cache", e);
15274                    }
15275
15276                    /*
15277                     * The cache free must have deleted the file we
15278                     * downloaded to install.
15279                     *
15280                     * TODO: fix the "freeCache" call to not delete
15281                     *       the file we care about.
15282                     */
15283                    if (pkgLite.recommendedInstallLocation
15284                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15285                        pkgLite.recommendedInstallLocation
15286                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15287                    }
15288                }
15289            }
15290
15291            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15292                int loc = pkgLite.recommendedInstallLocation;
15293                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15294                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15295                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15296                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15297                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15298                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15299                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15300                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15301                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15302                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15303                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15304                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15305                } else {
15306                    // Override with defaults if needed.
15307                    loc = installLocationPolicy(pkgLite);
15308                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15309                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15310                    } else if (!onSd && !onInt) {
15311                        // Override install location with flags
15312                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15313                            // Set the flag to install on external media.
15314                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15315                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15316                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15317                            if (DEBUG_INSTANT) {
15318                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15319                            }
15320                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15321                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15322                                    |PackageManager.INSTALL_INTERNAL);
15323                        } else {
15324                            // Make sure the flag for installing on external
15325                            // media is unset
15326                            installFlags |= PackageManager.INSTALL_INTERNAL;
15327                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15328                        }
15329                    }
15330                }
15331            }
15332
15333            final InstallArgs args = createInstallArgs(this);
15334            mArgs = args;
15335
15336            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15337                // TODO: http://b/22976637
15338                // Apps installed for "all" users use the device owner to verify the app
15339                UserHandle verifierUser = getUser();
15340                if (verifierUser == UserHandle.ALL) {
15341                    verifierUser = UserHandle.SYSTEM;
15342                }
15343
15344                /*
15345                 * Determine if we have any installed package verifiers. If we
15346                 * do, then we'll defer to them to verify the packages.
15347                 */
15348                final int requiredUid = mRequiredVerifierPackage == null ? -1
15349                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15350                                verifierUser.getIdentifier());
15351                final int installerUid =
15352                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15353                if (!origin.existing && requiredUid != -1
15354                        && isVerificationEnabled(
15355                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15356                    final Intent verification = new Intent(
15357                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15358                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15359                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15360                            PACKAGE_MIME_TYPE);
15361                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15362
15363                    // Query all live verifiers based on current user state
15364                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15365                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15366                            false /*allowDynamicSplits*/);
15367
15368                    if (DEBUG_VERIFY) {
15369                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15370                                + verification.toString() + " with " + pkgLite.verifiers.length
15371                                + " optional verifiers");
15372                    }
15373
15374                    final int verificationId = mPendingVerificationToken++;
15375
15376                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15377
15378                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15379                            installerPackageName);
15380
15381                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15382                            installFlags);
15383
15384                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15385                            pkgLite.packageName);
15386
15387                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15388                            pkgLite.versionCode);
15389
15390                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15391                            pkgLite.getLongVersionCode());
15392
15393                    if (verificationInfo != null) {
15394                        if (verificationInfo.originatingUri != null) {
15395                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15396                                    verificationInfo.originatingUri);
15397                        }
15398                        if (verificationInfo.referrer != null) {
15399                            verification.putExtra(Intent.EXTRA_REFERRER,
15400                                    verificationInfo.referrer);
15401                        }
15402                        if (verificationInfo.originatingUid >= 0) {
15403                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15404                                    verificationInfo.originatingUid);
15405                        }
15406                        if (verificationInfo.installerUid >= 0) {
15407                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15408                                    verificationInfo.installerUid);
15409                        }
15410                    }
15411
15412                    final PackageVerificationState verificationState = new PackageVerificationState(
15413                            requiredUid, args);
15414
15415                    mPendingVerification.append(verificationId, verificationState);
15416
15417                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15418                            receivers, verificationState);
15419
15420                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15421                    final long idleDuration = getVerificationTimeout();
15422
15423                    /*
15424                     * If any sufficient verifiers were listed in the package
15425                     * manifest, attempt to ask them.
15426                     */
15427                    if (sufficientVerifiers != null) {
15428                        final int N = sufficientVerifiers.size();
15429                        if (N == 0) {
15430                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15431                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15432                        } else {
15433                            for (int i = 0; i < N; i++) {
15434                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15435                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15436                                        verifierComponent.getPackageName(), idleDuration,
15437                                        verifierUser.getIdentifier(), false, "package verifier");
15438
15439                                final Intent sufficientIntent = new Intent(verification);
15440                                sufficientIntent.setComponent(verifierComponent);
15441                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15442                            }
15443                        }
15444                    }
15445
15446                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15447                            mRequiredVerifierPackage, receivers);
15448                    if (ret == PackageManager.INSTALL_SUCCEEDED
15449                            && mRequiredVerifierPackage != null) {
15450                        Trace.asyncTraceBegin(
15451                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15452                        /*
15453                         * Send the intent to the required verification agent,
15454                         * but only start the verification timeout after the
15455                         * target BroadcastReceivers have run.
15456                         */
15457                        verification.setComponent(requiredVerifierComponent);
15458                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15459                                mRequiredVerifierPackage, idleDuration,
15460                                verifierUser.getIdentifier(), false, "package verifier");
15461                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15462                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15463                                new BroadcastReceiver() {
15464                                    @Override
15465                                    public void onReceive(Context context, Intent intent) {
15466                                        final Message msg = mHandler
15467                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15468                                        msg.arg1 = verificationId;
15469                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15470                                    }
15471                                }, null, 0, null, null);
15472
15473                        /*
15474                         * We don't want the copy to proceed until verification
15475                         * succeeds, so null out this field.
15476                         */
15477                        mArgs = null;
15478                    }
15479                } else {
15480                    /*
15481                     * No package verification is enabled, so immediately start
15482                     * the remote call to initiate copy using temporary file.
15483                     */
15484                    ret = args.copyApk(mContainerService, true);
15485                }
15486            }
15487
15488            mRet = ret;
15489        }
15490
15491        @Override
15492        void handleReturnCode() {
15493            // If mArgs is null, then MCS couldn't be reached. When it
15494            // reconnects, it will try again to install. At that point, this
15495            // will succeed.
15496            if (mArgs != null) {
15497                processPendingInstall(mArgs, mRet);
15498            }
15499        }
15500
15501        @Override
15502        void handleServiceError() {
15503            mArgs = createInstallArgs(this);
15504            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15505        }
15506    }
15507
15508    private InstallArgs createInstallArgs(InstallParams params) {
15509        if (params.move != null) {
15510            return new MoveInstallArgs(params);
15511        } else {
15512            return new FileInstallArgs(params);
15513        }
15514    }
15515
15516    /**
15517     * Create args that describe an existing installed package. Typically used
15518     * when cleaning up old installs, or used as a move source.
15519     */
15520    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15521            String resourcePath, String[] instructionSets) {
15522        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15523    }
15524
15525    static abstract class InstallArgs {
15526        /** @see InstallParams#origin */
15527        final OriginInfo origin;
15528        /** @see InstallParams#move */
15529        final MoveInfo move;
15530
15531        final IPackageInstallObserver2 observer;
15532        // Always refers to PackageManager flags only
15533        final int installFlags;
15534        final String installerPackageName;
15535        final String volumeUuid;
15536        final UserHandle user;
15537        final String abiOverride;
15538        final String[] installGrantPermissions;
15539        /** If non-null, drop an async trace when the install completes */
15540        final String traceMethod;
15541        final int traceCookie;
15542        final PackageParser.SigningDetails signingDetails;
15543        final int installReason;
15544
15545        // The list of instruction sets supported by this app. This is currently
15546        // only used during the rmdex() phase to clean up resources. We can get rid of this
15547        // if we move dex files under the common app path.
15548        /* nullable */ String[] instructionSets;
15549
15550        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15551                int installFlags, String installerPackageName, String volumeUuid,
15552                UserHandle user, String[] instructionSets,
15553                String abiOverride, String[] installGrantPermissions,
15554                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15555                int installReason) {
15556            this.origin = origin;
15557            this.move = move;
15558            this.installFlags = installFlags;
15559            this.observer = observer;
15560            this.installerPackageName = installerPackageName;
15561            this.volumeUuid = volumeUuid;
15562            this.user = user;
15563            this.instructionSets = instructionSets;
15564            this.abiOverride = abiOverride;
15565            this.installGrantPermissions = installGrantPermissions;
15566            this.traceMethod = traceMethod;
15567            this.traceCookie = traceCookie;
15568            this.signingDetails = signingDetails;
15569            this.installReason = installReason;
15570        }
15571
15572        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15573        abstract int doPreInstall(int status);
15574
15575        /**
15576         * Rename package into final resting place. All paths on the given
15577         * scanned package should be updated to reflect the rename.
15578         */
15579        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15580        abstract int doPostInstall(int status, int uid);
15581
15582        /** @see PackageSettingBase#codePathString */
15583        abstract String getCodePath();
15584        /** @see PackageSettingBase#resourcePathString */
15585        abstract String getResourcePath();
15586
15587        // Need installer lock especially for dex file removal.
15588        abstract void cleanUpResourcesLI();
15589        abstract boolean doPostDeleteLI(boolean delete);
15590
15591        /**
15592         * Called before the source arguments are copied. This is used mostly
15593         * for MoveParams when it needs to read the source file to put it in the
15594         * destination.
15595         */
15596        int doPreCopy() {
15597            return PackageManager.INSTALL_SUCCEEDED;
15598        }
15599
15600        /**
15601         * Called after the source arguments are copied. This is used mostly for
15602         * MoveParams when it needs to read the source file to put it in the
15603         * destination.
15604         */
15605        int doPostCopy(int uid) {
15606            return PackageManager.INSTALL_SUCCEEDED;
15607        }
15608
15609        protected boolean isFwdLocked() {
15610            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15611        }
15612
15613        protected boolean isExternalAsec() {
15614            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15615        }
15616
15617        protected boolean isEphemeral() {
15618            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15619        }
15620
15621        UserHandle getUser() {
15622            return user;
15623        }
15624    }
15625
15626    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15627        if (!allCodePaths.isEmpty()) {
15628            if (instructionSets == null) {
15629                throw new IllegalStateException("instructionSet == null");
15630            }
15631            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15632            for (String codePath : allCodePaths) {
15633                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15634                    try {
15635                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15636                    } catch (InstallerException ignored) {
15637                    }
15638                }
15639            }
15640        }
15641    }
15642
15643    /**
15644     * Logic to handle installation of non-ASEC applications, including copying
15645     * and renaming logic.
15646     */
15647    class FileInstallArgs extends InstallArgs {
15648        private File codeFile;
15649        private File resourceFile;
15650
15651        // Example topology:
15652        // /data/app/com.example/base.apk
15653        // /data/app/com.example/split_foo.apk
15654        // /data/app/com.example/lib/arm/libfoo.so
15655        // /data/app/com.example/lib/arm64/libfoo.so
15656        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15657
15658        /** New install */
15659        FileInstallArgs(InstallParams params) {
15660            super(params.origin, params.move, params.observer, params.installFlags,
15661                    params.installerPackageName, params.volumeUuid,
15662                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15663                    params.grantedRuntimePermissions,
15664                    params.traceMethod, params.traceCookie, params.signingDetails,
15665                    params.installReason);
15666            if (isFwdLocked()) {
15667                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15668            }
15669        }
15670
15671        /** Existing install */
15672        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15673            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15674                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15675                    PackageManager.INSTALL_REASON_UNKNOWN);
15676            this.codeFile = (codePath != null) ? new File(codePath) : null;
15677            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15678        }
15679
15680        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15681            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15682            try {
15683                return doCopyApk(imcs, temp);
15684            } finally {
15685                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15686            }
15687        }
15688
15689        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15690            if (origin.staged) {
15691                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15692                codeFile = origin.file;
15693                resourceFile = origin.file;
15694                return PackageManager.INSTALL_SUCCEEDED;
15695            }
15696
15697            try {
15698                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15699                final File tempDir =
15700                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15701                codeFile = tempDir;
15702                resourceFile = tempDir;
15703            } catch (IOException e) {
15704                Slog.w(TAG, "Failed to create copy file: " + e);
15705                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15706            }
15707
15708            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15709                @Override
15710                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15711                    if (!FileUtils.isValidExtFilename(name)) {
15712                        throw new IllegalArgumentException("Invalid filename: " + name);
15713                    }
15714                    try {
15715                        final File file = new File(codeFile, name);
15716                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15717                                O_RDWR | O_CREAT, 0644);
15718                        Os.chmod(file.getAbsolutePath(), 0644);
15719                        return new ParcelFileDescriptor(fd);
15720                    } catch (ErrnoException e) {
15721                        throw new RemoteException("Failed to open: " + e.getMessage());
15722                    }
15723                }
15724            };
15725
15726            int ret = PackageManager.INSTALL_SUCCEEDED;
15727            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15728            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15729                Slog.e(TAG, "Failed to copy package");
15730                return ret;
15731            }
15732
15733            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15734            NativeLibraryHelper.Handle handle = null;
15735            try {
15736                handle = NativeLibraryHelper.Handle.create(codeFile);
15737                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15738                        abiOverride);
15739            } catch (IOException e) {
15740                Slog.e(TAG, "Copying native libraries failed", e);
15741                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15742            } finally {
15743                IoUtils.closeQuietly(handle);
15744            }
15745
15746            return ret;
15747        }
15748
15749        int doPreInstall(int status) {
15750            if (status != PackageManager.INSTALL_SUCCEEDED) {
15751                cleanUp();
15752            }
15753            return status;
15754        }
15755
15756        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15757            if (status != PackageManager.INSTALL_SUCCEEDED) {
15758                cleanUp();
15759                return false;
15760            }
15761
15762            final File targetDir = codeFile.getParentFile();
15763            final File beforeCodeFile = codeFile;
15764            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15765
15766            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15767            try {
15768                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15769            } catch (ErrnoException e) {
15770                Slog.w(TAG, "Failed to rename", e);
15771                return false;
15772            }
15773
15774            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15775                Slog.w(TAG, "Failed to restorecon");
15776                return false;
15777            }
15778
15779            // Reflect the rename internally
15780            codeFile = afterCodeFile;
15781            resourceFile = afterCodeFile;
15782
15783            // Reflect the rename in scanned details
15784            try {
15785                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15786            } catch (IOException e) {
15787                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15788                return false;
15789            }
15790            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15791                    afterCodeFile, pkg.baseCodePath));
15792            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15793                    afterCodeFile, pkg.splitCodePaths));
15794
15795            // Reflect the rename in app info
15796            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15797            pkg.setApplicationInfoCodePath(pkg.codePath);
15798            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15799            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15800            pkg.setApplicationInfoResourcePath(pkg.codePath);
15801            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15802            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15803
15804            return true;
15805        }
15806
15807        int doPostInstall(int status, int uid) {
15808            if (status != PackageManager.INSTALL_SUCCEEDED) {
15809                cleanUp();
15810            }
15811            return status;
15812        }
15813
15814        @Override
15815        String getCodePath() {
15816            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15817        }
15818
15819        @Override
15820        String getResourcePath() {
15821            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15822        }
15823
15824        private boolean cleanUp() {
15825            if (codeFile == null || !codeFile.exists()) {
15826                return false;
15827            }
15828
15829            removeCodePathLI(codeFile);
15830
15831            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15832                resourceFile.delete();
15833            }
15834
15835            return true;
15836        }
15837
15838        void cleanUpResourcesLI() {
15839            // Try enumerating all code paths before deleting
15840            List<String> allCodePaths = Collections.EMPTY_LIST;
15841            if (codeFile != null && codeFile.exists()) {
15842                try {
15843                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15844                    allCodePaths = pkg.getAllCodePaths();
15845                } catch (PackageParserException e) {
15846                    // Ignored; we tried our best
15847                }
15848            }
15849
15850            cleanUp();
15851            removeDexFiles(allCodePaths, instructionSets);
15852        }
15853
15854        boolean doPostDeleteLI(boolean delete) {
15855            // XXX err, shouldn't we respect the delete flag?
15856            cleanUpResourcesLI();
15857            return true;
15858        }
15859    }
15860
15861    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15862            PackageManagerException {
15863        if (copyRet < 0) {
15864            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15865                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15866                throw new PackageManagerException(copyRet, message);
15867            }
15868        }
15869    }
15870
15871    /**
15872     * Extract the StorageManagerService "container ID" from the full code path of an
15873     * .apk.
15874     */
15875    static String cidFromCodePath(String fullCodePath) {
15876        int eidx = fullCodePath.lastIndexOf("/");
15877        String subStr1 = fullCodePath.substring(0, eidx);
15878        int sidx = subStr1.lastIndexOf("/");
15879        return subStr1.substring(sidx+1, eidx);
15880    }
15881
15882    /**
15883     * Logic to handle movement of existing installed applications.
15884     */
15885    class MoveInstallArgs extends InstallArgs {
15886        private File codeFile;
15887        private File resourceFile;
15888
15889        /** New install */
15890        MoveInstallArgs(InstallParams params) {
15891            super(params.origin, params.move, params.observer, params.installFlags,
15892                    params.installerPackageName, params.volumeUuid,
15893                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15894                    params.grantedRuntimePermissions,
15895                    params.traceMethod, params.traceCookie, params.signingDetails,
15896                    params.installReason);
15897        }
15898
15899        int copyApk(IMediaContainerService imcs, boolean temp) {
15900            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15901                    + move.fromUuid + " to " + move.toUuid);
15902            synchronized (mInstaller) {
15903                try {
15904                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15905                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15906                } catch (InstallerException e) {
15907                    Slog.w(TAG, "Failed to move app", e);
15908                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15909                }
15910            }
15911
15912            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15913            resourceFile = codeFile;
15914            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15915
15916            return PackageManager.INSTALL_SUCCEEDED;
15917        }
15918
15919        int doPreInstall(int status) {
15920            if (status != PackageManager.INSTALL_SUCCEEDED) {
15921                cleanUp(move.toUuid);
15922            }
15923            return status;
15924        }
15925
15926        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15927            if (status != PackageManager.INSTALL_SUCCEEDED) {
15928                cleanUp(move.toUuid);
15929                return false;
15930            }
15931
15932            // Reflect the move in app info
15933            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15934            pkg.setApplicationInfoCodePath(pkg.codePath);
15935            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15936            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15937            pkg.setApplicationInfoResourcePath(pkg.codePath);
15938            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15939            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15940
15941            return true;
15942        }
15943
15944        int doPostInstall(int status, int uid) {
15945            if (status == PackageManager.INSTALL_SUCCEEDED) {
15946                cleanUp(move.fromUuid);
15947            } else {
15948                cleanUp(move.toUuid);
15949            }
15950            return status;
15951        }
15952
15953        @Override
15954        String getCodePath() {
15955            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15956        }
15957
15958        @Override
15959        String getResourcePath() {
15960            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15961        }
15962
15963        private boolean cleanUp(String volumeUuid) {
15964            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15965                    move.dataAppName);
15966            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15967            final int[] userIds = sUserManager.getUserIds();
15968            synchronized (mInstallLock) {
15969                // Clean up both app data and code
15970                // All package moves are frozen until finished
15971                for (int userId : userIds) {
15972                    try {
15973                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15974                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15975                    } catch (InstallerException e) {
15976                        Slog.w(TAG, String.valueOf(e));
15977                    }
15978                }
15979                removeCodePathLI(codeFile);
15980            }
15981            return true;
15982        }
15983
15984        void cleanUpResourcesLI() {
15985            throw new UnsupportedOperationException();
15986        }
15987
15988        boolean doPostDeleteLI(boolean delete) {
15989            throw new UnsupportedOperationException();
15990        }
15991    }
15992
15993    static String getAsecPackageName(String packageCid) {
15994        int idx = packageCid.lastIndexOf("-");
15995        if (idx == -1) {
15996            return packageCid;
15997        }
15998        return packageCid.substring(0, idx);
15999    }
16000
16001    // Utility method used to create code paths based on package name and available index.
16002    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16003        String idxStr = "";
16004        int idx = 1;
16005        // Fall back to default value of idx=1 if prefix is not
16006        // part of oldCodePath
16007        if (oldCodePath != null) {
16008            String subStr = oldCodePath;
16009            // Drop the suffix right away
16010            if (suffix != null && subStr.endsWith(suffix)) {
16011                subStr = subStr.substring(0, subStr.length() - suffix.length());
16012            }
16013            // If oldCodePath already contains prefix find out the
16014            // ending index to either increment or decrement.
16015            int sidx = subStr.lastIndexOf(prefix);
16016            if (sidx != -1) {
16017                subStr = subStr.substring(sidx + prefix.length());
16018                if (subStr != null) {
16019                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16020                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16021                    }
16022                    try {
16023                        idx = Integer.parseInt(subStr);
16024                        if (idx <= 1) {
16025                            idx++;
16026                        } else {
16027                            idx--;
16028                        }
16029                    } catch(NumberFormatException e) {
16030                    }
16031                }
16032            }
16033        }
16034        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16035        return prefix + idxStr;
16036    }
16037
16038    private File getNextCodePath(File targetDir, String packageName) {
16039        File result;
16040        SecureRandom random = new SecureRandom();
16041        byte[] bytes = new byte[16];
16042        do {
16043            random.nextBytes(bytes);
16044            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16045            result = new File(targetDir, packageName + "-" + suffix);
16046        } while (result.exists());
16047        return result;
16048    }
16049
16050    // Utility method that returns the relative package path with respect
16051    // to the installation directory. Like say for /data/data/com.test-1.apk
16052    // string com.test-1 is returned.
16053    static String deriveCodePathName(String codePath) {
16054        if (codePath == null) {
16055            return null;
16056        }
16057        final File codeFile = new File(codePath);
16058        final String name = codeFile.getName();
16059        if (codeFile.isDirectory()) {
16060            return name;
16061        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16062            final int lastDot = name.lastIndexOf('.');
16063            return name.substring(0, lastDot);
16064        } else {
16065            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16066            return null;
16067        }
16068    }
16069
16070    static class PackageInstalledInfo {
16071        String name;
16072        int uid;
16073        // The set of users that originally had this package installed.
16074        int[] origUsers;
16075        // The set of users that now have this package installed.
16076        int[] newUsers;
16077        PackageParser.Package pkg;
16078        int returnCode;
16079        String returnMsg;
16080        String installerPackageName;
16081        PackageRemovedInfo removedInfo;
16082        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16083
16084        public void setError(int code, String msg) {
16085            setReturnCode(code);
16086            setReturnMessage(msg);
16087            Slog.w(TAG, msg);
16088        }
16089
16090        public void setError(String msg, PackageParserException e) {
16091            setReturnCode(e.error);
16092            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16093            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16094            for (int i = 0; i < childCount; i++) {
16095                addedChildPackages.valueAt(i).setError(msg, e);
16096            }
16097            Slog.w(TAG, msg, e);
16098        }
16099
16100        public void setError(String msg, PackageManagerException e) {
16101            returnCode = e.error;
16102            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16103            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16104            for (int i = 0; i < childCount; i++) {
16105                addedChildPackages.valueAt(i).setError(msg, e);
16106            }
16107            Slog.w(TAG, msg, e);
16108        }
16109
16110        public void setReturnCode(int returnCode) {
16111            this.returnCode = returnCode;
16112            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16113            for (int i = 0; i < childCount; i++) {
16114                addedChildPackages.valueAt(i).returnCode = returnCode;
16115            }
16116        }
16117
16118        private void setReturnMessage(String returnMsg) {
16119            this.returnMsg = returnMsg;
16120            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16121            for (int i = 0; i < childCount; i++) {
16122                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16123            }
16124        }
16125
16126        // In some error cases we want to convey more info back to the observer
16127        String origPackage;
16128        String origPermission;
16129    }
16130
16131    /*
16132     * Install a non-existing package.
16133     */
16134    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16135            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16136            String volumeUuid, PackageInstalledInfo res, int installReason) {
16137        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16138
16139        // Remember this for later, in case we need to rollback this install
16140        String pkgName = pkg.packageName;
16141
16142        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16143
16144        synchronized(mPackages) {
16145            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16146            if (renamedPackage != null) {
16147                // A package with the same name is already installed, though
16148                // it has been renamed to an older name.  The package we
16149                // are trying to install should be installed as an update to
16150                // the existing one, but that has not been requested, so bail.
16151                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16152                        + " without first uninstalling package running as "
16153                        + renamedPackage);
16154                return;
16155            }
16156            if (mPackages.containsKey(pkgName)) {
16157                // Don't allow installation over an existing package with the same name.
16158                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16159                        + " without first uninstalling.");
16160                return;
16161            }
16162        }
16163
16164        try {
16165            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16166                    System.currentTimeMillis(), user);
16167
16168            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16169
16170            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16171                prepareAppDataAfterInstallLIF(newPackage);
16172
16173            } else {
16174                // Remove package from internal structures, but keep around any
16175                // data that might have already existed
16176                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16177                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16178            }
16179        } catch (PackageManagerException e) {
16180            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16181        }
16182
16183        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16184    }
16185
16186    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16187        try (DigestInputStream digestStream =
16188                new DigestInputStream(new FileInputStream(file), digest)) {
16189            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16190        }
16191    }
16192
16193    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16194            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16195            PackageInstalledInfo res, int installReason) {
16196        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16197
16198        final PackageParser.Package oldPackage;
16199        final PackageSetting ps;
16200        final String pkgName = pkg.packageName;
16201        final int[] allUsers;
16202        final int[] installedUsers;
16203
16204        synchronized(mPackages) {
16205            oldPackage = mPackages.get(pkgName);
16206            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16207
16208            // don't allow upgrade to target a release SDK from a pre-release SDK
16209            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16210                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16211            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16212                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16213            if (oldTargetsPreRelease
16214                    && !newTargetsPreRelease
16215                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16216                Slog.w(TAG, "Can't install package targeting released sdk");
16217                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16218                return;
16219            }
16220
16221            ps = mSettings.mPackages.get(pkgName);
16222
16223            // verify signatures are valid
16224            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16225            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16226                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16227                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16228                            "New package not signed by keys specified by upgrade-keysets: "
16229                                    + pkgName);
16230                    return;
16231                }
16232            } else {
16233
16234                // default to original signature matching
16235                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16236                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16237                                && !oldPackage.mSigningDetails.checkCapability(
16238                                        pkg.mSigningDetails,
16239                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16240                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16241                            "New package has a different signature: " + pkgName);
16242                    return;
16243                }
16244            }
16245
16246            // don't allow a system upgrade unless the upgrade hash matches
16247            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16248                byte[] digestBytes = null;
16249                try {
16250                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16251                    updateDigest(digest, new File(pkg.baseCodePath));
16252                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16253                        for (String path : pkg.splitCodePaths) {
16254                            updateDigest(digest, new File(path));
16255                        }
16256                    }
16257                    digestBytes = digest.digest();
16258                } catch (NoSuchAlgorithmException | IOException e) {
16259                    res.setError(INSTALL_FAILED_INVALID_APK,
16260                            "Could not compute hash: " + pkgName);
16261                    return;
16262                }
16263                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16264                    res.setError(INSTALL_FAILED_INVALID_APK,
16265                            "New package fails restrict-update check: " + pkgName);
16266                    return;
16267                }
16268                // retain upgrade restriction
16269                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16270            }
16271
16272            // Check for shared user id changes
16273            String invalidPackageName =
16274                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16275            if (invalidPackageName != null) {
16276                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16277                        "Package " + invalidPackageName + " tried to change user "
16278                                + oldPackage.mSharedUserId);
16279                return;
16280            }
16281
16282            // check if the new package supports all of the abis which the old package supports
16283            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16284            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16285            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16286                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16287                        "Update to package " + pkgName + " doesn't support multi arch");
16288                return;
16289            }
16290
16291            // In case of rollback, remember per-user/profile install state
16292            allUsers = sUserManager.getUserIds();
16293            installedUsers = ps.queryInstalledUsers(allUsers, true);
16294
16295            // don't allow an upgrade from full to ephemeral
16296            if (isInstantApp) {
16297                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16298                    for (int currentUser : allUsers) {
16299                        if (!ps.getInstantApp(currentUser)) {
16300                            // can't downgrade from full to instant
16301                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16302                                    + " for user: " + currentUser);
16303                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16304                            return;
16305                        }
16306                    }
16307                } else if (!ps.getInstantApp(user.getIdentifier())) {
16308                    // can't downgrade from full to instant
16309                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16310                            + " for user: " + user.getIdentifier());
16311                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16312                    return;
16313                }
16314            }
16315        }
16316
16317        // Update what is removed
16318        res.removedInfo = new PackageRemovedInfo(this);
16319        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16320        res.removedInfo.removedPackage = oldPackage.packageName;
16321        res.removedInfo.installerPackageName = ps.installerPackageName;
16322        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16323        res.removedInfo.isUpdate = true;
16324        res.removedInfo.origUsers = installedUsers;
16325        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16326        for (int i = 0; i < installedUsers.length; i++) {
16327            final int userId = installedUsers[i];
16328            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16329        }
16330
16331        final int childCount = (oldPackage.childPackages != null)
16332                ? oldPackage.childPackages.size() : 0;
16333        for (int i = 0; i < childCount; i++) {
16334            boolean childPackageUpdated = false;
16335            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16336            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16337            if (res.addedChildPackages != null) {
16338                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16339                if (childRes != null) {
16340                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16341                    childRes.removedInfo.removedPackage = childPkg.packageName;
16342                    if (childPs != null) {
16343                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16344                    }
16345                    childRes.removedInfo.isUpdate = true;
16346                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16347                    childPackageUpdated = true;
16348                }
16349            }
16350            if (!childPackageUpdated) {
16351                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16352                childRemovedRes.removedPackage = childPkg.packageName;
16353                if (childPs != null) {
16354                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16355                }
16356                childRemovedRes.isUpdate = false;
16357                childRemovedRes.dataRemoved = true;
16358                synchronized (mPackages) {
16359                    if (childPs != null) {
16360                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16361                    }
16362                }
16363                if (res.removedInfo.removedChildPackages == null) {
16364                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16365                }
16366                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16367            }
16368        }
16369
16370        boolean sysPkg = (isSystemApp(oldPackage));
16371        if (sysPkg) {
16372            // Set the system/privileged/oem/vendor/product flags as needed
16373            final boolean privileged =
16374                    (oldPackage.applicationInfo.privateFlags
16375                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16376            final boolean oem =
16377                    (oldPackage.applicationInfo.privateFlags
16378                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16379            final boolean vendor =
16380                    (oldPackage.applicationInfo.privateFlags
16381                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16382            final boolean product =
16383                    (oldPackage.applicationInfo.privateFlags
16384                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16385            final @ParseFlags int systemParseFlags = parseFlags;
16386            final @ScanFlags int systemScanFlags = scanFlags
16387                    | SCAN_AS_SYSTEM
16388                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16389                    | (oem ? SCAN_AS_OEM : 0)
16390                    | (vendor ? SCAN_AS_VENDOR : 0)
16391                    | (product ? SCAN_AS_PRODUCT : 0);
16392
16393            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16394                    user, allUsers, installerPackageName, res, installReason);
16395        } else {
16396            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16397                    user, allUsers, installerPackageName, res, installReason);
16398        }
16399    }
16400
16401    @Override
16402    public List<String> getPreviousCodePaths(String packageName) {
16403        final int callingUid = Binder.getCallingUid();
16404        final List<String> result = new ArrayList<>();
16405        if (getInstantAppPackageName(callingUid) != null) {
16406            return result;
16407        }
16408        final PackageSetting ps = mSettings.mPackages.get(packageName);
16409        if (ps != null
16410                && ps.oldCodePaths != null
16411                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16412            result.addAll(ps.oldCodePaths);
16413        }
16414        return result;
16415    }
16416
16417    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16418            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16419            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16420            String installerPackageName, PackageInstalledInfo res, int installReason) {
16421        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16422                + deletedPackage);
16423
16424        String pkgName = deletedPackage.packageName;
16425        boolean deletedPkg = true;
16426        boolean addedPkg = false;
16427        boolean updatedSettings = false;
16428        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16429        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16430                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16431
16432        final long origUpdateTime = (pkg.mExtras != null)
16433                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16434
16435        // First delete the existing package while retaining the data directory
16436        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16437                res.removedInfo, true, pkg)) {
16438            // If the existing package wasn't successfully deleted
16439            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16440            deletedPkg = false;
16441        } else {
16442            // Successfully deleted the old package; proceed with replace.
16443
16444            // If deleted package lived in a container, give users a chance to
16445            // relinquish resources before killing.
16446            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16447                if (DEBUG_INSTALL) {
16448                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16449                }
16450                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16451                final ArrayList<String> pkgList = new ArrayList<String>(1);
16452                pkgList.add(deletedPackage.applicationInfo.packageName);
16453                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16454            }
16455
16456            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16457                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16458
16459            try {
16460                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16461                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16462                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16463                        installReason);
16464
16465                // Update the in-memory copy of the previous code paths.
16466                PackageSetting ps = mSettings.mPackages.get(pkgName);
16467                if (!killApp) {
16468                    if (ps.oldCodePaths == null) {
16469                        ps.oldCodePaths = new ArraySet<>();
16470                    }
16471                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16472                    if (deletedPackage.splitCodePaths != null) {
16473                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16474                    }
16475                } else {
16476                    ps.oldCodePaths = null;
16477                }
16478                if (ps.childPackageNames != null) {
16479                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16480                        final String childPkgName = ps.childPackageNames.get(i);
16481                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16482                        childPs.oldCodePaths = ps.oldCodePaths;
16483                    }
16484                }
16485                prepareAppDataAfterInstallLIF(newPackage);
16486                addedPkg = true;
16487                mDexManager.notifyPackageUpdated(newPackage.packageName,
16488                        newPackage.baseCodePath, newPackage.splitCodePaths);
16489            } catch (PackageManagerException e) {
16490                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16491            }
16492        }
16493
16494        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16495            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16496
16497            // Revert all internal state mutations and added folders for the failed install
16498            if (addedPkg) {
16499                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16500                        res.removedInfo, true, null);
16501            }
16502
16503            // Restore the old package
16504            if (deletedPkg) {
16505                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16506                File restoreFile = new File(deletedPackage.codePath);
16507                // Parse old package
16508                boolean oldExternal = isExternal(deletedPackage);
16509                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16510                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16511                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16512                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16513                try {
16514                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16515                            null);
16516                } catch (PackageManagerException e) {
16517                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16518                            + e.getMessage());
16519                    return;
16520                }
16521
16522                synchronized (mPackages) {
16523                    // Ensure the installer package name up to date
16524                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16525
16526                    // Update permissions for restored package
16527                    mPermissionManager.updatePermissions(
16528                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16529                            mPermissionCallback);
16530
16531                    mSettings.writeLPr();
16532                }
16533
16534                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16535            }
16536        } else {
16537            synchronized (mPackages) {
16538                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16539                if (ps != null) {
16540                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16541                    if (res.removedInfo.removedChildPackages != null) {
16542                        final int childCount = res.removedInfo.removedChildPackages.size();
16543                        // Iterate in reverse as we may modify the collection
16544                        for (int i = childCount - 1; i >= 0; i--) {
16545                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16546                            if (res.addedChildPackages.containsKey(childPackageName)) {
16547                                res.removedInfo.removedChildPackages.removeAt(i);
16548                            } else {
16549                                PackageRemovedInfo childInfo = res.removedInfo
16550                                        .removedChildPackages.valueAt(i);
16551                                childInfo.removedForAllUsers = mPackages.get(
16552                                        childInfo.removedPackage) == null;
16553                            }
16554                        }
16555                    }
16556                }
16557            }
16558        }
16559    }
16560
16561    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16562            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16563            final @ScanFlags int scanFlags, UserHandle user,
16564            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16565            int installReason) {
16566        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16567                + ", old=" + deletedPackage);
16568
16569        final boolean disabledSystem;
16570
16571        // Remove existing system package
16572        removePackageLI(deletedPackage, true);
16573
16574        synchronized (mPackages) {
16575            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16576        }
16577        if (!disabledSystem) {
16578            // We didn't need to disable the .apk as a current system package,
16579            // which means we are replacing another update that is already
16580            // installed.  We need to make sure to delete the older one's .apk.
16581            res.removedInfo.args = createInstallArgsForExisting(0,
16582                    deletedPackage.applicationInfo.getCodePath(),
16583                    deletedPackage.applicationInfo.getResourcePath(),
16584                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16585        } else {
16586            res.removedInfo.args = null;
16587        }
16588
16589        // Successfully disabled the old package. Now proceed with re-installation
16590        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16591                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16592
16593        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16594        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16595                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16596
16597        PackageParser.Package newPackage = null;
16598        try {
16599            // Add the package to the internal data structures
16600            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16601
16602            // Set the update and install times
16603            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16604            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16605                    System.currentTimeMillis());
16606
16607            // Update the package dynamic state if succeeded
16608            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16609                // Now that the install succeeded make sure we remove data
16610                // directories for any child package the update removed.
16611                final int deletedChildCount = (deletedPackage.childPackages != null)
16612                        ? deletedPackage.childPackages.size() : 0;
16613                final int newChildCount = (newPackage.childPackages != null)
16614                        ? newPackage.childPackages.size() : 0;
16615                for (int i = 0; i < deletedChildCount; i++) {
16616                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16617                    boolean childPackageDeleted = true;
16618                    for (int j = 0; j < newChildCount; j++) {
16619                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16620                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16621                            childPackageDeleted = false;
16622                            break;
16623                        }
16624                    }
16625                    if (childPackageDeleted) {
16626                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16627                                deletedChildPkg.packageName);
16628                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16629                            PackageRemovedInfo removedChildRes = res.removedInfo
16630                                    .removedChildPackages.get(deletedChildPkg.packageName);
16631                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16632                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16633                        }
16634                    }
16635                }
16636
16637                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16638                        installReason);
16639                prepareAppDataAfterInstallLIF(newPackage);
16640
16641                mDexManager.notifyPackageUpdated(newPackage.packageName,
16642                            newPackage.baseCodePath, newPackage.splitCodePaths);
16643            }
16644        } catch (PackageManagerException e) {
16645            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16646            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16647        }
16648
16649        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16650            // Re installation failed. Restore old information
16651            // Remove new pkg information
16652            if (newPackage != null) {
16653                removeInstalledPackageLI(newPackage, true);
16654            }
16655            // Add back the old system package
16656            try {
16657                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16658            } catch (PackageManagerException e) {
16659                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16660            }
16661
16662            synchronized (mPackages) {
16663                if (disabledSystem) {
16664                    enableSystemPackageLPw(deletedPackage);
16665                }
16666
16667                // Ensure the installer package name up to date
16668                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16669
16670                // Update permissions for restored package
16671                mPermissionManager.updatePermissions(
16672                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16673                        mPermissionCallback);
16674
16675                mSettings.writeLPr();
16676            }
16677
16678            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16679                    + " after failed upgrade");
16680        }
16681    }
16682
16683    /**
16684     * Checks whether the parent or any of the child packages have a change shared
16685     * user. For a package to be a valid update the shred users of the parent and
16686     * the children should match. We may later support changing child shared users.
16687     * @param oldPkg The updated package.
16688     * @param newPkg The update package.
16689     * @return The shared user that change between the versions.
16690     */
16691    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16692            PackageParser.Package newPkg) {
16693        // Check parent shared user
16694        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16695            return newPkg.packageName;
16696        }
16697        // Check child shared users
16698        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16699        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16700        for (int i = 0; i < newChildCount; i++) {
16701            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16702            // If this child was present, did it have the same shared user?
16703            for (int j = 0; j < oldChildCount; j++) {
16704                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16705                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16706                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16707                    return newChildPkg.packageName;
16708                }
16709            }
16710        }
16711        return null;
16712    }
16713
16714    private void removeNativeBinariesLI(PackageSetting ps) {
16715        // Remove the lib path for the parent package
16716        if (ps != null) {
16717            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16718            // Remove the lib path for the child packages
16719            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16720            for (int i = 0; i < childCount; i++) {
16721                PackageSetting childPs = null;
16722                synchronized (mPackages) {
16723                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16724                }
16725                if (childPs != null) {
16726                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16727                            .legacyNativeLibraryPathString);
16728                }
16729            }
16730        }
16731    }
16732
16733    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16734        // Enable the parent package
16735        mSettings.enableSystemPackageLPw(pkg.packageName);
16736        // Enable the child packages
16737        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16738        for (int i = 0; i < childCount; i++) {
16739            PackageParser.Package childPkg = pkg.childPackages.get(i);
16740            mSettings.enableSystemPackageLPw(childPkg.packageName);
16741        }
16742    }
16743
16744    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16745            PackageParser.Package newPkg) {
16746        // Disable the parent package (parent always replaced)
16747        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16748        // Disable the child packages
16749        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16750        for (int i = 0; i < childCount; i++) {
16751            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16752            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16753            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16754        }
16755        return disabled;
16756    }
16757
16758    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16759            String installerPackageName) {
16760        // Enable the parent package
16761        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16762        // Enable the child packages
16763        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16764        for (int i = 0; i < childCount; i++) {
16765            PackageParser.Package childPkg = pkg.childPackages.get(i);
16766            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16767        }
16768    }
16769
16770    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16771            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16772        // Update the parent package setting
16773        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16774                res, user, installReason);
16775        // Update the child packages setting
16776        final int childCount = (newPackage.childPackages != null)
16777                ? newPackage.childPackages.size() : 0;
16778        for (int i = 0; i < childCount; i++) {
16779            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16780            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16781            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16782                    childRes.origUsers, childRes, user, installReason);
16783        }
16784    }
16785
16786    private void updateSettingsInternalLI(PackageParser.Package pkg,
16787            String installerPackageName, int[] allUsers, int[] installedForUsers,
16788            PackageInstalledInfo res, UserHandle user, int installReason) {
16789        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16790
16791        final String pkgName = pkg.packageName;
16792
16793        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16794        synchronized (mPackages) {
16795// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16796            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16797                    mPermissionCallback);
16798            // For system-bundled packages, we assume that installing an upgraded version
16799            // of the package implies that the user actually wants to run that new code,
16800            // so we enable the package.
16801            PackageSetting ps = mSettings.mPackages.get(pkgName);
16802            final int userId = user.getIdentifier();
16803            if (ps != null) {
16804                if (isSystemApp(pkg)) {
16805                    if (DEBUG_INSTALL) {
16806                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16807                    }
16808                    // Enable system package for requested users
16809                    if (res.origUsers != null) {
16810                        for (int origUserId : res.origUsers) {
16811                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16812                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16813                                        origUserId, installerPackageName);
16814                            }
16815                        }
16816                    }
16817                    // Also convey the prior install/uninstall state
16818                    if (allUsers != null && installedForUsers != null) {
16819                        for (int currentUserId : allUsers) {
16820                            final boolean installed = ArrayUtils.contains(
16821                                    installedForUsers, currentUserId);
16822                            if (DEBUG_INSTALL) {
16823                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16824                            }
16825                            ps.setInstalled(installed, currentUserId);
16826                        }
16827                        // these install state changes will be persisted in the
16828                        // upcoming call to mSettings.writeLPr().
16829                    }
16830                }
16831                // It's implied that when a user requests installation, they want the app to be
16832                // installed and enabled.
16833                if (userId != UserHandle.USER_ALL) {
16834                    ps.setInstalled(true, userId);
16835                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16836                }
16837
16838                // When replacing an existing package, preserve the original install reason for all
16839                // users that had the package installed before.
16840                final Set<Integer> previousUserIds = new ArraySet<>();
16841                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16842                    final int installReasonCount = res.removedInfo.installReasons.size();
16843                    for (int i = 0; i < installReasonCount; i++) {
16844                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16845                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16846                        ps.setInstallReason(previousInstallReason, previousUserId);
16847                        previousUserIds.add(previousUserId);
16848                    }
16849                }
16850
16851                // Set install reason for users that are having the package newly installed.
16852                if (userId == UserHandle.USER_ALL) {
16853                    for (int currentUserId : sUserManager.getUserIds()) {
16854                        if (!previousUserIds.contains(currentUserId)) {
16855                            ps.setInstallReason(installReason, currentUserId);
16856                        }
16857                    }
16858                } else if (!previousUserIds.contains(userId)) {
16859                    ps.setInstallReason(installReason, userId);
16860                }
16861                mSettings.writeKernelMappingLPr(ps);
16862            }
16863            res.name = pkgName;
16864            res.uid = pkg.applicationInfo.uid;
16865            res.pkg = pkg;
16866            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16867            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16868            //to update install status
16869            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16870            mSettings.writeLPr();
16871            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16872        }
16873
16874        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16875    }
16876
16877    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16878        try {
16879            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16880            installPackageLI(args, res);
16881        } finally {
16882            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16883        }
16884    }
16885
16886    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16887        final int installFlags = args.installFlags;
16888        final String installerPackageName = args.installerPackageName;
16889        final String volumeUuid = args.volumeUuid;
16890        final File tmpPackageFile = new File(args.getCodePath());
16891        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16892        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16893                || (args.volumeUuid != null));
16894        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16895        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16896        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16897        final boolean virtualPreload =
16898                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16899        boolean replace = false;
16900        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16901        if (args.move != null) {
16902            // moving a complete application; perform an initial scan on the new install location
16903            scanFlags |= SCAN_INITIAL;
16904        }
16905        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16906            scanFlags |= SCAN_DONT_KILL_APP;
16907        }
16908        if (instantApp) {
16909            scanFlags |= SCAN_AS_INSTANT_APP;
16910        }
16911        if (fullApp) {
16912            scanFlags |= SCAN_AS_FULL_APP;
16913        }
16914        if (virtualPreload) {
16915            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16916        }
16917
16918        // Result object to be returned
16919        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16920        res.installerPackageName = installerPackageName;
16921
16922        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16923
16924        // Sanity check
16925        if (instantApp && (forwardLocked || onExternal)) {
16926            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16927                    + " external=" + onExternal);
16928            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16929            return;
16930        }
16931
16932        // Retrieve PackageSettings and parse package
16933        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16934                | PackageParser.PARSE_ENFORCE_CODE
16935                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16936                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16937                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16938        PackageParser pp = new PackageParser();
16939        pp.setSeparateProcesses(mSeparateProcesses);
16940        pp.setDisplayMetrics(mMetrics);
16941        pp.setCallback(mPackageParserCallback);
16942
16943        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16944        final PackageParser.Package pkg;
16945        try {
16946            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16947            DexMetadataHelper.validatePackageDexMetadata(pkg);
16948        } catch (PackageParserException e) {
16949            res.setError("Failed parse during installPackageLI", e);
16950            return;
16951        } finally {
16952            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16953        }
16954
16955        // Instant apps have several additional install-time checks.
16956        if (instantApp) {
16957            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16958                Slog.w(TAG,
16959                        "Instant app package " + pkg.packageName + " does not target at least O");
16960                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16961                        "Instant app package must target at least O");
16962                return;
16963            }
16964            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16965                Slog.w(TAG, "Instant app package " + pkg.packageName
16966                        + " does not target targetSandboxVersion 2");
16967                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16968                        "Instant app package must use targetSandboxVersion 2");
16969                return;
16970            }
16971            if (pkg.mSharedUserId != null) {
16972                Slog.w(TAG, "Instant app package " + pkg.packageName
16973                        + " may not declare sharedUserId.");
16974                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16975                        "Instant app package may not declare a sharedUserId");
16976                return;
16977            }
16978        }
16979
16980        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16981            // Static shared libraries have synthetic package names
16982            renameStaticSharedLibraryPackage(pkg);
16983
16984            // No static shared libs on external storage
16985            if (onExternal) {
16986                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16987                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16988                        "Packages declaring static-shared libs cannot be updated");
16989                return;
16990            }
16991        }
16992
16993        // If we are installing a clustered package add results for the children
16994        if (pkg.childPackages != null) {
16995            synchronized (mPackages) {
16996                final int childCount = pkg.childPackages.size();
16997                for (int i = 0; i < childCount; i++) {
16998                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16999                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17000                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17001                    childRes.pkg = childPkg;
17002                    childRes.name = childPkg.packageName;
17003                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17004                    if (childPs != null) {
17005                        childRes.origUsers = childPs.queryInstalledUsers(
17006                                sUserManager.getUserIds(), true);
17007                    }
17008                    if ((mPackages.containsKey(childPkg.packageName))) {
17009                        childRes.removedInfo = new PackageRemovedInfo(this);
17010                        childRes.removedInfo.removedPackage = childPkg.packageName;
17011                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17012                    }
17013                    if (res.addedChildPackages == null) {
17014                        res.addedChildPackages = new ArrayMap<>();
17015                    }
17016                    res.addedChildPackages.put(childPkg.packageName, childRes);
17017                }
17018            }
17019        }
17020
17021        // If package doesn't declare API override, mark that we have an install
17022        // time CPU ABI override.
17023        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17024            pkg.cpuAbiOverride = args.abiOverride;
17025        }
17026
17027        String pkgName = res.name = pkg.packageName;
17028        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17029            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17030                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17031                return;
17032            }
17033        }
17034
17035        try {
17036            // either use what we've been given or parse directly from the APK
17037            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17038                pkg.setSigningDetails(args.signingDetails);
17039            } else {
17040                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17041            }
17042        } catch (PackageParserException e) {
17043            res.setError("Failed collect during installPackageLI", e);
17044            return;
17045        }
17046
17047        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17048                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17049            Slog.w(TAG, "Instant app package " + pkg.packageName
17050                    + " is not signed with at least APK Signature Scheme v2");
17051            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17052                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17053            return;
17054        }
17055
17056        // Get rid of all references to package scan path via parser.
17057        pp = null;
17058        String oldCodePath = null;
17059        boolean systemApp = false;
17060        synchronized (mPackages) {
17061            // Check if installing already existing package
17062            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17063                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17064                if (pkg.mOriginalPackages != null
17065                        && pkg.mOriginalPackages.contains(oldName)
17066                        && mPackages.containsKey(oldName)) {
17067                    // This package is derived from an original package,
17068                    // and this device has been updating from that original
17069                    // name.  We must continue using the original name, so
17070                    // rename the new package here.
17071                    pkg.setPackageName(oldName);
17072                    pkgName = pkg.packageName;
17073                    replace = true;
17074                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17075                            + oldName + " pkgName=" + pkgName);
17076                } else if (mPackages.containsKey(pkgName)) {
17077                    // This package, under its official name, already exists
17078                    // on the device; we should replace it.
17079                    replace = true;
17080                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17081                }
17082
17083                // Child packages are installed through the parent package
17084                if (pkg.parentPackage != null) {
17085                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17086                            "Package " + pkg.packageName + " is child of package "
17087                                    + pkg.parentPackage.parentPackage + ". Child packages "
17088                                    + "can be updated only through the parent package.");
17089                    return;
17090                }
17091
17092                if (replace) {
17093                    // Prevent apps opting out from runtime permissions
17094                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17095                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17096                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17097                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17098                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17099                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17100                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17101                                        + " doesn't support runtime permissions but the old"
17102                                        + " target SDK " + oldTargetSdk + " does.");
17103                        return;
17104                    }
17105                    // Prevent persistent apps from being updated
17106                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17107                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17108                                "Package " + oldPackage.packageName + " is a persistent app. "
17109                                        + "Persistent apps are not updateable.");
17110                        return;
17111                    }
17112                    // Prevent apps from downgrading their targetSandbox.
17113                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17114                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17115                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17116                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17117                                "Package " + pkg.packageName + " new target sandbox "
17118                                + newTargetSandbox + " is incompatible with the previous value of"
17119                                + oldTargetSandbox + ".");
17120                        return;
17121                    }
17122
17123                    // Prevent installing of child packages
17124                    if (oldPackage.parentPackage != null) {
17125                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17126                                "Package " + pkg.packageName + " is child of package "
17127                                        + oldPackage.parentPackage + ". Child packages "
17128                                        + "can be updated only through the parent package.");
17129                        return;
17130                    }
17131                }
17132            }
17133
17134            PackageSetting ps = mSettings.mPackages.get(pkgName);
17135            if (ps != null) {
17136                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17137
17138                // Static shared libs have same package with different versions where
17139                // we internally use a synthetic package name to allow multiple versions
17140                // of the same package, therefore we need to compare signatures against
17141                // the package setting for the latest library version.
17142                PackageSetting signatureCheckPs = ps;
17143                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17144                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17145                    if (libraryEntry != null) {
17146                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17147                    }
17148                }
17149
17150                // Quick sanity check that we're signed correctly if updating;
17151                // we'll check this again later when scanning, but we want to
17152                // bail early here before tripping over redefined permissions.
17153                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17154                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17155                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17156                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17157                                + pkg.packageName + " upgrade keys do not match the "
17158                                + "previously installed version");
17159                        return;
17160                    }
17161                } else {
17162                    try {
17163                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17164                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17165                        // We don't care about disabledPkgSetting on install for now.
17166                        final boolean compatMatch = verifySignatures(
17167                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17168                                compareRecover);
17169                        // The new KeySets will be re-added later in the scanning process.
17170                        if (compatMatch) {
17171                            synchronized (mPackages) {
17172                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17173                            }
17174                        }
17175                    } catch (PackageManagerException e) {
17176                        res.setError(e.error, e.getMessage());
17177                        return;
17178                    }
17179                }
17180
17181                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17182                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17183                    systemApp = (ps.pkg.applicationInfo.flags &
17184                            ApplicationInfo.FLAG_SYSTEM) != 0;
17185                }
17186                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17187            }
17188
17189            int N = pkg.permissions.size();
17190            for (int i = N-1; i >= 0; i--) {
17191                final PackageParser.Permission perm = pkg.permissions.get(i);
17192                final BasePermission bp =
17193                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17194
17195                // Don't allow anyone but the system to define ephemeral permissions.
17196                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17197                        && !systemApp) {
17198                    Slog.w(TAG, "Non-System package " + pkg.packageName
17199                            + " attempting to delcare ephemeral permission "
17200                            + perm.info.name + "; Removing ephemeral.");
17201                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17202                }
17203
17204                // Check whether the newly-scanned package wants to define an already-defined perm
17205                if (bp != null) {
17206                    // If the defining package is signed with our cert, it's okay.  This
17207                    // also includes the "updating the same package" case, of course.
17208                    // "updating same package" could also involve key-rotation.
17209                    final boolean sigsOk;
17210                    final String sourcePackageName = bp.getSourcePackageName();
17211                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17212                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17213                    if (sourcePackageName.equals(pkg.packageName)
17214                            && (ksms.shouldCheckUpgradeKeySetLocked(
17215                                    sourcePackageSetting, scanFlags))) {
17216                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17217                    } else {
17218
17219                        // in the event of signing certificate rotation, we need to see if the
17220                        // package's certificate has rotated from the current one, or if it is an
17221                        // older certificate with which the current is ok with sharing permissions
17222                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17223                                        pkg.mSigningDetails,
17224                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17225                            sigsOk = true;
17226                        } else if (pkg.mSigningDetails.checkCapability(
17227                                        sourcePackageSetting.signatures.mSigningDetails,
17228                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17229
17230                            // the scanned package checks out, has signing certificate rotation
17231                            // history, and is newer; bring it over
17232                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17233                            sigsOk = true;
17234                        } else {
17235                            sigsOk = false;
17236                        }
17237                    }
17238                    if (!sigsOk) {
17239                        // If the owning package is the system itself, we log but allow
17240                        // install to proceed; we fail the install on all other permission
17241                        // redefinitions.
17242                        if (!sourcePackageName.equals("android")) {
17243                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17244                                    + pkg.packageName + " attempting to redeclare permission "
17245                                    + perm.info.name + " already owned by " + sourcePackageName);
17246                            res.origPermission = perm.info.name;
17247                            res.origPackage = sourcePackageName;
17248                            return;
17249                        } else {
17250                            Slog.w(TAG, "Package " + pkg.packageName
17251                                    + " attempting to redeclare system permission "
17252                                    + perm.info.name + "; ignoring new declaration");
17253                            pkg.permissions.remove(i);
17254                        }
17255                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17256                        // Prevent apps to change protection level to dangerous from any other
17257                        // type as this would allow a privilege escalation where an app adds a
17258                        // normal/signature permission in other app's group and later redefines
17259                        // it as dangerous leading to the group auto-grant.
17260                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17261                                == PermissionInfo.PROTECTION_DANGEROUS) {
17262                            if (bp != null && !bp.isRuntime()) {
17263                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17264                                        + "non-runtime permission " + perm.info.name
17265                                        + " to runtime; keeping old protection level");
17266                                perm.info.protectionLevel = bp.getProtectionLevel();
17267                            }
17268                        }
17269                    }
17270                }
17271            }
17272        }
17273
17274        if (systemApp) {
17275            if (onExternal) {
17276                // Abort update; system app can't be replaced with app on sdcard
17277                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17278                        "Cannot install updates to system apps on sdcard");
17279                return;
17280            } else if (instantApp) {
17281                // Abort update; system app can't be replaced with an instant app
17282                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17283                        "Cannot update a system app with an instant app");
17284                return;
17285            }
17286        }
17287
17288        if (args.move != null) {
17289            // We did an in-place move, so dex is ready to roll
17290            scanFlags |= SCAN_NO_DEX;
17291            scanFlags |= SCAN_MOVE;
17292
17293            synchronized (mPackages) {
17294                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17295                if (ps == null) {
17296                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17297                            "Missing settings for moved package " + pkgName);
17298                }
17299
17300                // We moved the entire application as-is, so bring over the
17301                // previously derived ABI information.
17302                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17303                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17304            }
17305
17306        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17307            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17308            scanFlags |= SCAN_NO_DEX;
17309
17310            try {
17311                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17312                    args.abiOverride : pkg.cpuAbiOverride);
17313                final boolean extractNativeLibs = !pkg.isLibrary();
17314                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17315            } catch (PackageManagerException pme) {
17316                Slog.e(TAG, "Error deriving application ABI", pme);
17317                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17318                return;
17319            }
17320
17321            // Shared libraries for the package need to be updated.
17322            synchronized (mPackages) {
17323                try {
17324                    updateSharedLibrariesLPr(pkg, null);
17325                } catch (PackageManagerException e) {
17326                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17327                }
17328            }
17329        }
17330
17331        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17332            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17333            return;
17334        }
17335
17336        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17337            String apkPath = null;
17338            synchronized (mPackages) {
17339                // Note that if the attacker managed to skip verify setup, for example by tampering
17340                // with the package settings, upon reboot we will do full apk verification when
17341                // verity is not detected.
17342                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17343                if (ps != null && ps.isPrivileged()) {
17344                    apkPath = pkg.baseCodePath;
17345                }
17346            }
17347
17348            if (apkPath != null) {
17349                final VerityUtils.SetupResult result =
17350                        VerityUtils.generateApkVeritySetupData(apkPath);
17351                if (result.isOk()) {
17352                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17353                    FileDescriptor fd = result.getUnownedFileDescriptor();
17354                    try {
17355                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17356                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17357                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17358                    } catch (InstallerException | IOException | DigestException |
17359                             NoSuchAlgorithmException e) {
17360                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17361                                "Failed to set up verity: " + e);
17362                        return;
17363                    } finally {
17364                        IoUtils.closeQuietly(fd);
17365                    }
17366                } else if (result.isFailed()) {
17367                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17368                    return;
17369                } else {
17370                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17371                    // reboot.
17372                }
17373            }
17374        }
17375
17376        if (!instantApp) {
17377            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17378        } else {
17379            if (DEBUG_DOMAIN_VERIFICATION) {
17380                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17381            }
17382        }
17383
17384        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17385                "installPackageLI")) {
17386            if (replace) {
17387                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17388                    // Static libs have a synthetic package name containing the version
17389                    // and cannot be updated as an update would get a new package name,
17390                    // unless this is the exact same version code which is useful for
17391                    // development.
17392                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17393                    if (existingPkg != null &&
17394                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17395                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17396                                + "static-shared libs cannot be updated");
17397                        return;
17398                    }
17399                }
17400                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17401                        installerPackageName, res, args.installReason);
17402            } else {
17403                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17404                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17405            }
17406        }
17407
17408        // Prepare the application profiles for the new code paths.
17409        // This needs to be done before invoking dexopt so that any install-time profile
17410        // can be used for optimizations.
17411        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17412
17413        // Check whether we need to dexopt the app.
17414        //
17415        // NOTE: it is IMPORTANT to call dexopt:
17416        //   - after doRename which will sync the package data from PackageParser.Package and its
17417        //     corresponding ApplicationInfo.
17418        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17419        //     uid of the application (pkg.applicationInfo.uid).
17420        //     This update happens in place!
17421        //
17422        // We only need to dexopt if the package meets ALL of the following conditions:
17423        //   1) it is not forward locked.
17424        //   2) it is not on on an external ASEC container.
17425        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17426        //
17427        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17428        // complete, so we skip this step during installation. Instead, we'll take extra time
17429        // the first time the instant app starts. It's preferred to do it this way to provide
17430        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17431        // middle of running an instant app. The default behaviour can be overridden
17432        // via gservices.
17433        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17434                && !forwardLocked
17435                && !pkg.applicationInfo.isExternalAsec()
17436                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17437                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17438
17439        if (performDexopt) {
17440            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17441            // Do not run PackageDexOptimizer through the local performDexOpt
17442            // method because `pkg` may not be in `mPackages` yet.
17443            //
17444            // Also, don't fail application installs if the dexopt step fails.
17445            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17446                    REASON_INSTALL,
17447                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17448                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17449            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17450                    null /* instructionSets */,
17451                    getOrCreateCompilerPackageStats(pkg),
17452                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17453                    dexoptOptions);
17454            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17455        }
17456
17457        // Notify BackgroundDexOptService that the package has been changed.
17458        // If this is an update of a package which used to fail to compile,
17459        // BackgroundDexOptService will remove it from its blacklist.
17460        // TODO: Layering violation
17461        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17462
17463        synchronized (mPackages) {
17464            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17465            if (ps != null) {
17466                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17467                ps.setUpdateAvailable(false /*updateAvailable*/);
17468            }
17469
17470            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17471            for (int i = 0; i < childCount; i++) {
17472                PackageParser.Package childPkg = pkg.childPackages.get(i);
17473                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17474                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17475                if (childPs != null) {
17476                    childRes.newUsers = childPs.queryInstalledUsers(
17477                            sUserManager.getUserIds(), true);
17478                }
17479            }
17480
17481            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17482                updateSequenceNumberLP(ps, res.newUsers);
17483                updateInstantAppInstallerLocked(pkgName);
17484            }
17485        }
17486    }
17487
17488    private void startIntentFilterVerifications(int userId, boolean replacing,
17489            PackageParser.Package pkg) {
17490        if (mIntentFilterVerifierComponent == null) {
17491            Slog.w(TAG, "No IntentFilter verification will not be done as "
17492                    + "there is no IntentFilterVerifier available!");
17493            return;
17494        }
17495
17496        final int verifierUid = getPackageUid(
17497                mIntentFilterVerifierComponent.getPackageName(),
17498                MATCH_DEBUG_TRIAGED_MISSING,
17499                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17500
17501        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17502        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17503        mHandler.sendMessage(msg);
17504
17505        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17506        for (int i = 0; i < childCount; i++) {
17507            PackageParser.Package childPkg = pkg.childPackages.get(i);
17508            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17509            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17510            mHandler.sendMessage(msg);
17511        }
17512    }
17513
17514    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17515            PackageParser.Package pkg) {
17516        int size = pkg.activities.size();
17517        if (size == 0) {
17518            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17519                    "No activity, so no need to verify any IntentFilter!");
17520            return;
17521        }
17522
17523        final boolean hasDomainURLs = hasDomainURLs(pkg);
17524        if (!hasDomainURLs) {
17525            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17526                    "No domain URLs, so no need to verify any IntentFilter!");
17527            return;
17528        }
17529
17530        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17531                + " if any IntentFilter from the " + size
17532                + " Activities needs verification ...");
17533
17534        int count = 0;
17535        final String packageName = pkg.packageName;
17536
17537        synchronized (mPackages) {
17538            // If this is a new install and we see that we've already run verification for this
17539            // package, we have nothing to do: it means the state was restored from backup.
17540            if (!replacing) {
17541                IntentFilterVerificationInfo ivi =
17542                        mSettings.getIntentFilterVerificationLPr(packageName);
17543                if (ivi != null) {
17544                    if (DEBUG_DOMAIN_VERIFICATION) {
17545                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17546                                + ivi.getStatusString());
17547                    }
17548                    return;
17549                }
17550            }
17551
17552            // If any filters need to be verified, then all need to be.
17553            boolean needToVerify = false;
17554            for (PackageParser.Activity a : pkg.activities) {
17555                for (ActivityIntentInfo filter : a.intents) {
17556                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17557                        if (DEBUG_DOMAIN_VERIFICATION) {
17558                            Slog.d(TAG,
17559                                    "Intent filter needs verification, so processing all filters");
17560                        }
17561                        needToVerify = true;
17562                        break;
17563                    }
17564                }
17565            }
17566
17567            if (needToVerify) {
17568                final int verificationId = mIntentFilterVerificationToken++;
17569                for (PackageParser.Activity a : pkg.activities) {
17570                    for (ActivityIntentInfo filter : a.intents) {
17571                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17572                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17573                                    "Verification needed for IntentFilter:" + filter.toString());
17574                            mIntentFilterVerifier.addOneIntentFilterVerification(
17575                                    verifierUid, userId, verificationId, filter, packageName);
17576                            count++;
17577                        }
17578                    }
17579                }
17580            }
17581        }
17582
17583        if (count > 0) {
17584            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17585                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17586                    +  " for userId:" + userId);
17587            mIntentFilterVerifier.startVerifications(userId);
17588        } else {
17589            if (DEBUG_DOMAIN_VERIFICATION) {
17590                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17591            }
17592        }
17593    }
17594
17595    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17596        final ComponentName cn  = filter.activity.getComponentName();
17597        final String packageName = cn.getPackageName();
17598
17599        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17600                packageName);
17601        if (ivi == null) {
17602            return true;
17603        }
17604        int status = ivi.getStatus();
17605        switch (status) {
17606            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17607            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17608                return true;
17609
17610            default:
17611                // Nothing to do
17612                return false;
17613        }
17614    }
17615
17616    private static boolean isMultiArch(ApplicationInfo info) {
17617        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17618    }
17619
17620    private static boolean isExternal(PackageParser.Package pkg) {
17621        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17622    }
17623
17624    private static boolean isExternal(PackageSetting ps) {
17625        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17626    }
17627
17628    private static boolean isSystemApp(PackageParser.Package pkg) {
17629        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17630    }
17631
17632    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17633        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17634    }
17635
17636    private static boolean isOemApp(PackageParser.Package pkg) {
17637        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17638    }
17639
17640    private static boolean isVendorApp(PackageParser.Package pkg) {
17641        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17642    }
17643
17644    private static boolean isProductApp(PackageParser.Package pkg) {
17645        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17646    }
17647
17648    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17649        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17650    }
17651
17652    private static boolean isSystemApp(PackageSetting ps) {
17653        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17654    }
17655
17656    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17657        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17658    }
17659
17660    private int packageFlagsToInstallFlags(PackageSetting ps) {
17661        int installFlags = 0;
17662        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17663            // This existing package was an external ASEC install when we have
17664            // the external flag without a UUID
17665            installFlags |= PackageManager.INSTALL_EXTERNAL;
17666        }
17667        if (ps.isForwardLocked()) {
17668            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17669        }
17670        return installFlags;
17671    }
17672
17673    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17674        if (isExternal(pkg)) {
17675            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17676                return mSettings.getExternalVersion();
17677            } else {
17678                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17679            }
17680        } else {
17681            return mSettings.getInternalVersion();
17682        }
17683    }
17684
17685    private void deleteTempPackageFiles() {
17686        final FilenameFilter filter = new FilenameFilter() {
17687            public boolean accept(File dir, String name) {
17688                return name.startsWith("vmdl") && name.endsWith(".tmp");
17689            }
17690        };
17691        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17692            file.delete();
17693        }
17694    }
17695
17696    @Override
17697    public void deletePackageAsUser(String packageName, int versionCode,
17698            IPackageDeleteObserver observer, int userId, int flags) {
17699        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17700                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17701    }
17702
17703    @Override
17704    public void deletePackageVersioned(VersionedPackage versionedPackage,
17705            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17706        final int callingUid = Binder.getCallingUid();
17707        mContext.enforceCallingOrSelfPermission(
17708                android.Manifest.permission.DELETE_PACKAGES, null);
17709        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17710        Preconditions.checkNotNull(versionedPackage);
17711        Preconditions.checkNotNull(observer);
17712        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17713                PackageManager.VERSION_CODE_HIGHEST,
17714                Long.MAX_VALUE, "versionCode must be >= -1");
17715
17716        final String packageName = versionedPackage.getPackageName();
17717        final long versionCode = versionedPackage.getLongVersionCode();
17718        final String internalPackageName;
17719        synchronized (mPackages) {
17720            // Normalize package name to handle renamed packages and static libs
17721            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17722        }
17723
17724        final int uid = Binder.getCallingUid();
17725        if (!isOrphaned(internalPackageName)
17726                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17727            try {
17728                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17729                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17730                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17731                observer.onUserActionRequired(intent);
17732            } catch (RemoteException re) {
17733            }
17734            return;
17735        }
17736        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17737        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17738        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17739            mContext.enforceCallingOrSelfPermission(
17740                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17741                    "deletePackage for user " + userId);
17742        }
17743
17744        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17745            try {
17746                observer.onPackageDeleted(packageName,
17747                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17748            } catch (RemoteException re) {
17749            }
17750            return;
17751        }
17752
17753        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17754            try {
17755                observer.onPackageDeleted(packageName,
17756                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17757            } catch (RemoteException re) {
17758            }
17759            return;
17760        }
17761
17762        if (DEBUG_REMOVE) {
17763            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17764                    + " deleteAllUsers: " + deleteAllUsers + " version="
17765                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17766                    ? "VERSION_CODE_HIGHEST" : versionCode));
17767        }
17768        // Queue up an async operation since the package deletion may take a little while.
17769        mHandler.post(new Runnable() {
17770            public void run() {
17771                mHandler.removeCallbacks(this);
17772                int returnCode;
17773                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17774                boolean doDeletePackage = true;
17775                if (ps != null) {
17776                    final boolean targetIsInstantApp =
17777                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17778                    doDeletePackage = !targetIsInstantApp
17779                            || canViewInstantApps;
17780                }
17781                if (doDeletePackage) {
17782                    if (!deleteAllUsers) {
17783                        returnCode = deletePackageX(internalPackageName, versionCode,
17784                                userId, deleteFlags);
17785                    } else {
17786                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17787                                internalPackageName, users);
17788                        // If nobody is blocking uninstall, proceed with delete for all users
17789                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17790                            returnCode = deletePackageX(internalPackageName, versionCode,
17791                                    userId, deleteFlags);
17792                        } else {
17793                            // Otherwise uninstall individually for users with blockUninstalls=false
17794                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17795                            for (int userId : users) {
17796                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17797                                    returnCode = deletePackageX(internalPackageName, versionCode,
17798                                            userId, userFlags);
17799                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17800                                        Slog.w(TAG, "Package delete failed for user " + userId
17801                                                + ", returnCode " + returnCode);
17802                                    }
17803                                }
17804                            }
17805                            // The app has only been marked uninstalled for certain users.
17806                            // We still need to report that delete was blocked
17807                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17808                        }
17809                    }
17810                } else {
17811                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17812                }
17813                try {
17814                    observer.onPackageDeleted(packageName, returnCode, null);
17815                } catch (RemoteException e) {
17816                    Log.i(TAG, "Observer no longer exists.");
17817                } //end catch
17818            } //end run
17819        });
17820    }
17821
17822    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17823        if (pkg.staticSharedLibName != null) {
17824            return pkg.manifestPackageName;
17825        }
17826        return pkg.packageName;
17827    }
17828
17829    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17830        // Handle renamed packages
17831        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17832        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17833
17834        // Is this a static library?
17835        LongSparseArray<SharedLibraryEntry> versionedLib =
17836                mStaticLibsByDeclaringPackage.get(packageName);
17837        if (versionedLib == null || versionedLib.size() <= 0) {
17838            return packageName;
17839        }
17840
17841        // Figure out which lib versions the caller can see
17842        LongSparseLongArray versionsCallerCanSee = null;
17843        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17844        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17845                && callingAppId != Process.ROOT_UID) {
17846            versionsCallerCanSee = new LongSparseLongArray();
17847            String libName = versionedLib.valueAt(0).info.getName();
17848            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17849            if (uidPackages != null) {
17850                for (String uidPackage : uidPackages) {
17851                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17852                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17853                    if (libIdx >= 0) {
17854                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17855                        versionsCallerCanSee.append(libVersion, libVersion);
17856                    }
17857                }
17858            }
17859        }
17860
17861        // Caller can see nothing - done
17862        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17863            return packageName;
17864        }
17865
17866        // Find the version the caller can see and the app version code
17867        SharedLibraryEntry highestVersion = null;
17868        final int versionCount = versionedLib.size();
17869        for (int i = 0; i < versionCount; i++) {
17870            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17871            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17872                    libEntry.info.getLongVersion()) < 0) {
17873                continue;
17874            }
17875            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17876            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17877                if (libVersionCode == versionCode) {
17878                    return libEntry.apk;
17879                }
17880            } else if (highestVersion == null) {
17881                highestVersion = libEntry;
17882            } else if (libVersionCode  > highestVersion.info
17883                    .getDeclaringPackage().getLongVersionCode()) {
17884                highestVersion = libEntry;
17885            }
17886        }
17887
17888        if (highestVersion != null) {
17889            return highestVersion.apk;
17890        }
17891
17892        return packageName;
17893    }
17894
17895    boolean isCallerVerifier(int callingUid) {
17896        final int callingUserId = UserHandle.getUserId(callingUid);
17897        return mRequiredVerifierPackage != null &&
17898                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17899    }
17900
17901    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17902        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17903              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17904            return true;
17905        }
17906        final int callingUserId = UserHandle.getUserId(callingUid);
17907        // If the caller installed the pkgName, then allow it to silently uninstall.
17908        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17909            return true;
17910        }
17911
17912        // Allow package verifier to silently uninstall.
17913        if (mRequiredVerifierPackage != null &&
17914                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17915            return true;
17916        }
17917
17918        // Allow package uninstaller to silently uninstall.
17919        if (mRequiredUninstallerPackage != null &&
17920                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17921            return true;
17922        }
17923
17924        // Allow storage manager to silently uninstall.
17925        if (mStorageManagerPackage != null &&
17926                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17927            return true;
17928        }
17929
17930        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17931        // uninstall for device owner provisioning.
17932        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17933                == PERMISSION_GRANTED) {
17934            return true;
17935        }
17936
17937        return false;
17938    }
17939
17940    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17941        int[] result = EMPTY_INT_ARRAY;
17942        for (int userId : userIds) {
17943            if (getBlockUninstallForUser(packageName, userId)) {
17944                result = ArrayUtils.appendInt(result, userId);
17945            }
17946        }
17947        return result;
17948    }
17949
17950    @Override
17951    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17952        final int callingUid = Binder.getCallingUid();
17953        if (getInstantAppPackageName(callingUid) != null
17954                && !isCallerSameApp(packageName, callingUid)) {
17955            return false;
17956        }
17957        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17958    }
17959
17960    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17961        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17962                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17963        try {
17964            if (dpm != null) {
17965                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17966                        /* callingUserOnly =*/ false);
17967                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17968                        : deviceOwnerComponentName.getPackageName();
17969                // Does the package contains the device owner?
17970                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17971                // this check is probably not needed, since DO should be registered as a device
17972                // admin on some user too. (Original bug for this: b/17657954)
17973                if (packageName.equals(deviceOwnerPackageName)) {
17974                    return true;
17975                }
17976                // Does it contain a device admin for any user?
17977                int[] users;
17978                if (userId == UserHandle.USER_ALL) {
17979                    users = sUserManager.getUserIds();
17980                } else {
17981                    users = new int[]{userId};
17982                }
17983                for (int i = 0; i < users.length; ++i) {
17984                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17985                        return true;
17986                    }
17987                }
17988            }
17989        } catch (RemoteException e) {
17990        }
17991        return false;
17992    }
17993
17994    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17995        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17996    }
17997
17998    /**
17999     *  This method is an internal method that could be get invoked either
18000     *  to delete an installed package or to clean up a failed installation.
18001     *  After deleting an installed package, a broadcast is sent to notify any
18002     *  listeners that the package has been removed. For cleaning up a failed
18003     *  installation, the broadcast is not necessary since the package's
18004     *  installation wouldn't have sent the initial broadcast either
18005     *  The key steps in deleting a package are
18006     *  deleting the package information in internal structures like mPackages,
18007     *  deleting the packages base directories through installd
18008     *  updating mSettings to reflect current status
18009     *  persisting settings for later use
18010     *  sending a broadcast if necessary
18011     */
18012    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18013        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18014        final boolean res;
18015
18016        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18017                ? UserHandle.USER_ALL : userId;
18018
18019        if (isPackageDeviceAdmin(packageName, removeUser)) {
18020            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18021            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18022        }
18023
18024        PackageSetting uninstalledPs = null;
18025        PackageParser.Package pkg = null;
18026
18027        // for the uninstall-updates case and restricted profiles, remember the per-
18028        // user handle installed state
18029        int[] allUsers;
18030        synchronized (mPackages) {
18031            uninstalledPs = mSettings.mPackages.get(packageName);
18032            if (uninstalledPs == null) {
18033                Slog.w(TAG, "Not removing non-existent package " + packageName);
18034                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18035            }
18036
18037            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18038                    && uninstalledPs.versionCode != versionCode) {
18039                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18040                        + uninstalledPs.versionCode + " != " + versionCode);
18041                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18042            }
18043
18044            // Static shared libs can be declared by any package, so let us not
18045            // allow removing a package if it provides a lib others depend on.
18046            pkg = mPackages.get(packageName);
18047
18048            allUsers = sUserManager.getUserIds();
18049
18050            if (pkg != null && pkg.staticSharedLibName != null) {
18051                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18052                        pkg.staticSharedLibVersion);
18053                if (libEntry != null) {
18054                    for (int currUserId : allUsers) {
18055                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18056                            continue;
18057                        }
18058                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18059                                libEntry.info, 0, currUserId);
18060                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18061                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18062                                    + " hosting lib " + libEntry.info.getName() + " version "
18063                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18064                                    + " for user " + currUserId);
18065                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18066                        }
18067                    }
18068                }
18069            }
18070
18071            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18072        }
18073
18074        final int freezeUser;
18075        if (isUpdatedSystemApp(uninstalledPs)
18076                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18077            // We're downgrading a system app, which will apply to all users, so
18078            // freeze them all during the downgrade
18079            freezeUser = UserHandle.USER_ALL;
18080        } else {
18081            freezeUser = removeUser;
18082        }
18083
18084        synchronized (mInstallLock) {
18085            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18086            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18087                    deleteFlags, "deletePackageX")) {
18088                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18089                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18090            }
18091            synchronized (mPackages) {
18092                if (res) {
18093                    if (pkg != null) {
18094                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18095                    }
18096                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18097                    updateInstantAppInstallerLocked(packageName);
18098                }
18099            }
18100        }
18101
18102        if (res) {
18103            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18104            info.sendPackageRemovedBroadcasts(killApp);
18105            info.sendSystemPackageUpdatedBroadcasts();
18106            info.sendSystemPackageAppearedBroadcasts();
18107        }
18108        // Force a gc here.
18109        Runtime.getRuntime().gc();
18110        // Delete the resources here after sending the broadcast to let
18111        // other processes clean up before deleting resources.
18112        if (info.args != null) {
18113            synchronized (mInstallLock) {
18114                info.args.doPostDeleteLI(true);
18115            }
18116        }
18117
18118        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18119    }
18120
18121    static class PackageRemovedInfo {
18122        final PackageSender packageSender;
18123        String removedPackage;
18124        String installerPackageName;
18125        int uid = -1;
18126        int removedAppId = -1;
18127        int[] origUsers;
18128        int[] removedUsers = null;
18129        int[] broadcastUsers = null;
18130        int[] instantUserIds = null;
18131        SparseArray<Integer> installReasons;
18132        boolean isRemovedPackageSystemUpdate = false;
18133        boolean isUpdate;
18134        boolean dataRemoved;
18135        boolean removedForAllUsers;
18136        boolean isStaticSharedLib;
18137        // Clean up resources deleted packages.
18138        InstallArgs args = null;
18139        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18140        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18141
18142        PackageRemovedInfo(PackageSender packageSender) {
18143            this.packageSender = packageSender;
18144        }
18145
18146        void sendPackageRemovedBroadcasts(boolean killApp) {
18147            sendPackageRemovedBroadcastInternal(killApp);
18148            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18149            for (int i = 0; i < childCount; i++) {
18150                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18151                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18152            }
18153        }
18154
18155        void sendSystemPackageUpdatedBroadcasts() {
18156            if (isRemovedPackageSystemUpdate) {
18157                sendSystemPackageUpdatedBroadcastsInternal();
18158                final int childCount = (removedChildPackages != null)
18159                        ? removedChildPackages.size() : 0;
18160                for (int i = 0; i < childCount; i++) {
18161                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18162                    if (childInfo.isRemovedPackageSystemUpdate) {
18163                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18164                    }
18165                }
18166            }
18167        }
18168
18169        void sendSystemPackageAppearedBroadcasts() {
18170            final int packageCount = (appearedChildPackages != null)
18171                    ? appearedChildPackages.size() : 0;
18172            for (int i = 0; i < packageCount; i++) {
18173                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18174                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18175                    true /*sendBootCompleted*/, false /*startReceiver*/,
18176                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18177            }
18178        }
18179
18180        private void sendSystemPackageUpdatedBroadcastsInternal() {
18181            Bundle extras = new Bundle(2);
18182            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18183            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18184            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18185                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18186            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18187                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18188            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18189                null, null, 0, removedPackage, null, null, null);
18190            if (installerPackageName != null) {
18191                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18192                        removedPackage, extras, 0 /*flags*/,
18193                        installerPackageName, null, null, null);
18194                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18195                        removedPackage, extras, 0 /*flags*/,
18196                        installerPackageName, null, null, null);
18197            }
18198        }
18199
18200        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18201            // Don't send static shared library removal broadcasts as these
18202            // libs are visible only the the apps that depend on them an one
18203            // cannot remove the library if it has a dependency.
18204            if (isStaticSharedLib) {
18205                return;
18206            }
18207            Bundle extras = new Bundle(2);
18208            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18209            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18210            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18211            if (isUpdate || isRemovedPackageSystemUpdate) {
18212                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18213            }
18214            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18215            if (removedPackage != null) {
18216                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18217                    removedPackage, extras, 0, null /*targetPackage*/, null,
18218                    broadcastUsers, instantUserIds);
18219                if (installerPackageName != null) {
18220                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18221                            removedPackage, extras, 0 /*flags*/,
18222                            installerPackageName, null, broadcastUsers, instantUserIds);
18223                }
18224                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18225                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18226                        removedPackage, extras,
18227                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18228                        null, null, broadcastUsers, instantUserIds);
18229                    packageSender.notifyPackageRemoved(removedPackage);
18230                }
18231            }
18232            if (removedAppId >= 0) {
18233                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18234                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18235                    null, null, broadcastUsers, instantUserIds);
18236            }
18237        }
18238
18239        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18240            removedUsers = userIds;
18241            if (removedUsers == null) {
18242                broadcastUsers = null;
18243                return;
18244            }
18245
18246            broadcastUsers = EMPTY_INT_ARRAY;
18247            instantUserIds = EMPTY_INT_ARRAY;
18248            for (int i = userIds.length - 1; i >= 0; --i) {
18249                final int userId = userIds[i];
18250                if (deletedPackageSetting.getInstantApp(userId)) {
18251                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18252                } else {
18253                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18254                }
18255            }
18256        }
18257    }
18258
18259    /*
18260     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18261     * flag is not set, the data directory is removed as well.
18262     * make sure this flag is set for partially installed apps. If not its meaningless to
18263     * delete a partially installed application.
18264     */
18265    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18266            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18267        String packageName = ps.name;
18268        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18269        // Retrieve object to delete permissions for shared user later on
18270        final PackageParser.Package deletedPkg;
18271        final PackageSetting deletedPs;
18272        // reader
18273        synchronized (mPackages) {
18274            deletedPkg = mPackages.get(packageName);
18275            deletedPs = mSettings.mPackages.get(packageName);
18276            if (outInfo != null) {
18277                outInfo.removedPackage = packageName;
18278                outInfo.installerPackageName = ps.installerPackageName;
18279                outInfo.isStaticSharedLib = deletedPkg != null
18280                        && deletedPkg.staticSharedLibName != null;
18281                outInfo.populateUsers(deletedPs == null ? null
18282                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18283            }
18284        }
18285
18286        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18287
18288        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18289            final PackageParser.Package resolvedPkg;
18290            if (deletedPkg != null) {
18291                resolvedPkg = deletedPkg;
18292            } else {
18293                // We don't have a parsed package when it lives on an ejected
18294                // adopted storage device, so fake something together
18295                resolvedPkg = new PackageParser.Package(ps.name);
18296                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18297            }
18298            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18299                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18300            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18301            if (outInfo != null) {
18302                outInfo.dataRemoved = true;
18303            }
18304            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18305        }
18306
18307        int removedAppId = -1;
18308
18309        // writer
18310        synchronized (mPackages) {
18311            boolean installedStateChanged = false;
18312            if (deletedPs != null) {
18313                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18314                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18315                    clearDefaultBrowserIfNeeded(packageName);
18316                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18317                    removedAppId = mSettings.removePackageLPw(packageName);
18318                    if (outInfo != null) {
18319                        outInfo.removedAppId = removedAppId;
18320                    }
18321                    mPermissionManager.updatePermissions(
18322                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18323                    if (deletedPs.sharedUser != null) {
18324                        // Remove permissions associated with package. Since runtime
18325                        // permissions are per user we have to kill the removed package
18326                        // or packages running under the shared user of the removed
18327                        // package if revoking the permissions requested only by the removed
18328                        // package is successful and this causes a change in gids.
18329                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18330                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18331                                    userId);
18332                            if (userIdToKill == UserHandle.USER_ALL
18333                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18334                                // If gids changed for this user, kill all affected packages.
18335                                mHandler.post(new Runnable() {
18336                                    @Override
18337                                    public void run() {
18338                                        // This has to happen with no lock held.
18339                                        killApplication(deletedPs.name, deletedPs.appId,
18340                                                KILL_APP_REASON_GIDS_CHANGED);
18341                                    }
18342                                });
18343                                break;
18344                            }
18345                        }
18346                    }
18347                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18348                }
18349                // make sure to preserve per-user disabled state if this removal was just
18350                // a downgrade of a system app to the factory package
18351                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18352                    if (DEBUG_REMOVE) {
18353                        Slog.d(TAG, "Propagating install state across downgrade");
18354                    }
18355                    for (int userId : allUserHandles) {
18356                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18357                        if (DEBUG_REMOVE) {
18358                            Slog.d(TAG, "    user " + userId + " => " + installed);
18359                        }
18360                        if (installed != ps.getInstalled(userId)) {
18361                            installedStateChanged = true;
18362                        }
18363                        ps.setInstalled(installed, userId);
18364                    }
18365                }
18366            }
18367            // can downgrade to reader
18368            if (writeSettings) {
18369                // Save settings now
18370                mSettings.writeLPr();
18371            }
18372            if (installedStateChanged) {
18373                mSettings.writeKernelMappingLPr(ps);
18374            }
18375        }
18376        if (removedAppId != -1) {
18377            // A user ID was deleted here. Go through all users and remove it
18378            // from KeyStore.
18379            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18380        }
18381    }
18382
18383    static boolean locationIsPrivileged(String path) {
18384        try {
18385            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18386            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18387            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18388            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18389            return path.startsWith(privilegedAppDir.getCanonicalPath())
18390                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18391                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18392                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18393        } catch (IOException e) {
18394            Slog.e(TAG, "Unable to access code path " + path);
18395        }
18396        return false;
18397    }
18398
18399    static boolean locationIsOem(String path) {
18400        try {
18401            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18402        } catch (IOException e) {
18403            Slog.e(TAG, "Unable to access code path " + path);
18404        }
18405        return false;
18406    }
18407
18408    static boolean locationIsVendor(String path) {
18409        try {
18410            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18411                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18412        } catch (IOException e) {
18413            Slog.e(TAG, "Unable to access code path " + path);
18414        }
18415        return false;
18416    }
18417
18418    static boolean locationIsProduct(String path) {
18419        try {
18420            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18421        } catch (IOException e) {
18422            Slog.e(TAG, "Unable to access code path " + path);
18423        }
18424        return false;
18425    }
18426
18427    /*
18428     * Tries to delete system package.
18429     */
18430    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18431            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18432            boolean writeSettings) {
18433        if (deletedPs.parentPackageName != null) {
18434            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18435            return false;
18436        }
18437
18438        final boolean applyUserRestrictions
18439                = (allUserHandles != null) && (outInfo.origUsers != null);
18440        final PackageSetting disabledPs;
18441        // Confirm if the system package has been updated
18442        // An updated system app can be deleted. This will also have to restore
18443        // the system pkg from system partition
18444        // reader
18445        synchronized (mPackages) {
18446            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18447        }
18448
18449        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18450                + " disabledPs=" + disabledPs);
18451
18452        if (disabledPs == null) {
18453            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18454            return false;
18455        } else if (DEBUG_REMOVE) {
18456            Slog.d(TAG, "Deleting system pkg from data partition");
18457        }
18458
18459        if (DEBUG_REMOVE) {
18460            if (applyUserRestrictions) {
18461                Slog.d(TAG, "Remembering install states:");
18462                for (int userId : allUserHandles) {
18463                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18464                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18465                }
18466            }
18467        }
18468
18469        // Delete the updated package
18470        outInfo.isRemovedPackageSystemUpdate = true;
18471        if (outInfo.removedChildPackages != null) {
18472            final int childCount = (deletedPs.childPackageNames != null)
18473                    ? deletedPs.childPackageNames.size() : 0;
18474            for (int i = 0; i < childCount; i++) {
18475                String childPackageName = deletedPs.childPackageNames.get(i);
18476                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18477                        .contains(childPackageName)) {
18478                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18479                            childPackageName);
18480                    if (childInfo != null) {
18481                        childInfo.isRemovedPackageSystemUpdate = true;
18482                    }
18483                }
18484            }
18485        }
18486
18487        if (disabledPs.versionCode < deletedPs.versionCode) {
18488            // Delete data for downgrades
18489            flags &= ~PackageManager.DELETE_KEEP_DATA;
18490        } else {
18491            // Preserve data by setting flag
18492            flags |= PackageManager.DELETE_KEEP_DATA;
18493        }
18494
18495        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18496                outInfo, writeSettings, disabledPs.pkg);
18497        if (!ret) {
18498            return false;
18499        }
18500
18501        // writer
18502        synchronized (mPackages) {
18503            // NOTE: The system package always needs to be enabled; even if it's for
18504            // a compressed stub. If we don't, installing the system package fails
18505            // during scan [scanning checks the disabled packages]. We will reverse
18506            // this later, after we've "installed" the stub.
18507            // Reinstate the old system package
18508            enableSystemPackageLPw(disabledPs.pkg);
18509            // Remove any native libraries from the upgraded package.
18510            removeNativeBinariesLI(deletedPs);
18511        }
18512
18513        // Install the system package
18514        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18515        try {
18516            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18517                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18518        } catch (PackageManagerException e) {
18519            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18520                    + e.getMessage());
18521            return false;
18522        } finally {
18523            if (disabledPs.pkg.isStub) {
18524                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18525            }
18526        }
18527        return true;
18528    }
18529
18530    /**
18531     * Installs a package that's already on the system partition.
18532     */
18533    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18534            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18535            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18536                    throws PackageManagerException {
18537        @ParseFlags int parseFlags =
18538                mDefParseFlags
18539                | PackageParser.PARSE_MUST_BE_APK
18540                | PackageParser.PARSE_IS_SYSTEM_DIR;
18541        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18542        if (isPrivileged || locationIsPrivileged(codePathString)) {
18543            scanFlags |= SCAN_AS_PRIVILEGED;
18544        }
18545        if (locationIsOem(codePathString)) {
18546            scanFlags |= SCAN_AS_OEM;
18547        }
18548        if (locationIsVendor(codePathString)) {
18549            scanFlags |= SCAN_AS_VENDOR;
18550        }
18551        if (locationIsProduct(codePathString)) {
18552            scanFlags |= SCAN_AS_PRODUCT;
18553        }
18554
18555        final File codePath = new File(codePathString);
18556        final PackageParser.Package pkg =
18557                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18558
18559        try {
18560            // update shared libraries for the newly re-installed system package
18561            updateSharedLibrariesLPr(pkg, null);
18562        } catch (PackageManagerException e) {
18563            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18564        }
18565
18566        prepareAppDataAfterInstallLIF(pkg);
18567
18568        // writer
18569        synchronized (mPackages) {
18570            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18571
18572            // Propagate the permissions state as we do not want to drop on the floor
18573            // runtime permissions. The update permissions method below will take
18574            // care of removing obsolete permissions and grant install permissions.
18575            if (origPermissionState != null) {
18576                ps.getPermissionsState().copyFrom(origPermissionState);
18577            }
18578            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18579                    mPermissionCallback);
18580
18581            final boolean applyUserRestrictions
18582                    = (allUserHandles != null) && (origUserHandles != null);
18583            if (applyUserRestrictions) {
18584                boolean installedStateChanged = false;
18585                if (DEBUG_REMOVE) {
18586                    Slog.d(TAG, "Propagating install state across reinstall");
18587                }
18588                for (int userId : allUserHandles) {
18589                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18590                    if (DEBUG_REMOVE) {
18591                        Slog.d(TAG, "    user " + userId + " => " + installed);
18592                    }
18593                    if (installed != ps.getInstalled(userId)) {
18594                        installedStateChanged = true;
18595                    }
18596                    ps.setInstalled(installed, userId);
18597
18598                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18599                }
18600                // Regardless of writeSettings we need to ensure that this restriction
18601                // state propagation is persisted
18602                mSettings.writeAllUsersPackageRestrictionsLPr();
18603                if (installedStateChanged) {
18604                    mSettings.writeKernelMappingLPr(ps);
18605                }
18606            }
18607            // can downgrade to reader here
18608            if (writeSettings) {
18609                mSettings.writeLPr();
18610            }
18611        }
18612        return pkg;
18613    }
18614
18615    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18616            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18617            PackageRemovedInfo outInfo, boolean writeSettings,
18618            PackageParser.Package replacingPackage) {
18619        synchronized (mPackages) {
18620            if (outInfo != null) {
18621                outInfo.uid = ps.appId;
18622            }
18623
18624            if (outInfo != null && outInfo.removedChildPackages != null) {
18625                final int childCount = (ps.childPackageNames != null)
18626                        ? ps.childPackageNames.size() : 0;
18627                for (int i = 0; i < childCount; i++) {
18628                    String childPackageName = ps.childPackageNames.get(i);
18629                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18630                    if (childPs == null) {
18631                        return false;
18632                    }
18633                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18634                            childPackageName);
18635                    if (childInfo != null) {
18636                        childInfo.uid = childPs.appId;
18637                    }
18638                }
18639            }
18640        }
18641
18642        // Delete package data from internal structures and also remove data if flag is set
18643        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18644
18645        // Delete the child packages data
18646        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18647        for (int i = 0; i < childCount; i++) {
18648            PackageSetting childPs;
18649            synchronized (mPackages) {
18650                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18651            }
18652            if (childPs != null) {
18653                PackageRemovedInfo childOutInfo = (outInfo != null
18654                        && outInfo.removedChildPackages != null)
18655                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18656                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18657                        && (replacingPackage != null
18658                        && !replacingPackage.hasChildPackage(childPs.name))
18659                        ? flags & ~DELETE_KEEP_DATA : flags;
18660                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18661                        deleteFlags, writeSettings);
18662            }
18663        }
18664
18665        // Delete application code and resources only for parent packages
18666        if (ps.parentPackageName == null) {
18667            if (deleteCodeAndResources && (outInfo != null)) {
18668                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18669                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18670                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18671            }
18672        }
18673
18674        return true;
18675    }
18676
18677    @Override
18678    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18679            int userId) {
18680        mContext.enforceCallingOrSelfPermission(
18681                android.Manifest.permission.DELETE_PACKAGES, null);
18682        synchronized (mPackages) {
18683            // Cannot block uninstall of static shared libs as they are
18684            // considered a part of the using app (emulating static linking).
18685            // Also static libs are installed always on internal storage.
18686            PackageParser.Package pkg = mPackages.get(packageName);
18687            if (pkg != null && pkg.staticSharedLibName != null) {
18688                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18689                        + " providing static shared library: " + pkg.staticSharedLibName);
18690                return false;
18691            }
18692            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18693            mSettings.writePackageRestrictionsLPr(userId);
18694        }
18695        return true;
18696    }
18697
18698    @Override
18699    public boolean getBlockUninstallForUser(String packageName, int userId) {
18700        synchronized (mPackages) {
18701            final PackageSetting ps = mSettings.mPackages.get(packageName);
18702            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18703                return false;
18704            }
18705            return mSettings.getBlockUninstallLPr(userId, packageName);
18706        }
18707    }
18708
18709    @Override
18710    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18711        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18712        synchronized (mPackages) {
18713            PackageSetting ps = mSettings.mPackages.get(packageName);
18714            if (ps == null) {
18715                Log.w(TAG, "Package doesn't exist: " + packageName);
18716                return false;
18717            }
18718            if (systemUserApp) {
18719                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18720            } else {
18721                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18722            }
18723            mSettings.writeLPr();
18724        }
18725        return true;
18726    }
18727
18728    /*
18729     * This method handles package deletion in general
18730     */
18731    private boolean deletePackageLIF(String packageName, UserHandle user,
18732            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18733            PackageRemovedInfo outInfo, boolean writeSettings,
18734            PackageParser.Package replacingPackage) {
18735        if (packageName == null) {
18736            Slog.w(TAG, "Attempt to delete null packageName.");
18737            return false;
18738        }
18739
18740        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18741
18742        PackageSetting ps;
18743        synchronized (mPackages) {
18744            ps = mSettings.mPackages.get(packageName);
18745            if (ps == null) {
18746                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18747                return false;
18748            }
18749
18750            if (ps.parentPackageName != null && (!isSystemApp(ps)
18751                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18752                if (DEBUG_REMOVE) {
18753                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18754                            + ((user == null) ? UserHandle.USER_ALL : user));
18755                }
18756                final int removedUserId = (user != null) ? user.getIdentifier()
18757                        : UserHandle.USER_ALL;
18758
18759                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18760                    return false;
18761                }
18762                markPackageUninstalledForUserLPw(ps, user);
18763                scheduleWritePackageRestrictionsLocked(user);
18764                return true;
18765            }
18766        }
18767
18768        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18769        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18770            onSuspendingPackageRemoved(packageName, userId);
18771        }
18772
18773
18774        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18775                && user.getIdentifier() != UserHandle.USER_ALL)) {
18776            // The caller is asking that the package only be deleted for a single
18777            // user.  To do this, we just mark its uninstalled state and delete
18778            // its data. If this is a system app, we only allow this to happen if
18779            // they have set the special DELETE_SYSTEM_APP which requests different
18780            // semantics than normal for uninstalling system apps.
18781            markPackageUninstalledForUserLPw(ps, user);
18782
18783            if (!isSystemApp(ps)) {
18784                // Do not uninstall the APK if an app should be cached
18785                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18786                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18787                    // Other user still have this package installed, so all
18788                    // we need to do is clear this user's data and save that
18789                    // it is uninstalled.
18790                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18791                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18792                        return false;
18793                    }
18794                    scheduleWritePackageRestrictionsLocked(user);
18795                    return true;
18796                } else {
18797                    // We need to set it back to 'installed' so the uninstall
18798                    // broadcasts will be sent correctly.
18799                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18800                    ps.setInstalled(true, user.getIdentifier());
18801                    mSettings.writeKernelMappingLPr(ps);
18802                }
18803            } else {
18804                // This is a system app, so we assume that the
18805                // other users still have this package installed, so all
18806                // we need to do is clear this user's data and save that
18807                // it is uninstalled.
18808                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18809                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18810                    return false;
18811                }
18812                scheduleWritePackageRestrictionsLocked(user);
18813                return true;
18814            }
18815        }
18816
18817        // If we are deleting a composite package for all users, keep track
18818        // of result for each child.
18819        if (ps.childPackageNames != null && outInfo != null) {
18820            synchronized (mPackages) {
18821                final int childCount = ps.childPackageNames.size();
18822                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18823                for (int i = 0; i < childCount; i++) {
18824                    String childPackageName = ps.childPackageNames.get(i);
18825                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18826                    childInfo.removedPackage = childPackageName;
18827                    childInfo.installerPackageName = ps.installerPackageName;
18828                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18829                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18830                    if (childPs != null) {
18831                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18832                    }
18833                }
18834            }
18835        }
18836
18837        boolean ret = false;
18838        if (isSystemApp(ps)) {
18839            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18840            // When an updated system application is deleted we delete the existing resources
18841            // as well and fall back to existing code in system partition
18842            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18843        } else {
18844            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18845            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18846                    outInfo, writeSettings, replacingPackage);
18847        }
18848
18849        // Take a note whether we deleted the package for all users
18850        if (outInfo != null) {
18851            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18852            if (outInfo.removedChildPackages != null) {
18853                synchronized (mPackages) {
18854                    final int childCount = outInfo.removedChildPackages.size();
18855                    for (int i = 0; i < childCount; i++) {
18856                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18857                        if (childInfo != null) {
18858                            childInfo.removedForAllUsers = mPackages.get(
18859                                    childInfo.removedPackage) == null;
18860                        }
18861                    }
18862                }
18863            }
18864            // If we uninstalled an update to a system app there may be some
18865            // child packages that appeared as they are declared in the system
18866            // app but were not declared in the update.
18867            if (isSystemApp(ps)) {
18868                synchronized (mPackages) {
18869                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18870                    final int childCount = (updatedPs.childPackageNames != null)
18871                            ? updatedPs.childPackageNames.size() : 0;
18872                    for (int i = 0; i < childCount; i++) {
18873                        String childPackageName = updatedPs.childPackageNames.get(i);
18874                        if (outInfo.removedChildPackages == null
18875                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18876                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18877                            if (childPs == null) {
18878                                continue;
18879                            }
18880                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18881                            installRes.name = childPackageName;
18882                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18883                            installRes.pkg = mPackages.get(childPackageName);
18884                            installRes.uid = childPs.pkg.applicationInfo.uid;
18885                            if (outInfo.appearedChildPackages == null) {
18886                                outInfo.appearedChildPackages = new ArrayMap<>();
18887                            }
18888                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18889                        }
18890                    }
18891                }
18892            }
18893        }
18894
18895        return ret;
18896    }
18897
18898    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18899        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18900                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18901        for (int nextUserId : userIds) {
18902            if (DEBUG_REMOVE) {
18903                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18904            }
18905            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18906                    false /*installed*/,
18907                    true /*stopped*/,
18908                    true /*notLaunched*/,
18909                    false /*hidden*/,
18910                    false /*suspended*/,
18911                    null, /*suspendingPackage*/
18912                    null, /*dialogMessage*/
18913                    null, /*suspendedAppExtras*/
18914                    null, /*suspendedLauncherExtras*/
18915                    false /*instantApp*/,
18916                    false /*virtualPreload*/,
18917                    null /*lastDisableAppCaller*/,
18918                    null /*enabledComponents*/,
18919                    null /*disabledComponents*/,
18920                    ps.readUserState(nextUserId).domainVerificationStatus,
18921                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18922                    null /*harmfulAppWarning*/);
18923        }
18924        mSettings.writeKernelMappingLPr(ps);
18925    }
18926
18927    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18928            PackageRemovedInfo outInfo) {
18929        final PackageParser.Package pkg;
18930        synchronized (mPackages) {
18931            pkg = mPackages.get(ps.name);
18932        }
18933
18934        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18935                : new int[] {userId};
18936        for (int nextUserId : userIds) {
18937            if (DEBUG_REMOVE) {
18938                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18939                        + nextUserId);
18940            }
18941
18942            destroyAppDataLIF(pkg, userId,
18943                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18944            destroyAppProfilesLIF(pkg, userId);
18945            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18946            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18947            schedulePackageCleaning(ps.name, nextUserId, false);
18948            synchronized (mPackages) {
18949                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18950                    scheduleWritePackageRestrictionsLocked(nextUserId);
18951                }
18952                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18953            }
18954        }
18955
18956        if (outInfo != null) {
18957            outInfo.removedPackage = ps.name;
18958            outInfo.installerPackageName = ps.installerPackageName;
18959            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18960            outInfo.removedAppId = ps.appId;
18961            outInfo.removedUsers = userIds;
18962            outInfo.broadcastUsers = userIds;
18963        }
18964
18965        return true;
18966    }
18967
18968    private final class ClearStorageConnection implements ServiceConnection {
18969        IMediaContainerService mContainerService;
18970
18971        @Override
18972        public void onServiceConnected(ComponentName name, IBinder service) {
18973            synchronized (this) {
18974                mContainerService = IMediaContainerService.Stub
18975                        .asInterface(Binder.allowBlocking(service));
18976                notifyAll();
18977            }
18978        }
18979
18980        @Override
18981        public void onServiceDisconnected(ComponentName name) {
18982        }
18983    }
18984
18985    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18986        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18987
18988        final boolean mounted;
18989        if (Environment.isExternalStorageEmulated()) {
18990            mounted = true;
18991        } else {
18992            final String status = Environment.getExternalStorageState();
18993
18994            mounted = status.equals(Environment.MEDIA_MOUNTED)
18995                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18996        }
18997
18998        if (!mounted) {
18999            return;
19000        }
19001
19002        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19003        int[] users;
19004        if (userId == UserHandle.USER_ALL) {
19005            users = sUserManager.getUserIds();
19006        } else {
19007            users = new int[] { userId };
19008        }
19009        final ClearStorageConnection conn = new ClearStorageConnection();
19010        if (mContext.bindServiceAsUser(
19011                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19012            try {
19013                for (int curUser : users) {
19014                    long timeout = SystemClock.uptimeMillis() + 5000;
19015                    synchronized (conn) {
19016                        long now;
19017                        while (conn.mContainerService == null &&
19018                                (now = SystemClock.uptimeMillis()) < timeout) {
19019                            try {
19020                                conn.wait(timeout - now);
19021                            } catch (InterruptedException e) {
19022                            }
19023                        }
19024                    }
19025                    if (conn.mContainerService == null) {
19026                        return;
19027                    }
19028
19029                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19030                    clearDirectory(conn.mContainerService,
19031                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19032                    if (allData) {
19033                        clearDirectory(conn.mContainerService,
19034                                userEnv.buildExternalStorageAppDataDirs(packageName));
19035                        clearDirectory(conn.mContainerService,
19036                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19037                    }
19038                }
19039            } finally {
19040                mContext.unbindService(conn);
19041            }
19042        }
19043    }
19044
19045    @Override
19046    public void clearApplicationProfileData(String packageName) {
19047        enforceSystemOrRoot("Only the system can clear all profile data");
19048
19049        final PackageParser.Package pkg;
19050        synchronized (mPackages) {
19051            pkg = mPackages.get(packageName);
19052        }
19053
19054        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19055            synchronized (mInstallLock) {
19056                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19057            }
19058        }
19059    }
19060
19061    @Override
19062    public void clearApplicationUserData(final String packageName,
19063            final IPackageDataObserver observer, final int userId) {
19064        mContext.enforceCallingOrSelfPermission(
19065                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19066
19067        final int callingUid = Binder.getCallingUid();
19068        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19069                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19070
19071        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19072        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19073        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19074            throw new SecurityException("Cannot clear data for a protected package: "
19075                    + packageName);
19076        }
19077        // Queue up an async operation since the package deletion may take a little while.
19078        mHandler.post(new Runnable() {
19079            public void run() {
19080                mHandler.removeCallbacks(this);
19081                final boolean succeeded;
19082                if (!filterApp) {
19083                    try (PackageFreezer freezer = freezePackage(packageName,
19084                            "clearApplicationUserData")) {
19085                        synchronized (mInstallLock) {
19086                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19087                        }
19088                        clearExternalStorageDataSync(packageName, userId, true);
19089                        synchronized (mPackages) {
19090                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19091                                    packageName, userId);
19092                        }
19093                    }
19094                    if (succeeded) {
19095                        // invoke DeviceStorageMonitor's update method to clear any notifications
19096                        DeviceStorageMonitorInternal dsm = LocalServices
19097                                .getService(DeviceStorageMonitorInternal.class);
19098                        if (dsm != null) {
19099                            dsm.checkMemory();
19100                        }
19101                    }
19102                } else {
19103                    succeeded = false;
19104                }
19105                if (observer != null) {
19106                    try {
19107                        observer.onRemoveCompleted(packageName, succeeded);
19108                    } catch (RemoteException e) {
19109                        Log.i(TAG, "Observer no longer exists.");
19110                    }
19111                } //end if observer
19112            } //end run
19113        });
19114    }
19115
19116    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19117        if (packageName == null) {
19118            Slog.w(TAG, "Attempt to delete null packageName.");
19119            return false;
19120        }
19121
19122        // Try finding details about the requested package
19123        PackageParser.Package pkg;
19124        synchronized (mPackages) {
19125            pkg = mPackages.get(packageName);
19126            if (pkg == null) {
19127                final PackageSetting ps = mSettings.mPackages.get(packageName);
19128                if (ps != null) {
19129                    pkg = ps.pkg;
19130                }
19131            }
19132
19133            if (pkg == null) {
19134                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19135                return false;
19136            }
19137
19138            PackageSetting ps = (PackageSetting) pkg.mExtras;
19139            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19140        }
19141
19142        clearAppDataLIF(pkg, userId,
19143                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19144
19145        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19146        removeKeystoreDataIfNeeded(userId, appId);
19147
19148        UserManagerInternal umInternal = getUserManagerInternal();
19149        final int flags;
19150        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19151            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19152        } else if (umInternal.isUserRunning(userId)) {
19153            flags = StorageManager.FLAG_STORAGE_DE;
19154        } else {
19155            flags = 0;
19156        }
19157        prepareAppDataContentsLIF(pkg, userId, flags);
19158
19159        return true;
19160    }
19161
19162    /**
19163     * Reverts user permission state changes (permissions and flags) in
19164     * all packages for a given user.
19165     *
19166     * @param userId The device user for which to do a reset.
19167     */
19168    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19169        final int packageCount = mPackages.size();
19170        for (int i = 0; i < packageCount; i++) {
19171            PackageParser.Package pkg = mPackages.valueAt(i);
19172            PackageSetting ps = (PackageSetting) pkg.mExtras;
19173            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19174        }
19175    }
19176
19177    private void resetNetworkPolicies(int userId) {
19178        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19179    }
19180
19181    /**
19182     * Reverts user permission state changes (permissions and flags).
19183     *
19184     * @param ps The package for which to reset.
19185     * @param userId The device user for which to do a reset.
19186     */
19187    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19188            final PackageSetting ps, final int userId) {
19189        if (ps.pkg == null) {
19190            return;
19191        }
19192
19193        // These are flags that can change base on user actions.
19194        final int userSettableMask = FLAG_PERMISSION_USER_SET
19195                | FLAG_PERMISSION_USER_FIXED
19196                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19197                | FLAG_PERMISSION_REVIEW_REQUIRED;
19198
19199        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19200                | FLAG_PERMISSION_POLICY_FIXED;
19201
19202        boolean writeInstallPermissions = false;
19203        boolean writeRuntimePermissions = false;
19204
19205        final int permissionCount = ps.pkg.requestedPermissions.size();
19206        for (int i = 0; i < permissionCount; i++) {
19207            final String permName = ps.pkg.requestedPermissions.get(i);
19208            final BasePermission bp =
19209                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19210            if (bp == null) {
19211                continue;
19212            }
19213
19214            // If shared user we just reset the state to which only this app contributed.
19215            if (ps.sharedUser != null) {
19216                boolean used = false;
19217                final int packageCount = ps.sharedUser.packages.size();
19218                for (int j = 0; j < packageCount; j++) {
19219                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19220                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19221                            && pkg.pkg.requestedPermissions.contains(permName)) {
19222                        used = true;
19223                        break;
19224                    }
19225                }
19226                if (used) {
19227                    continue;
19228                }
19229            }
19230
19231            final PermissionsState permissionsState = ps.getPermissionsState();
19232
19233            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19234
19235            // Always clear the user settable flags.
19236            final boolean hasInstallState =
19237                    permissionsState.getInstallPermissionState(permName) != null;
19238            // If permission review is enabled and this is a legacy app, mark the
19239            // permission as requiring a review as this is the initial state.
19240            int flags = 0;
19241            if (mSettings.mPermissions.mPermissionReviewRequired
19242                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19243                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19244            }
19245            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19246                if (hasInstallState) {
19247                    writeInstallPermissions = true;
19248                } else {
19249                    writeRuntimePermissions = true;
19250                }
19251            }
19252
19253            // Below is only runtime permission handling.
19254            if (!bp.isRuntime()) {
19255                continue;
19256            }
19257
19258            // Never clobber system or policy.
19259            if ((oldFlags & policyOrSystemFlags) != 0) {
19260                continue;
19261            }
19262
19263            // If this permission was granted by default, make sure it is.
19264            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19265                if (permissionsState.grantRuntimePermission(bp, userId)
19266                        != PERMISSION_OPERATION_FAILURE) {
19267                    writeRuntimePermissions = true;
19268                }
19269            // If permission review is enabled the permissions for a legacy apps
19270            // are represented as constantly granted runtime ones, so don't revoke.
19271            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19272                // Otherwise, reset the permission.
19273                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19274                switch (revokeResult) {
19275                    case PERMISSION_OPERATION_SUCCESS:
19276                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19277                        writeRuntimePermissions = true;
19278                        final int appId = ps.appId;
19279                        mHandler.post(new Runnable() {
19280                            @Override
19281                            public void run() {
19282                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19283                            }
19284                        });
19285                    } break;
19286                }
19287            }
19288        }
19289
19290        // Synchronously write as we are taking permissions away.
19291        if (writeRuntimePermissions) {
19292            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19293        }
19294
19295        // Synchronously write as we are taking permissions away.
19296        if (writeInstallPermissions) {
19297            mSettings.writeLPr();
19298        }
19299    }
19300
19301    /**
19302     * Remove entries from the keystore daemon. Will only remove it if the
19303     * {@code appId} is valid.
19304     */
19305    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19306        if (appId < 0) {
19307            return;
19308        }
19309
19310        final KeyStore keyStore = KeyStore.getInstance();
19311        if (keyStore != null) {
19312            if (userId == UserHandle.USER_ALL) {
19313                for (final int individual : sUserManager.getUserIds()) {
19314                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19315                }
19316            } else {
19317                keyStore.clearUid(UserHandle.getUid(userId, appId));
19318            }
19319        } else {
19320            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19321        }
19322    }
19323
19324    @Override
19325    public void deleteApplicationCacheFiles(final String packageName,
19326            final IPackageDataObserver observer) {
19327        final int userId = UserHandle.getCallingUserId();
19328        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19329    }
19330
19331    @Override
19332    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19333            final IPackageDataObserver observer) {
19334        final int callingUid = Binder.getCallingUid();
19335        if (mContext.checkCallingOrSelfPermission(
19336                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19337                != PackageManager.PERMISSION_GRANTED) {
19338            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19339            if (mContext.checkCallingOrSelfPermission(
19340                    android.Manifest.permission.DELETE_CACHE_FILES)
19341                    == PackageManager.PERMISSION_GRANTED) {
19342                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19343                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19344                        ", silently ignoring");
19345                return;
19346            }
19347            mContext.enforceCallingOrSelfPermission(
19348                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19349        }
19350        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19351                /* requireFullPermission= */ true, /* checkShell= */ false,
19352                "delete application cache files");
19353        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19354                android.Manifest.permission.ACCESS_INSTANT_APPS);
19355
19356        final PackageParser.Package pkg;
19357        synchronized (mPackages) {
19358            pkg = mPackages.get(packageName);
19359        }
19360
19361        // Queue up an async operation since the package deletion may take a little while.
19362        mHandler.post(new Runnable() {
19363            public void run() {
19364                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19365                boolean doClearData = true;
19366                if (ps != null) {
19367                    final boolean targetIsInstantApp =
19368                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19369                    doClearData = !targetIsInstantApp
19370                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19371                }
19372                if (doClearData) {
19373                    synchronized (mInstallLock) {
19374                        final int flags = StorageManager.FLAG_STORAGE_DE
19375                                | StorageManager.FLAG_STORAGE_CE;
19376                        // We're only clearing cache files, so we don't care if the
19377                        // app is unfrozen and still able to run
19378                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19379                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19380                    }
19381                    clearExternalStorageDataSync(packageName, userId, false);
19382                }
19383                if (observer != null) {
19384                    try {
19385                        observer.onRemoveCompleted(packageName, true);
19386                    } catch (RemoteException e) {
19387                        Log.i(TAG, "Observer no longer exists.");
19388                    }
19389                }
19390            }
19391        });
19392    }
19393
19394    @Override
19395    public void getPackageSizeInfo(final String packageName, int userHandle,
19396            final IPackageStatsObserver observer) {
19397        throw new UnsupportedOperationException(
19398                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19399    }
19400
19401    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19402        final PackageSetting ps;
19403        synchronized (mPackages) {
19404            ps = mSettings.mPackages.get(packageName);
19405            if (ps == null) {
19406                Slog.w(TAG, "Failed to find settings for " + packageName);
19407                return false;
19408            }
19409        }
19410
19411        final String[] packageNames = { packageName };
19412        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19413        final String[] codePaths = { ps.codePathString };
19414
19415        try {
19416            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19417                    ps.appId, ceDataInodes, codePaths, stats);
19418
19419            // For now, ignore code size of packages on system partition
19420            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19421                stats.codeSize = 0;
19422            }
19423
19424            // External clients expect these to be tracked separately
19425            stats.dataSize -= stats.cacheSize;
19426
19427        } catch (InstallerException e) {
19428            Slog.w(TAG, String.valueOf(e));
19429            return false;
19430        }
19431
19432        return true;
19433    }
19434
19435    private int getUidTargetSdkVersionLockedLPr(int uid) {
19436        Object obj = mSettings.getUserIdLPr(uid);
19437        if (obj instanceof SharedUserSetting) {
19438            final SharedUserSetting sus = (SharedUserSetting) obj;
19439            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19440            final Iterator<PackageSetting> it = sus.packages.iterator();
19441            while (it.hasNext()) {
19442                final PackageSetting ps = it.next();
19443                if (ps.pkg != null) {
19444                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19445                    if (v < vers) vers = v;
19446                }
19447            }
19448            return vers;
19449        } else if (obj instanceof PackageSetting) {
19450            final PackageSetting ps = (PackageSetting) obj;
19451            if (ps.pkg != null) {
19452                return ps.pkg.applicationInfo.targetSdkVersion;
19453            }
19454        }
19455        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19456    }
19457
19458    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19459        final PackageParser.Package p = mPackages.get(packageName);
19460        if (p != null) {
19461            return p.applicationInfo.targetSdkVersion;
19462        }
19463        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19464    }
19465
19466    @Override
19467    public void addPreferredActivity(IntentFilter filter, int match,
19468            ComponentName[] set, ComponentName activity, int userId) {
19469        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19470                "Adding preferred");
19471    }
19472
19473    private void addPreferredActivityInternal(IntentFilter filter, int match,
19474            ComponentName[] set, ComponentName activity, boolean always, int userId,
19475            String opname) {
19476        // writer
19477        int callingUid = Binder.getCallingUid();
19478        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19479                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19480        if (filter.countActions() == 0) {
19481            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19482            return;
19483        }
19484        synchronized (mPackages) {
19485            if (mContext.checkCallingOrSelfPermission(
19486                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19487                    != PackageManager.PERMISSION_GRANTED) {
19488                if (getUidTargetSdkVersionLockedLPr(callingUid)
19489                        < Build.VERSION_CODES.FROYO) {
19490                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19491                            + callingUid);
19492                    return;
19493                }
19494                mContext.enforceCallingOrSelfPermission(
19495                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19496            }
19497
19498            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19499            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19500                    + userId + ":");
19501            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19502            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19503            scheduleWritePackageRestrictionsLocked(userId);
19504            postPreferredActivityChangedBroadcast(userId);
19505        }
19506    }
19507
19508    private void postPreferredActivityChangedBroadcast(int userId) {
19509        mHandler.post(() -> {
19510            final IActivityManager am = ActivityManager.getService();
19511            if (am == null) {
19512                return;
19513            }
19514
19515            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19516            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19517            try {
19518                am.broadcastIntent(null, intent, null, null,
19519                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19520                        null, false, false, userId);
19521            } catch (RemoteException e) {
19522            }
19523        });
19524    }
19525
19526    @Override
19527    public void replacePreferredActivity(IntentFilter filter, int match,
19528            ComponentName[] set, ComponentName activity, int userId) {
19529        if (filter.countActions() != 1) {
19530            throw new IllegalArgumentException(
19531                    "replacePreferredActivity expects filter to have only 1 action.");
19532        }
19533        if (filter.countDataAuthorities() != 0
19534                || filter.countDataPaths() != 0
19535                || filter.countDataSchemes() > 1
19536                || filter.countDataTypes() != 0) {
19537            throw new IllegalArgumentException(
19538                    "replacePreferredActivity expects filter to have no data authorities, " +
19539                    "paths, or types; and at most one scheme.");
19540        }
19541
19542        final int callingUid = Binder.getCallingUid();
19543        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19544                true /* requireFullPermission */, false /* checkShell */,
19545                "replace preferred activity");
19546        synchronized (mPackages) {
19547            if (mContext.checkCallingOrSelfPermission(
19548                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19549                    != PackageManager.PERMISSION_GRANTED) {
19550                if (getUidTargetSdkVersionLockedLPr(callingUid)
19551                        < Build.VERSION_CODES.FROYO) {
19552                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19553                            + Binder.getCallingUid());
19554                    return;
19555                }
19556                mContext.enforceCallingOrSelfPermission(
19557                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19558            }
19559
19560            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19561            if (pir != null) {
19562                // Get all of the existing entries that exactly match this filter.
19563                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19564                if (existing != null && existing.size() == 1) {
19565                    PreferredActivity cur = existing.get(0);
19566                    if (DEBUG_PREFERRED) {
19567                        Slog.i(TAG, "Checking replace of preferred:");
19568                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19569                        if (!cur.mPref.mAlways) {
19570                            Slog.i(TAG, "  -- CUR; not mAlways!");
19571                        } else {
19572                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19573                            Slog.i(TAG, "  -- CUR: mSet="
19574                                    + Arrays.toString(cur.mPref.mSetComponents));
19575                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19576                            Slog.i(TAG, "  -- NEW: mMatch="
19577                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19578                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19579                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19580                        }
19581                    }
19582                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19583                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19584                            && cur.mPref.sameSet(set)) {
19585                        // Setting the preferred activity to what it happens to be already
19586                        if (DEBUG_PREFERRED) {
19587                            Slog.i(TAG, "Replacing with same preferred activity "
19588                                    + cur.mPref.mShortComponent + " for user "
19589                                    + userId + ":");
19590                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19591                        }
19592                        return;
19593                    }
19594                }
19595
19596                if (existing != null) {
19597                    if (DEBUG_PREFERRED) {
19598                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19599                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19600                    }
19601                    for (int i = 0; i < existing.size(); i++) {
19602                        PreferredActivity pa = existing.get(i);
19603                        if (DEBUG_PREFERRED) {
19604                            Slog.i(TAG, "Removing existing preferred activity "
19605                                    + pa.mPref.mComponent + ":");
19606                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19607                        }
19608                        pir.removeFilter(pa);
19609                    }
19610                }
19611            }
19612            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19613                    "Replacing preferred");
19614        }
19615    }
19616
19617    @Override
19618    public void clearPackagePreferredActivities(String packageName) {
19619        final int callingUid = Binder.getCallingUid();
19620        if (getInstantAppPackageName(callingUid) != null) {
19621            return;
19622        }
19623        // writer
19624        synchronized (mPackages) {
19625            PackageParser.Package pkg = mPackages.get(packageName);
19626            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19627                if (mContext.checkCallingOrSelfPermission(
19628                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19629                        != PackageManager.PERMISSION_GRANTED) {
19630                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19631                            < Build.VERSION_CODES.FROYO) {
19632                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19633                                + callingUid);
19634                        return;
19635                    }
19636                    mContext.enforceCallingOrSelfPermission(
19637                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19638                }
19639            }
19640            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19641            if (ps != null
19642                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19643                return;
19644            }
19645            int user = UserHandle.getCallingUserId();
19646            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19647                scheduleWritePackageRestrictionsLocked(user);
19648            }
19649        }
19650    }
19651
19652    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19653    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19654        ArrayList<PreferredActivity> removed = null;
19655        boolean changed = false;
19656        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19657            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19658            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19659            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19660                continue;
19661            }
19662            Iterator<PreferredActivity> it = pir.filterIterator();
19663            while (it.hasNext()) {
19664                PreferredActivity pa = it.next();
19665                // Mark entry for removal only if it matches the package name
19666                // and the entry is of type "always".
19667                if (packageName == null ||
19668                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19669                                && pa.mPref.mAlways)) {
19670                    if (removed == null) {
19671                        removed = new ArrayList<PreferredActivity>();
19672                    }
19673                    removed.add(pa);
19674                }
19675            }
19676            if (removed != null) {
19677                for (int j=0; j<removed.size(); j++) {
19678                    PreferredActivity pa = removed.get(j);
19679                    pir.removeFilter(pa);
19680                }
19681                changed = true;
19682            }
19683        }
19684        if (changed) {
19685            postPreferredActivityChangedBroadcast(userId);
19686        }
19687        return changed;
19688    }
19689
19690    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19691    private void clearIntentFilterVerificationsLPw(int userId) {
19692        final int packageCount = mPackages.size();
19693        for (int i = 0; i < packageCount; i++) {
19694            PackageParser.Package pkg = mPackages.valueAt(i);
19695            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19696        }
19697    }
19698
19699    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19700    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19701        if (userId == UserHandle.USER_ALL) {
19702            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19703                    sUserManager.getUserIds())) {
19704                for (int oneUserId : sUserManager.getUserIds()) {
19705                    scheduleWritePackageRestrictionsLocked(oneUserId);
19706                }
19707            }
19708        } else {
19709            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19710                scheduleWritePackageRestrictionsLocked(userId);
19711            }
19712        }
19713    }
19714
19715    /** Clears state for all users, and touches intent filter verification policy */
19716    void clearDefaultBrowserIfNeeded(String packageName) {
19717        for (int oneUserId : sUserManager.getUserIds()) {
19718            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19719        }
19720    }
19721
19722    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19723        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19724        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19725            if (packageName.equals(defaultBrowserPackageName)) {
19726                setDefaultBrowserPackageName(null, userId);
19727            }
19728        }
19729    }
19730
19731    @Override
19732    public void resetApplicationPreferences(int userId) {
19733        mContext.enforceCallingOrSelfPermission(
19734                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19735        final long identity = Binder.clearCallingIdentity();
19736        // writer
19737        try {
19738            synchronized (mPackages) {
19739                clearPackagePreferredActivitiesLPw(null, userId);
19740                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19741                // TODO: We have to reset the default SMS and Phone. This requires
19742                // significant refactoring to keep all default apps in the package
19743                // manager (cleaner but more work) or have the services provide
19744                // callbacks to the package manager to request a default app reset.
19745                applyFactoryDefaultBrowserLPw(userId);
19746                clearIntentFilterVerificationsLPw(userId);
19747                primeDomainVerificationsLPw(userId);
19748                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19749                scheduleWritePackageRestrictionsLocked(userId);
19750            }
19751            resetNetworkPolicies(userId);
19752        } finally {
19753            Binder.restoreCallingIdentity(identity);
19754        }
19755    }
19756
19757    @Override
19758    public int getPreferredActivities(List<IntentFilter> outFilters,
19759            List<ComponentName> outActivities, String packageName) {
19760        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19761            return 0;
19762        }
19763        int num = 0;
19764        final int userId = UserHandle.getCallingUserId();
19765        // reader
19766        synchronized (mPackages) {
19767            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19768            if (pir != null) {
19769                final Iterator<PreferredActivity> it = pir.filterIterator();
19770                while (it.hasNext()) {
19771                    final PreferredActivity pa = it.next();
19772                    if (packageName == null
19773                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19774                                    && pa.mPref.mAlways)) {
19775                        if (outFilters != null) {
19776                            outFilters.add(new IntentFilter(pa));
19777                        }
19778                        if (outActivities != null) {
19779                            outActivities.add(pa.mPref.mComponent);
19780                        }
19781                    }
19782                }
19783            }
19784        }
19785
19786        return num;
19787    }
19788
19789    @Override
19790    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19791            int userId) {
19792        int callingUid = Binder.getCallingUid();
19793        if (callingUid != Process.SYSTEM_UID) {
19794            throw new SecurityException(
19795                    "addPersistentPreferredActivity can only be run by the system");
19796        }
19797        if (filter.countActions() == 0) {
19798            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19799            return;
19800        }
19801        synchronized (mPackages) {
19802            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19803                    ":");
19804            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19805            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19806                    new PersistentPreferredActivity(filter, activity));
19807            scheduleWritePackageRestrictionsLocked(userId);
19808            postPreferredActivityChangedBroadcast(userId);
19809        }
19810    }
19811
19812    @Override
19813    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19814        int callingUid = Binder.getCallingUid();
19815        if (callingUid != Process.SYSTEM_UID) {
19816            throw new SecurityException(
19817                    "clearPackagePersistentPreferredActivities can only be run by the system");
19818        }
19819        ArrayList<PersistentPreferredActivity> removed = null;
19820        boolean changed = false;
19821        synchronized (mPackages) {
19822            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19823                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19824                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19825                        .valueAt(i);
19826                if (userId != thisUserId) {
19827                    continue;
19828                }
19829                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19830                while (it.hasNext()) {
19831                    PersistentPreferredActivity ppa = it.next();
19832                    // Mark entry for removal only if it matches the package name.
19833                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19834                        if (removed == null) {
19835                            removed = new ArrayList<PersistentPreferredActivity>();
19836                        }
19837                        removed.add(ppa);
19838                    }
19839                }
19840                if (removed != null) {
19841                    for (int j=0; j<removed.size(); j++) {
19842                        PersistentPreferredActivity ppa = removed.get(j);
19843                        ppir.removeFilter(ppa);
19844                    }
19845                    changed = true;
19846                }
19847            }
19848
19849            if (changed) {
19850                scheduleWritePackageRestrictionsLocked(userId);
19851                postPreferredActivityChangedBroadcast(userId);
19852            }
19853        }
19854    }
19855
19856    /**
19857     * Common machinery for picking apart a restored XML blob and passing
19858     * it to a caller-supplied functor to be applied to the running system.
19859     */
19860    private void restoreFromXml(XmlPullParser parser, int userId,
19861            String expectedStartTag, BlobXmlRestorer functor)
19862            throws IOException, XmlPullParserException {
19863        int type;
19864        while ((type = parser.next()) != XmlPullParser.START_TAG
19865                && type != XmlPullParser.END_DOCUMENT) {
19866        }
19867        if (type != XmlPullParser.START_TAG) {
19868            // oops didn't find a start tag?!
19869            if (DEBUG_BACKUP) {
19870                Slog.e(TAG, "Didn't find start tag during restore");
19871            }
19872            return;
19873        }
19874Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19875        // this is supposed to be TAG_PREFERRED_BACKUP
19876        if (!expectedStartTag.equals(parser.getName())) {
19877            if (DEBUG_BACKUP) {
19878                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19879            }
19880            return;
19881        }
19882
19883        // skip interfering stuff, then we're aligned with the backing implementation
19884        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19885Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19886        functor.apply(parser, userId);
19887    }
19888
19889    private interface BlobXmlRestorer {
19890        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19891    }
19892
19893    /**
19894     * Non-Binder method, support for the backup/restore mechanism: write the
19895     * full set of preferred activities in its canonical XML format.  Returns the
19896     * XML output as a byte array, or null if there is none.
19897     */
19898    @Override
19899    public byte[] getPreferredActivityBackup(int userId) {
19900        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19901            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19902        }
19903
19904        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19905        try {
19906            final XmlSerializer serializer = new FastXmlSerializer();
19907            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19908            serializer.startDocument(null, true);
19909            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19910
19911            synchronized (mPackages) {
19912                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19913            }
19914
19915            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19916            serializer.endDocument();
19917            serializer.flush();
19918        } catch (Exception e) {
19919            if (DEBUG_BACKUP) {
19920                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19921            }
19922            return null;
19923        }
19924
19925        return dataStream.toByteArray();
19926    }
19927
19928    @Override
19929    public void restorePreferredActivities(byte[] backup, int userId) {
19930        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19931            throw new SecurityException("Only the system may call restorePreferredActivities()");
19932        }
19933
19934        try {
19935            final XmlPullParser parser = Xml.newPullParser();
19936            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19937            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19938                    new BlobXmlRestorer() {
19939                        @Override
19940                        public void apply(XmlPullParser parser, int userId)
19941                                throws XmlPullParserException, IOException {
19942                            synchronized (mPackages) {
19943                                mSettings.readPreferredActivitiesLPw(parser, userId);
19944                            }
19945                        }
19946                    } );
19947        } catch (Exception e) {
19948            if (DEBUG_BACKUP) {
19949                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19950            }
19951        }
19952    }
19953
19954    /**
19955     * Non-Binder method, support for the backup/restore mechanism: write the
19956     * default browser (etc) settings in its canonical XML format.  Returns the default
19957     * browser XML representation as a byte array, or null if there is none.
19958     */
19959    @Override
19960    public byte[] getDefaultAppsBackup(int userId) {
19961        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19962            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19963        }
19964
19965        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19966        try {
19967            final XmlSerializer serializer = new FastXmlSerializer();
19968            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19969            serializer.startDocument(null, true);
19970            serializer.startTag(null, TAG_DEFAULT_APPS);
19971
19972            synchronized (mPackages) {
19973                mSettings.writeDefaultAppsLPr(serializer, userId);
19974            }
19975
19976            serializer.endTag(null, TAG_DEFAULT_APPS);
19977            serializer.endDocument();
19978            serializer.flush();
19979        } catch (Exception e) {
19980            if (DEBUG_BACKUP) {
19981                Slog.e(TAG, "Unable to write default apps for backup", e);
19982            }
19983            return null;
19984        }
19985
19986        return dataStream.toByteArray();
19987    }
19988
19989    @Override
19990    public void restoreDefaultApps(byte[] backup, int userId) {
19991        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19992            throw new SecurityException("Only the system may call restoreDefaultApps()");
19993        }
19994
19995        try {
19996            final XmlPullParser parser = Xml.newPullParser();
19997            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19998            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19999                    new BlobXmlRestorer() {
20000                        @Override
20001                        public void apply(XmlPullParser parser, int userId)
20002                                throws XmlPullParserException, IOException {
20003                            synchronized (mPackages) {
20004                                mSettings.readDefaultAppsLPw(parser, userId);
20005                            }
20006                        }
20007                    } );
20008        } catch (Exception e) {
20009            if (DEBUG_BACKUP) {
20010                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20011            }
20012        }
20013    }
20014
20015    @Override
20016    public byte[] getIntentFilterVerificationBackup(int userId) {
20017        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20018            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20019        }
20020
20021        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20022        try {
20023            final XmlSerializer serializer = new FastXmlSerializer();
20024            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20025            serializer.startDocument(null, true);
20026            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20027
20028            synchronized (mPackages) {
20029                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20030            }
20031
20032            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20033            serializer.endDocument();
20034            serializer.flush();
20035        } catch (Exception e) {
20036            if (DEBUG_BACKUP) {
20037                Slog.e(TAG, "Unable to write default apps for backup", e);
20038            }
20039            return null;
20040        }
20041
20042        return dataStream.toByteArray();
20043    }
20044
20045    @Override
20046    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20047        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20048            throw new SecurityException("Only the system may call restorePreferredActivities()");
20049        }
20050
20051        try {
20052            final XmlPullParser parser = Xml.newPullParser();
20053            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20054            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20055                    new BlobXmlRestorer() {
20056                        @Override
20057                        public void apply(XmlPullParser parser, int userId)
20058                                throws XmlPullParserException, IOException {
20059                            synchronized (mPackages) {
20060                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20061                                mSettings.writeLPr();
20062                            }
20063                        }
20064                    } );
20065        } catch (Exception e) {
20066            if (DEBUG_BACKUP) {
20067                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20068            }
20069        }
20070    }
20071
20072    @Override
20073    public byte[] getPermissionGrantBackup(int userId) {
20074        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20075            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20076        }
20077
20078        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20079        try {
20080            final XmlSerializer serializer = new FastXmlSerializer();
20081            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20082            serializer.startDocument(null, true);
20083            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20084
20085            synchronized (mPackages) {
20086                serializeRuntimePermissionGrantsLPr(serializer, userId);
20087            }
20088
20089            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20090            serializer.endDocument();
20091            serializer.flush();
20092        } catch (Exception e) {
20093            if (DEBUG_BACKUP) {
20094                Slog.e(TAG, "Unable to write default apps for backup", e);
20095            }
20096            return null;
20097        }
20098
20099        return dataStream.toByteArray();
20100    }
20101
20102    @Override
20103    public void restorePermissionGrants(byte[] backup, int userId) {
20104        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20105            throw new SecurityException("Only the system may call restorePermissionGrants()");
20106        }
20107
20108        try {
20109            final XmlPullParser parser = Xml.newPullParser();
20110            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20111            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20112                    new BlobXmlRestorer() {
20113                        @Override
20114                        public void apply(XmlPullParser parser, int userId)
20115                                throws XmlPullParserException, IOException {
20116                            synchronized (mPackages) {
20117                                processRestoredPermissionGrantsLPr(parser, userId);
20118                            }
20119                        }
20120                    } );
20121        } catch (Exception e) {
20122            if (DEBUG_BACKUP) {
20123                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20124            }
20125        }
20126    }
20127
20128    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20129            throws IOException {
20130        serializer.startTag(null, TAG_ALL_GRANTS);
20131
20132        final int N = mSettings.mPackages.size();
20133        for (int i = 0; i < N; i++) {
20134            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20135            boolean pkgGrantsKnown = false;
20136
20137            PermissionsState packagePerms = ps.getPermissionsState();
20138
20139            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20140                final int grantFlags = state.getFlags();
20141                // only look at grants that are not system/policy fixed
20142                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20143                    final boolean isGranted = state.isGranted();
20144                    // And only back up the user-twiddled state bits
20145                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20146                        final String packageName = mSettings.mPackages.keyAt(i);
20147                        if (!pkgGrantsKnown) {
20148                            serializer.startTag(null, TAG_GRANT);
20149                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20150                            pkgGrantsKnown = true;
20151                        }
20152
20153                        final boolean userSet =
20154                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20155                        final boolean userFixed =
20156                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20157                        final boolean revoke =
20158                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20159
20160                        serializer.startTag(null, TAG_PERMISSION);
20161                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20162                        if (isGranted) {
20163                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20164                        }
20165                        if (userSet) {
20166                            serializer.attribute(null, ATTR_USER_SET, "true");
20167                        }
20168                        if (userFixed) {
20169                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20170                        }
20171                        if (revoke) {
20172                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20173                        }
20174                        serializer.endTag(null, TAG_PERMISSION);
20175                    }
20176                }
20177            }
20178
20179            if (pkgGrantsKnown) {
20180                serializer.endTag(null, TAG_GRANT);
20181            }
20182        }
20183
20184        serializer.endTag(null, TAG_ALL_GRANTS);
20185    }
20186
20187    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20188            throws XmlPullParserException, IOException {
20189        String pkgName = null;
20190        int outerDepth = parser.getDepth();
20191        int type;
20192        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20193                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20194            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20195                continue;
20196            }
20197
20198            final String tagName = parser.getName();
20199            if (tagName.equals(TAG_GRANT)) {
20200                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20201                if (DEBUG_BACKUP) {
20202                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20203                }
20204            } else if (tagName.equals(TAG_PERMISSION)) {
20205
20206                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20207                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20208
20209                int newFlagSet = 0;
20210                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20211                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20212                }
20213                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20214                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20215                }
20216                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20217                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20218                }
20219                if (DEBUG_BACKUP) {
20220                    Slog.v(TAG, "  + Restoring grant:"
20221                            + " pkg=" + pkgName
20222                            + " perm=" + permName
20223                            + " granted=" + isGranted
20224                            + " bits=0x" + Integer.toHexString(newFlagSet));
20225                }
20226                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20227                if (ps != null) {
20228                    // Already installed so we apply the grant immediately
20229                    if (DEBUG_BACKUP) {
20230                        Slog.v(TAG, "        + already installed; applying");
20231                    }
20232                    PermissionsState perms = ps.getPermissionsState();
20233                    BasePermission bp =
20234                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20235                    if (bp != null) {
20236                        if (isGranted) {
20237                            perms.grantRuntimePermission(bp, userId);
20238                        }
20239                        if (newFlagSet != 0) {
20240                            perms.updatePermissionFlags(
20241                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20242                        }
20243                    }
20244                } else {
20245                    // Need to wait for post-restore install to apply the grant
20246                    if (DEBUG_BACKUP) {
20247                        Slog.v(TAG, "        - not yet installed; saving for later");
20248                    }
20249                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20250                            isGranted, newFlagSet, userId);
20251                }
20252            } else {
20253                PackageManagerService.reportSettingsProblem(Log.WARN,
20254                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20255                XmlUtils.skipCurrentTag(parser);
20256            }
20257        }
20258
20259        scheduleWriteSettingsLocked();
20260        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20261    }
20262
20263    @Override
20264    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20265            int sourceUserId, int targetUserId, int flags) {
20266        mContext.enforceCallingOrSelfPermission(
20267                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20268        int callingUid = Binder.getCallingUid();
20269        enforceOwnerRights(ownerPackage, callingUid);
20270        PackageManagerServiceUtils.enforceShellRestriction(
20271                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20272        if (intentFilter.countActions() == 0) {
20273            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20274            return;
20275        }
20276        synchronized (mPackages) {
20277            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20278                    ownerPackage, targetUserId, flags);
20279            CrossProfileIntentResolver resolver =
20280                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20281            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20282            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20283            if (existing != null) {
20284                int size = existing.size();
20285                for (int i = 0; i < size; i++) {
20286                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20287                        return;
20288                    }
20289                }
20290            }
20291            resolver.addFilter(newFilter);
20292            scheduleWritePackageRestrictionsLocked(sourceUserId);
20293        }
20294    }
20295
20296    @Override
20297    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20298        mContext.enforceCallingOrSelfPermission(
20299                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20300        final int callingUid = Binder.getCallingUid();
20301        enforceOwnerRights(ownerPackage, callingUid);
20302        PackageManagerServiceUtils.enforceShellRestriction(
20303                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20304        synchronized (mPackages) {
20305            CrossProfileIntentResolver resolver =
20306                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20307            ArraySet<CrossProfileIntentFilter> set =
20308                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20309            for (CrossProfileIntentFilter filter : set) {
20310                if (filter.getOwnerPackage().equals(ownerPackage)) {
20311                    resolver.removeFilter(filter);
20312                }
20313            }
20314            scheduleWritePackageRestrictionsLocked(sourceUserId);
20315        }
20316    }
20317
20318    // Enforcing that callingUid is owning pkg on userId
20319    private void enforceOwnerRights(String pkg, int callingUid) {
20320        // The system owns everything.
20321        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20322            return;
20323        }
20324        final int callingUserId = UserHandle.getUserId(callingUid);
20325        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20326        if (pi == null) {
20327            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20328                    + callingUserId);
20329        }
20330        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20331            throw new SecurityException("Calling uid " + callingUid
20332                    + " does not own package " + pkg);
20333        }
20334    }
20335
20336    @Override
20337    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20338        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20339            return null;
20340        }
20341        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20342    }
20343
20344    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20345        UserManagerService ums = UserManagerService.getInstance();
20346        if (ums != null) {
20347            final UserInfo parent = ums.getProfileParent(userId);
20348            final int launcherUid = (parent != null) ? parent.id : userId;
20349            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20350            if (launcherComponent != null) {
20351                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20352                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20353                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20354                        .setPackage(launcherComponent.getPackageName());
20355                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20356            }
20357        }
20358    }
20359
20360    /**
20361     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20362     * then reports the most likely home activity or null if there are more than one.
20363     */
20364    private ComponentName getDefaultHomeActivity(int userId) {
20365        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20366        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20367        if (cn != null) {
20368            return cn;
20369        }
20370
20371        // Find the launcher with the highest priority and return that component if there are no
20372        // other home activity with the same priority.
20373        int lastPriority = Integer.MIN_VALUE;
20374        ComponentName lastComponent = null;
20375        final int size = allHomeCandidates.size();
20376        for (int i = 0; i < size; i++) {
20377            final ResolveInfo ri = allHomeCandidates.get(i);
20378            if (ri.priority > lastPriority) {
20379                lastComponent = ri.activityInfo.getComponentName();
20380                lastPriority = ri.priority;
20381            } else if (ri.priority == lastPriority) {
20382                // Two components found with same priority.
20383                lastComponent = null;
20384            }
20385        }
20386        return lastComponent;
20387    }
20388
20389    private Intent getHomeIntent() {
20390        Intent intent = new Intent(Intent.ACTION_MAIN);
20391        intent.addCategory(Intent.CATEGORY_HOME);
20392        intent.addCategory(Intent.CATEGORY_DEFAULT);
20393        return intent;
20394    }
20395
20396    private IntentFilter getHomeFilter() {
20397        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20398        filter.addCategory(Intent.CATEGORY_HOME);
20399        filter.addCategory(Intent.CATEGORY_DEFAULT);
20400        return filter;
20401    }
20402
20403    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20404            int userId) {
20405        Intent intent  = getHomeIntent();
20406        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20407                PackageManager.GET_META_DATA, userId);
20408        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20409                true, false, false, userId);
20410
20411        allHomeCandidates.clear();
20412        if (list != null) {
20413            for (ResolveInfo ri : list) {
20414                allHomeCandidates.add(ri);
20415            }
20416        }
20417        return (preferred == null || preferred.activityInfo == null)
20418                ? null
20419                : new ComponentName(preferred.activityInfo.packageName,
20420                        preferred.activityInfo.name);
20421    }
20422
20423    @Override
20424    public void setHomeActivity(ComponentName comp, int userId) {
20425        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20426            return;
20427        }
20428        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20429        getHomeActivitiesAsUser(homeActivities, userId);
20430
20431        boolean found = false;
20432
20433        final int size = homeActivities.size();
20434        final ComponentName[] set = new ComponentName[size];
20435        for (int i = 0; i < size; i++) {
20436            final ResolveInfo candidate = homeActivities.get(i);
20437            final ActivityInfo info = candidate.activityInfo;
20438            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20439            set[i] = activityName;
20440            if (!found && activityName.equals(comp)) {
20441                found = true;
20442            }
20443        }
20444        if (!found) {
20445            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20446                    + userId);
20447        }
20448        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20449                set, comp, userId);
20450    }
20451
20452    private @Nullable String getSetupWizardPackageName() {
20453        final Intent intent = new Intent(Intent.ACTION_MAIN);
20454        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20455
20456        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20457                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20458                        | MATCH_DISABLED_COMPONENTS,
20459                UserHandle.myUserId());
20460        if (matches.size() == 1) {
20461            return matches.get(0).getComponentInfo().packageName;
20462        } else {
20463            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20464                    + ": matches=" + matches);
20465            return null;
20466        }
20467    }
20468
20469    private @Nullable String getStorageManagerPackageName() {
20470        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20471
20472        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20473                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20474                        | MATCH_DISABLED_COMPONENTS,
20475                UserHandle.myUserId());
20476        if (matches.size() == 1) {
20477            return matches.get(0).getComponentInfo().packageName;
20478        } else {
20479            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20480                    + matches.size() + ": matches=" + matches);
20481            return null;
20482        }
20483    }
20484
20485    @Override
20486    public String getSystemTextClassifierPackageName() {
20487        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20488    }
20489
20490    @Override
20491    public void setApplicationEnabledSetting(String appPackageName,
20492            int newState, int flags, int userId, String callingPackage) {
20493        if (!sUserManager.exists(userId)) return;
20494        if (callingPackage == null) {
20495            callingPackage = Integer.toString(Binder.getCallingUid());
20496        }
20497        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20498    }
20499
20500    @Override
20501    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20502        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20503        synchronized (mPackages) {
20504            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20505            if (pkgSetting != null) {
20506                pkgSetting.setUpdateAvailable(updateAvailable);
20507            }
20508        }
20509    }
20510
20511    @Override
20512    public void setComponentEnabledSetting(ComponentName componentName,
20513            int newState, int flags, int userId) {
20514        if (!sUserManager.exists(userId)) return;
20515        setEnabledSetting(componentName.getPackageName(),
20516                componentName.getClassName(), newState, flags, userId, null);
20517    }
20518
20519    private void setEnabledSetting(final String packageName, String className, int newState,
20520            final int flags, int userId, String callingPackage) {
20521        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20522              || newState == COMPONENT_ENABLED_STATE_ENABLED
20523              || newState == COMPONENT_ENABLED_STATE_DISABLED
20524              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20525              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20526            throw new IllegalArgumentException("Invalid new component state: "
20527                    + newState);
20528        }
20529        PackageSetting pkgSetting;
20530        final int callingUid = Binder.getCallingUid();
20531        final int permission;
20532        if (callingUid == Process.SYSTEM_UID) {
20533            permission = PackageManager.PERMISSION_GRANTED;
20534        } else {
20535            permission = mContext.checkCallingOrSelfPermission(
20536                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20537        }
20538        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20539                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20540        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20541        boolean sendNow = false;
20542        boolean isApp = (className == null);
20543        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20544        String componentName = isApp ? packageName : className;
20545        int packageUid = -1;
20546        ArrayList<String> components;
20547
20548        // reader
20549        synchronized (mPackages) {
20550            pkgSetting = mSettings.mPackages.get(packageName);
20551            if (pkgSetting == null) {
20552                if (!isCallerInstantApp) {
20553                    if (className == null) {
20554                        throw new IllegalArgumentException("Unknown package: " + packageName);
20555                    }
20556                    throw new IllegalArgumentException(
20557                            "Unknown component: " + packageName + "/" + className);
20558                } else {
20559                    // throw SecurityException to prevent leaking package information
20560                    throw new SecurityException(
20561                            "Attempt to change component state; "
20562                            + "pid=" + Binder.getCallingPid()
20563                            + ", uid=" + callingUid
20564                            + (className == null
20565                                    ? ", package=" + packageName
20566                                    : ", component=" + packageName + "/" + className));
20567                }
20568            }
20569        }
20570
20571        // Limit who can change which apps
20572        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20573            // Don't allow apps that don't have permission to modify other apps
20574            if (!allowedByPermission
20575                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20576                throw new SecurityException(
20577                        "Attempt to change component state; "
20578                        + "pid=" + Binder.getCallingPid()
20579                        + ", uid=" + callingUid
20580                        + (className == null
20581                                ? ", package=" + packageName
20582                                : ", component=" + packageName + "/" + className));
20583            }
20584            // Don't allow changing protected packages.
20585            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20586                throw new SecurityException("Cannot disable a protected package: " + packageName);
20587            }
20588        }
20589
20590        synchronized (mPackages) {
20591            if (callingUid == Process.SHELL_UID
20592                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20593                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20594                // unless it is a test package.
20595                int oldState = pkgSetting.getEnabled(userId);
20596                if (className == null
20597                        &&
20598                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20599                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20600                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20601                        &&
20602                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20603                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20604                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20605                    // ok
20606                } else {
20607                    throw new SecurityException(
20608                            "Shell cannot change component state for " + packageName + "/"
20609                                    + className + " to " + newState);
20610                }
20611            }
20612        }
20613        if (className == null) {
20614            // We're dealing with an application/package level state change
20615            synchronized (mPackages) {
20616                if (pkgSetting.getEnabled(userId) == newState) {
20617                    // Nothing to do
20618                    return;
20619                }
20620            }
20621            // If we're enabling a system stub, there's a little more work to do.
20622            // Prior to enabling the package, we need to decompress the APK(s) to the
20623            // data partition and then replace the version on the system partition.
20624            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20625            final boolean isSystemStub = deletedPkg.isStub
20626                    && deletedPkg.isSystem();
20627            if (isSystemStub
20628                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20629                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20630                final File codePath = decompressPackage(deletedPkg);
20631                if (codePath == null) {
20632                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20633                    return;
20634                }
20635                // TODO remove direct parsing of the package object during internal cleanup
20636                // of scan package
20637                // We need to call parse directly here for no other reason than we need
20638                // the new package in order to disable the old one [we use the information
20639                // for some internal optimization to optionally create a new package setting
20640                // object on replace]. However, we can't get the package from the scan
20641                // because the scan modifies live structures and we need to remove the
20642                // old [system] package from the system before a scan can be attempted.
20643                // Once scan is indempotent we can remove this parse and use the package
20644                // object we scanned, prior to adding it to package settings.
20645                final PackageParser pp = new PackageParser();
20646                pp.setSeparateProcesses(mSeparateProcesses);
20647                pp.setDisplayMetrics(mMetrics);
20648                pp.setCallback(mPackageParserCallback);
20649                final PackageParser.Package tmpPkg;
20650                try {
20651                    final @ParseFlags int parseFlags = mDefParseFlags
20652                            | PackageParser.PARSE_MUST_BE_APK
20653                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20654                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20655                } catch (PackageParserException e) {
20656                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20657                    return;
20658                }
20659                synchronized (mInstallLock) {
20660                    // Disable the stub and remove any package entries
20661                    removePackageLI(deletedPkg, true);
20662                    synchronized (mPackages) {
20663                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20664                    }
20665                    final PackageParser.Package pkg;
20666                    try (PackageFreezer freezer =
20667                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20668                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20669                                | PackageParser.PARSE_ENFORCE_CODE;
20670                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20671                                0 /*currentTime*/, null /*user*/);
20672                        prepareAppDataAfterInstallLIF(pkg);
20673                        synchronized (mPackages) {
20674                            try {
20675                                updateSharedLibrariesLPr(pkg, null);
20676                            } catch (PackageManagerException e) {
20677                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20678                            }
20679                            mPermissionManager.updatePermissions(
20680                                    pkg.packageName, pkg, true, mPackages.values(),
20681                                    mPermissionCallback);
20682                            mSettings.writeLPr();
20683                        }
20684                    } catch (PackageManagerException e) {
20685                        // Whoops! Something went wrong; try to roll back to the stub
20686                        Slog.w(TAG, "Failed to install compressed system package:"
20687                                + pkgSetting.name, e);
20688                        // Remove the failed install
20689                        removeCodePathLI(codePath);
20690
20691                        // Install the system package
20692                        try (PackageFreezer freezer =
20693                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20694                            synchronized (mPackages) {
20695                                // NOTE: The system package always needs to be enabled; even
20696                                // if it's for a compressed stub. If we don't, installing the
20697                                // system package fails during scan [scanning checks the disabled
20698                                // packages]. We will reverse this later, after we've "installed"
20699                                // the stub.
20700                                // This leaves us in a fragile state; the stub should never be
20701                                // enabled, so, cross your fingers and hope nothing goes wrong
20702                                // until we can disable the package later.
20703                                enableSystemPackageLPw(deletedPkg);
20704                            }
20705                            installPackageFromSystemLIF(deletedPkg.codePath,
20706                                    false /*isPrivileged*/, null /*allUserHandles*/,
20707                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20708                                    true /*writeSettings*/);
20709                        } catch (PackageManagerException pme) {
20710                            Slog.w(TAG, "Failed to restore system package:"
20711                                    + deletedPkg.packageName, pme);
20712                        } finally {
20713                            synchronized (mPackages) {
20714                                mSettings.disableSystemPackageLPw(
20715                                        deletedPkg.packageName, true /*replaced*/);
20716                                mSettings.writeLPr();
20717                            }
20718                        }
20719                        return;
20720                    }
20721                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20722                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20723                    mDexManager.notifyPackageUpdated(pkg.packageName,
20724                            pkg.baseCodePath, pkg.splitCodePaths);
20725                }
20726            }
20727            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20728                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20729                // Don't care about who enables an app.
20730                callingPackage = null;
20731            }
20732            synchronized (mPackages) {
20733                pkgSetting.setEnabled(newState, userId, callingPackage);
20734            }
20735        } else {
20736            synchronized (mPackages) {
20737                // We're dealing with a component level state change
20738                // First, verify that this is a valid class name.
20739                PackageParser.Package pkg = pkgSetting.pkg;
20740                if (pkg == null || !pkg.hasComponentClassName(className)) {
20741                    if (pkg != null &&
20742                            pkg.applicationInfo.targetSdkVersion >=
20743                                    Build.VERSION_CODES.JELLY_BEAN) {
20744                        throw new IllegalArgumentException("Component class " + className
20745                                + " does not exist in " + packageName);
20746                    } else {
20747                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20748                                + className + " does not exist in " + packageName);
20749                    }
20750                }
20751                switch (newState) {
20752                    case COMPONENT_ENABLED_STATE_ENABLED:
20753                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20754                            return;
20755                        }
20756                        break;
20757                    case COMPONENT_ENABLED_STATE_DISABLED:
20758                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20759                            return;
20760                        }
20761                        break;
20762                    case COMPONENT_ENABLED_STATE_DEFAULT:
20763                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20764                            return;
20765                        }
20766                        break;
20767                    default:
20768                        Slog.e(TAG, "Invalid new component state: " + newState);
20769                        return;
20770                }
20771            }
20772        }
20773        synchronized (mPackages) {
20774            scheduleWritePackageRestrictionsLocked(userId);
20775            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20776            final long callingId = Binder.clearCallingIdentity();
20777            try {
20778                updateInstantAppInstallerLocked(packageName);
20779            } finally {
20780                Binder.restoreCallingIdentity(callingId);
20781            }
20782            components = mPendingBroadcasts.get(userId, packageName);
20783            final boolean newPackage = components == null;
20784            if (newPackage) {
20785                components = new ArrayList<String>();
20786            }
20787            if (!components.contains(componentName)) {
20788                components.add(componentName);
20789            }
20790            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20791                sendNow = true;
20792                // Purge entry from pending broadcast list if another one exists already
20793                // since we are sending one right away.
20794                mPendingBroadcasts.remove(userId, packageName);
20795            } else {
20796                if (newPackage) {
20797                    mPendingBroadcasts.put(userId, packageName, components);
20798                }
20799                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20800                    // Schedule a message
20801                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20802                }
20803            }
20804        }
20805
20806        long callingId = Binder.clearCallingIdentity();
20807        try {
20808            if (sendNow) {
20809                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20810                sendPackageChangedBroadcast(packageName,
20811                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20812            }
20813        } finally {
20814            Binder.restoreCallingIdentity(callingId);
20815        }
20816    }
20817
20818    @Override
20819    public void flushPackageRestrictionsAsUser(int userId) {
20820        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20821            return;
20822        }
20823        if (!sUserManager.exists(userId)) {
20824            return;
20825        }
20826        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20827                false /* checkShell */, "flushPackageRestrictions");
20828        synchronized (mPackages) {
20829            mSettings.writePackageRestrictionsLPr(userId);
20830            mDirtyUsers.remove(userId);
20831            if (mDirtyUsers.isEmpty()) {
20832                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20833            }
20834        }
20835    }
20836
20837    private void sendPackageChangedBroadcast(String packageName,
20838            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20839        if (DEBUG_INSTALL)
20840            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20841                    + componentNames);
20842        Bundle extras = new Bundle(4);
20843        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20844        String nameList[] = new String[componentNames.size()];
20845        componentNames.toArray(nameList);
20846        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20847        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20848        extras.putInt(Intent.EXTRA_UID, packageUid);
20849        // If this is not reporting a change of the overall package, then only send it
20850        // to registered receivers.  We don't want to launch a swath of apps for every
20851        // little component state change.
20852        final int flags = !componentNames.contains(packageName)
20853                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20854        final int userId = UserHandle.getUserId(packageUid);
20855        final boolean isInstantApp = isInstantApp(packageName, userId);
20856        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20857        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20858        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20859                userIds, instantUserIds);
20860    }
20861
20862    @Override
20863    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20864        if (!sUserManager.exists(userId)) return;
20865        final int callingUid = Binder.getCallingUid();
20866        if (getInstantAppPackageName(callingUid) != null) {
20867            return;
20868        }
20869        final int permission = mContext.checkCallingOrSelfPermission(
20870                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20871        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20872        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20873                true /* requireFullPermission */, true /* checkShell */, "stop package");
20874        // writer
20875        synchronized (mPackages) {
20876            final PackageSetting ps = mSettings.mPackages.get(packageName);
20877            if (!filterAppAccessLPr(ps, callingUid, userId)
20878                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20879                            allowedByPermission, callingUid, userId)) {
20880                scheduleWritePackageRestrictionsLocked(userId);
20881            }
20882        }
20883    }
20884
20885    @Override
20886    public String getInstallerPackageName(String packageName) {
20887        final int callingUid = Binder.getCallingUid();
20888        synchronized (mPackages) {
20889            final PackageSetting ps = mSettings.mPackages.get(packageName);
20890            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20891                return null;
20892            }
20893            return mSettings.getInstallerPackageNameLPr(packageName);
20894        }
20895    }
20896
20897    public boolean isOrphaned(String packageName) {
20898        // reader
20899        synchronized (mPackages) {
20900            return mSettings.isOrphaned(packageName);
20901        }
20902    }
20903
20904    @Override
20905    public int getApplicationEnabledSetting(String packageName, int userId) {
20906        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20907        int callingUid = Binder.getCallingUid();
20908        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20909                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20910        // reader
20911        synchronized (mPackages) {
20912            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20913                return COMPONENT_ENABLED_STATE_DISABLED;
20914            }
20915            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20916        }
20917    }
20918
20919    @Override
20920    public int getComponentEnabledSetting(ComponentName component, int userId) {
20921        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20922        int callingUid = Binder.getCallingUid();
20923        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20924                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20925        synchronized (mPackages) {
20926            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20927                    component, TYPE_UNKNOWN, userId)) {
20928                return COMPONENT_ENABLED_STATE_DISABLED;
20929            }
20930            return mSettings.getComponentEnabledSettingLPr(component, userId);
20931        }
20932    }
20933
20934    @Override
20935    public void enterSafeMode() {
20936        enforceSystemOrRoot("Only the system can request entering safe mode");
20937
20938        if (!mSystemReady) {
20939            mSafeMode = true;
20940        }
20941    }
20942
20943    @Override
20944    public void systemReady() {
20945        enforceSystemOrRoot("Only the system can claim the system is ready");
20946
20947        mSystemReady = true;
20948        final ContentResolver resolver = mContext.getContentResolver();
20949        ContentObserver co = new ContentObserver(mHandler) {
20950            @Override
20951            public void onChange(boolean selfChange) {
20952                mWebInstantAppsDisabled =
20953                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20954                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20955            }
20956        };
20957        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20958                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20959                false, co, UserHandle.USER_SYSTEM);
20960        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20961                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20962        co.onChange(true);
20963
20964        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20965        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20966        // it is done.
20967        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20968            @Override
20969            public void onChange(boolean selfChange) {
20970                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20971                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20972                        oobEnabled == 1 ? "true" : "false");
20973            }
20974        };
20975        mContext.getContentResolver().registerContentObserver(
20976                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20977                UserHandle.USER_SYSTEM);
20978        // At boot, restore the value from the setting, which persists across reboot.
20979        privAppOobObserver.onChange(true);
20980
20981        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20982        // disabled after already being started.
20983        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20984                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20985
20986        // Read the compatibilty setting when the system is ready.
20987        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20988                mContext.getContentResolver(),
20989                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20990        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20991        if (DEBUG_SETTINGS) {
20992            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20993        }
20994
20995        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20996
20997        synchronized (mPackages) {
20998            // Verify that all of the preferred activity components actually
20999            // exist.  It is possible for applications to be updated and at
21000            // that point remove a previously declared activity component that
21001            // had been set as a preferred activity.  We try to clean this up
21002            // the next time we encounter that preferred activity, but it is
21003            // possible for the user flow to never be able to return to that
21004            // situation so here we do a sanity check to make sure we haven't
21005            // left any junk around.
21006            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21007            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21008                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21009                removed.clear();
21010                for (PreferredActivity pa : pir.filterSet()) {
21011                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21012                        removed.add(pa);
21013                    }
21014                }
21015                if (removed.size() > 0) {
21016                    for (int r=0; r<removed.size(); r++) {
21017                        PreferredActivity pa = removed.get(r);
21018                        Slog.w(TAG, "Removing dangling preferred activity: "
21019                                + pa.mPref.mComponent);
21020                        pir.removeFilter(pa);
21021                    }
21022                    mSettings.writePackageRestrictionsLPr(
21023                            mSettings.mPreferredActivities.keyAt(i));
21024                }
21025            }
21026
21027            for (int userId : UserManagerService.getInstance().getUserIds()) {
21028                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21029                    grantPermissionsUserIds = ArrayUtils.appendInt(
21030                            grantPermissionsUserIds, userId);
21031                }
21032            }
21033        }
21034        sUserManager.systemReady();
21035        // If we upgraded grant all default permissions before kicking off.
21036        for (int userId : grantPermissionsUserIds) {
21037            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21038        }
21039
21040        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21041            // If we did not grant default permissions, we preload from this the
21042            // default permission exceptions lazily to ensure we don't hit the
21043            // disk on a new user creation.
21044            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21045        }
21046
21047        // Now that we've scanned all packages, and granted any default
21048        // permissions, ensure permissions are updated. Beware of dragons if you
21049        // try optimizing this.
21050        synchronized (mPackages) {
21051            mPermissionManager.updateAllPermissions(
21052                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21053                    mPermissionCallback);
21054        }
21055
21056        // Kick off any messages waiting for system ready
21057        if (mPostSystemReadyMessages != null) {
21058            for (Message msg : mPostSystemReadyMessages) {
21059                msg.sendToTarget();
21060            }
21061            mPostSystemReadyMessages = null;
21062        }
21063
21064        // Watch for external volumes that come and go over time
21065        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21066        storage.registerListener(mStorageListener);
21067
21068        mInstallerService.systemReady();
21069        mPackageDexOptimizer.systemReady();
21070
21071        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21072                StorageManagerInternal.class);
21073        StorageManagerInternal.addExternalStoragePolicy(
21074                new StorageManagerInternal.ExternalStorageMountPolicy() {
21075            @Override
21076            public int getMountMode(int uid, String packageName) {
21077                if (Process.isIsolated(uid)) {
21078                    return Zygote.MOUNT_EXTERNAL_NONE;
21079                }
21080                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21081                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21082                }
21083                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21084                    return Zygote.MOUNT_EXTERNAL_READ;
21085                }
21086                return Zygote.MOUNT_EXTERNAL_WRITE;
21087            }
21088
21089            @Override
21090            public boolean hasExternalStorage(int uid, String packageName) {
21091                return true;
21092            }
21093        });
21094
21095        // Now that we're mostly running, clean up stale users and apps
21096        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21097        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21098
21099        mPermissionManager.systemReady();
21100
21101        if (mInstantAppResolverConnection != null) {
21102            mContext.registerReceiver(new BroadcastReceiver() {
21103                @Override
21104                public void onReceive(Context context, Intent intent) {
21105                    mInstantAppResolverConnection.optimisticBind();
21106                    mContext.unregisterReceiver(this);
21107                }
21108            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21109        }
21110    }
21111
21112    public void waitForAppDataPrepared() {
21113        if (mPrepareAppDataFuture == null) {
21114            return;
21115        }
21116        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21117        mPrepareAppDataFuture = null;
21118    }
21119
21120    @Override
21121    public boolean isSafeMode() {
21122        // allow instant applications
21123        return mSafeMode;
21124    }
21125
21126    @Override
21127    public boolean hasSystemUidErrors() {
21128        // allow instant applications
21129        return mHasSystemUidErrors;
21130    }
21131
21132    static String arrayToString(int[] array) {
21133        StringBuffer buf = new StringBuffer(128);
21134        buf.append('[');
21135        if (array != null) {
21136            for (int i=0; i<array.length; i++) {
21137                if (i > 0) buf.append(", ");
21138                buf.append(array[i]);
21139            }
21140        }
21141        buf.append(']');
21142        return buf.toString();
21143    }
21144
21145    @Override
21146    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21147            FileDescriptor err, String[] args, ShellCallback callback,
21148            ResultReceiver resultReceiver) {
21149        (new PackageManagerShellCommand(this)).exec(
21150                this, in, out, err, args, callback, resultReceiver);
21151    }
21152
21153    @Override
21154    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21155        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21156
21157        DumpState dumpState = new DumpState();
21158        boolean fullPreferred = false;
21159        boolean checkin = false;
21160
21161        String packageName = null;
21162        ArraySet<String> permissionNames = null;
21163
21164        int opti = 0;
21165        while (opti < args.length) {
21166            String opt = args[opti];
21167            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21168                break;
21169            }
21170            opti++;
21171
21172            if ("-a".equals(opt)) {
21173                // Right now we only know how to print all.
21174            } else if ("-h".equals(opt)) {
21175                pw.println("Package manager dump options:");
21176                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21177                pw.println("    --checkin: dump for a checkin");
21178                pw.println("    -f: print details of intent filters");
21179                pw.println("    -h: print this help");
21180                pw.println("  cmd may be one of:");
21181                pw.println("    l[ibraries]: list known shared libraries");
21182                pw.println("    f[eatures]: list device features");
21183                pw.println("    k[eysets]: print known keysets");
21184                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21185                pw.println("    perm[issions]: dump permissions");
21186                pw.println("    permission [name ...]: dump declaration and use of given permission");
21187                pw.println("    pref[erred]: print preferred package settings");
21188                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21189                pw.println("    prov[iders]: dump content providers");
21190                pw.println("    p[ackages]: dump installed packages");
21191                pw.println("    s[hared-users]: dump shared user IDs");
21192                pw.println("    m[essages]: print collected runtime messages");
21193                pw.println("    v[erifiers]: print package verifier info");
21194                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21195                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21196                pw.println("    version: print database version info");
21197                pw.println("    write: write current settings now");
21198                pw.println("    installs: details about install sessions");
21199                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21200                pw.println("    dexopt: dump dexopt state");
21201                pw.println("    compiler-stats: dump compiler statistics");
21202                pw.println("    service-permissions: dump permissions required by services");
21203                pw.println("    <package.name>: info about given package");
21204                return;
21205            } else if ("--checkin".equals(opt)) {
21206                checkin = true;
21207            } else if ("-f".equals(opt)) {
21208                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21209            } else if ("--proto".equals(opt)) {
21210                dumpProto(fd);
21211                return;
21212            } else {
21213                pw.println("Unknown argument: " + opt + "; use -h for help");
21214            }
21215        }
21216
21217        // Is the caller requesting to dump a particular piece of data?
21218        if (opti < args.length) {
21219            String cmd = args[opti];
21220            opti++;
21221            // Is this a package name?
21222            if ("android".equals(cmd) || cmd.contains(".")) {
21223                packageName = cmd;
21224                // When dumping a single package, we always dump all of its
21225                // filter information since the amount of data will be reasonable.
21226                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21227            } else if ("check-permission".equals(cmd)) {
21228                if (opti >= args.length) {
21229                    pw.println("Error: check-permission missing permission argument");
21230                    return;
21231                }
21232                String perm = args[opti];
21233                opti++;
21234                if (opti >= args.length) {
21235                    pw.println("Error: check-permission missing package argument");
21236                    return;
21237                }
21238
21239                String pkg = args[opti];
21240                opti++;
21241                int user = UserHandle.getUserId(Binder.getCallingUid());
21242                if (opti < args.length) {
21243                    try {
21244                        user = Integer.parseInt(args[opti]);
21245                    } catch (NumberFormatException e) {
21246                        pw.println("Error: check-permission user argument is not a number: "
21247                                + args[opti]);
21248                        return;
21249                    }
21250                }
21251
21252                // Normalize package name to handle renamed packages and static libs
21253                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21254
21255                pw.println(checkPermission(perm, pkg, user));
21256                return;
21257            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21258                dumpState.setDump(DumpState.DUMP_LIBS);
21259            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21260                dumpState.setDump(DumpState.DUMP_FEATURES);
21261            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21262                if (opti >= args.length) {
21263                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21264                            | DumpState.DUMP_SERVICE_RESOLVERS
21265                            | DumpState.DUMP_RECEIVER_RESOLVERS
21266                            | DumpState.DUMP_CONTENT_RESOLVERS);
21267                } else {
21268                    while (opti < args.length) {
21269                        String name = args[opti];
21270                        if ("a".equals(name) || "activity".equals(name)) {
21271                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21272                        } else if ("s".equals(name) || "service".equals(name)) {
21273                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21274                        } else if ("r".equals(name) || "receiver".equals(name)) {
21275                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21276                        } else if ("c".equals(name) || "content".equals(name)) {
21277                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21278                        } else {
21279                            pw.println("Error: unknown resolver table type: " + name);
21280                            return;
21281                        }
21282                        opti++;
21283                    }
21284                }
21285            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21286                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21287            } else if ("permission".equals(cmd)) {
21288                if (opti >= args.length) {
21289                    pw.println("Error: permission requires permission name");
21290                    return;
21291                }
21292                permissionNames = new ArraySet<>();
21293                while (opti < args.length) {
21294                    permissionNames.add(args[opti]);
21295                    opti++;
21296                }
21297                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21298                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21299            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21300                dumpState.setDump(DumpState.DUMP_PREFERRED);
21301            } else if ("preferred-xml".equals(cmd)) {
21302                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21303                if (opti < args.length && "--full".equals(args[opti])) {
21304                    fullPreferred = true;
21305                    opti++;
21306                }
21307            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21308                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21309            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21310                dumpState.setDump(DumpState.DUMP_PACKAGES);
21311            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21312                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21313            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21314                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21315            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21316                dumpState.setDump(DumpState.DUMP_MESSAGES);
21317            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21318                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21319            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21320                    || "intent-filter-verifiers".equals(cmd)) {
21321                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21322            } else if ("version".equals(cmd)) {
21323                dumpState.setDump(DumpState.DUMP_VERSION);
21324            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21325                dumpState.setDump(DumpState.DUMP_KEYSETS);
21326            } else if ("installs".equals(cmd)) {
21327                dumpState.setDump(DumpState.DUMP_INSTALLS);
21328            } else if ("frozen".equals(cmd)) {
21329                dumpState.setDump(DumpState.DUMP_FROZEN);
21330            } else if ("volumes".equals(cmd)) {
21331                dumpState.setDump(DumpState.DUMP_VOLUMES);
21332            } else if ("dexopt".equals(cmd)) {
21333                dumpState.setDump(DumpState.DUMP_DEXOPT);
21334            } else if ("compiler-stats".equals(cmd)) {
21335                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21336            } else if ("changes".equals(cmd)) {
21337                dumpState.setDump(DumpState.DUMP_CHANGES);
21338            } else if ("service-permissions".equals(cmd)) {
21339                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21340            } else if ("write".equals(cmd)) {
21341                synchronized (mPackages) {
21342                    mSettings.writeLPr();
21343                    pw.println("Settings written.");
21344                    return;
21345                }
21346            }
21347        }
21348
21349        if (checkin) {
21350            pw.println("vers,1");
21351        }
21352
21353        // reader
21354        synchronized (mPackages) {
21355            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21356                if (!checkin) {
21357                    if (dumpState.onTitlePrinted())
21358                        pw.println();
21359                    pw.println("Database versions:");
21360                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21361                }
21362            }
21363
21364            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21365                if (!checkin) {
21366                    if (dumpState.onTitlePrinted())
21367                        pw.println();
21368                    pw.println("Verifiers:");
21369                    pw.print("  Required: ");
21370                    pw.print(mRequiredVerifierPackage);
21371                    pw.print(" (uid=");
21372                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21373                            UserHandle.USER_SYSTEM));
21374                    pw.println(")");
21375                } else if (mRequiredVerifierPackage != null) {
21376                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21377                    pw.print(",");
21378                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21379                            UserHandle.USER_SYSTEM));
21380                }
21381            }
21382
21383            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21384                    packageName == null) {
21385                if (mIntentFilterVerifierComponent != null) {
21386                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21387                    if (!checkin) {
21388                        if (dumpState.onTitlePrinted())
21389                            pw.println();
21390                        pw.println("Intent Filter Verifier:");
21391                        pw.print("  Using: ");
21392                        pw.print(verifierPackageName);
21393                        pw.print(" (uid=");
21394                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21395                                UserHandle.USER_SYSTEM));
21396                        pw.println(")");
21397                    } else if (verifierPackageName != null) {
21398                        pw.print("ifv,"); pw.print(verifierPackageName);
21399                        pw.print(",");
21400                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21401                                UserHandle.USER_SYSTEM));
21402                    }
21403                } else {
21404                    pw.println();
21405                    pw.println("No Intent Filter Verifier available!");
21406                }
21407            }
21408
21409            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21410                boolean printedHeader = false;
21411                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21412                while (it.hasNext()) {
21413                    String libName = it.next();
21414                    LongSparseArray<SharedLibraryEntry> versionedLib
21415                            = mSharedLibraries.get(libName);
21416                    if (versionedLib == null) {
21417                        continue;
21418                    }
21419                    final int versionCount = versionedLib.size();
21420                    for (int i = 0; i < versionCount; i++) {
21421                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21422                        if (!checkin) {
21423                            if (!printedHeader) {
21424                                if (dumpState.onTitlePrinted())
21425                                    pw.println();
21426                                pw.println("Libraries:");
21427                                printedHeader = true;
21428                            }
21429                            pw.print("  ");
21430                        } else {
21431                            pw.print("lib,");
21432                        }
21433                        pw.print(libEntry.info.getName());
21434                        if (libEntry.info.isStatic()) {
21435                            pw.print(" version=" + libEntry.info.getLongVersion());
21436                        }
21437                        if (!checkin) {
21438                            pw.print(" -> ");
21439                        }
21440                        if (libEntry.path != null) {
21441                            pw.print(" (jar) ");
21442                            pw.print(libEntry.path);
21443                        } else {
21444                            pw.print(" (apk) ");
21445                            pw.print(libEntry.apk);
21446                        }
21447                        pw.println();
21448                    }
21449                }
21450            }
21451
21452            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21453                if (dumpState.onTitlePrinted())
21454                    pw.println();
21455                if (!checkin) {
21456                    pw.println("Features:");
21457                }
21458
21459                synchronized (mAvailableFeatures) {
21460                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21461                        if (checkin) {
21462                            pw.print("feat,");
21463                            pw.print(feat.name);
21464                            pw.print(",");
21465                            pw.println(feat.version);
21466                        } else {
21467                            pw.print("  ");
21468                            pw.print(feat.name);
21469                            if (feat.version > 0) {
21470                                pw.print(" version=");
21471                                pw.print(feat.version);
21472                            }
21473                            pw.println();
21474                        }
21475                    }
21476                }
21477            }
21478
21479            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21480                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21481                        : "Activity Resolver Table:", "  ", packageName,
21482                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21483                    dumpState.setTitlePrinted(true);
21484                }
21485            }
21486            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21487                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21488                        : "Receiver Resolver Table:", "  ", packageName,
21489                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21490                    dumpState.setTitlePrinted(true);
21491                }
21492            }
21493            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21494                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21495                        : "Service Resolver Table:", "  ", packageName,
21496                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21497                    dumpState.setTitlePrinted(true);
21498                }
21499            }
21500            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21501                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21502                        : "Provider Resolver Table:", "  ", packageName,
21503                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21504                    dumpState.setTitlePrinted(true);
21505                }
21506            }
21507
21508            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21509                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21510                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21511                    int user = mSettings.mPreferredActivities.keyAt(i);
21512                    if (pir.dump(pw,
21513                            dumpState.getTitlePrinted()
21514                                ? "\nPreferred Activities User " + user + ":"
21515                                : "Preferred Activities User " + user + ":", "  ",
21516                            packageName, true, false)) {
21517                        dumpState.setTitlePrinted(true);
21518                    }
21519                }
21520            }
21521
21522            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21523                pw.flush();
21524                FileOutputStream fout = new FileOutputStream(fd);
21525                BufferedOutputStream str = new BufferedOutputStream(fout);
21526                XmlSerializer serializer = new FastXmlSerializer();
21527                try {
21528                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21529                    serializer.startDocument(null, true);
21530                    serializer.setFeature(
21531                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21532                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21533                    serializer.endDocument();
21534                    serializer.flush();
21535                } catch (IllegalArgumentException e) {
21536                    pw.println("Failed writing: " + e);
21537                } catch (IllegalStateException e) {
21538                    pw.println("Failed writing: " + e);
21539                } catch (IOException e) {
21540                    pw.println("Failed writing: " + e);
21541                }
21542            }
21543
21544            if (!checkin
21545                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21546                    && packageName == null) {
21547                pw.println();
21548                int count = mSettings.mPackages.size();
21549                if (count == 0) {
21550                    pw.println("No applications!");
21551                    pw.println();
21552                } else {
21553                    final String prefix = "  ";
21554                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21555                    if (allPackageSettings.size() == 0) {
21556                        pw.println("No domain preferred apps!");
21557                        pw.println();
21558                    } else {
21559                        pw.println("App verification status:");
21560                        pw.println();
21561                        count = 0;
21562                        for (PackageSetting ps : allPackageSettings) {
21563                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21564                            if (ivi == null || ivi.getPackageName() == null) continue;
21565                            pw.println(prefix + "Package: " + ivi.getPackageName());
21566                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21567                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21568                            pw.println();
21569                            count++;
21570                        }
21571                        if (count == 0) {
21572                            pw.println(prefix + "No app verification established.");
21573                            pw.println();
21574                        }
21575                        for (int userId : sUserManager.getUserIds()) {
21576                            pw.println("App linkages for user " + userId + ":");
21577                            pw.println();
21578                            count = 0;
21579                            for (PackageSetting ps : allPackageSettings) {
21580                                final long status = ps.getDomainVerificationStatusForUser(userId);
21581                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21582                                        && !DEBUG_DOMAIN_VERIFICATION) {
21583                                    continue;
21584                                }
21585                                pw.println(prefix + "Package: " + ps.name);
21586                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21587                                String statusStr = IntentFilterVerificationInfo.
21588                                        getStatusStringFromValue(status);
21589                                pw.println(prefix + "Status:  " + statusStr);
21590                                pw.println();
21591                                count++;
21592                            }
21593                            if (count == 0) {
21594                                pw.println(prefix + "No configured app linkages.");
21595                                pw.println();
21596                            }
21597                        }
21598                    }
21599                }
21600            }
21601
21602            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21603                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21604            }
21605
21606            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21607                boolean printedSomething = false;
21608                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21609                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21610                        continue;
21611                    }
21612                    if (!printedSomething) {
21613                        if (dumpState.onTitlePrinted())
21614                            pw.println();
21615                        pw.println("Registered ContentProviders:");
21616                        printedSomething = true;
21617                    }
21618                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21619                    pw.print("    "); pw.println(p.toString());
21620                }
21621                printedSomething = false;
21622                for (Map.Entry<String, PackageParser.Provider> entry :
21623                        mProvidersByAuthority.entrySet()) {
21624                    PackageParser.Provider p = entry.getValue();
21625                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21626                        continue;
21627                    }
21628                    if (!printedSomething) {
21629                        if (dumpState.onTitlePrinted())
21630                            pw.println();
21631                        pw.println("ContentProvider Authorities:");
21632                        printedSomething = true;
21633                    }
21634                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21635                    pw.print("    "); pw.println(p.toString());
21636                    if (p.info != null && p.info.applicationInfo != null) {
21637                        final String appInfo = p.info.applicationInfo.toString();
21638                        pw.print("      applicationInfo="); pw.println(appInfo);
21639                    }
21640                }
21641            }
21642
21643            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21644                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21645            }
21646
21647            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21648                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21649            }
21650
21651            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21652                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21653            }
21654
21655            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21656                if (dumpState.onTitlePrinted()) pw.println();
21657                pw.println("Package Changes:");
21658                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21659                final int K = mChangedPackages.size();
21660                for (int i = 0; i < K; i++) {
21661                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21662                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21663                    final int N = changes.size();
21664                    if (N == 0) {
21665                        pw.print("    "); pw.println("No packages changed");
21666                    } else {
21667                        for (int j = 0; j < N; j++) {
21668                            final String pkgName = changes.valueAt(j);
21669                            final int sequenceNumber = changes.keyAt(j);
21670                            pw.print("    ");
21671                            pw.print("seq=");
21672                            pw.print(sequenceNumber);
21673                            pw.print(", package=");
21674                            pw.println(pkgName);
21675                        }
21676                    }
21677                }
21678            }
21679
21680            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21681                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21682            }
21683
21684            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21685                // XXX should handle packageName != null by dumping only install data that
21686                // the given package is involved with.
21687                if (dumpState.onTitlePrinted()) pw.println();
21688
21689                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21690                ipw.println();
21691                ipw.println("Frozen packages:");
21692                ipw.increaseIndent();
21693                if (mFrozenPackages.size() == 0) {
21694                    ipw.println("(none)");
21695                } else {
21696                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21697                        ipw.println(mFrozenPackages.valueAt(i));
21698                    }
21699                }
21700                ipw.decreaseIndent();
21701            }
21702
21703            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21704                if (dumpState.onTitlePrinted()) pw.println();
21705
21706                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21707                ipw.println();
21708                ipw.println("Loaded volumes:");
21709                ipw.increaseIndent();
21710                if (mLoadedVolumes.size() == 0) {
21711                    ipw.println("(none)");
21712                } else {
21713                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21714                        ipw.println(mLoadedVolumes.valueAt(i));
21715                    }
21716                }
21717                ipw.decreaseIndent();
21718            }
21719
21720            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21721                    && packageName == null) {
21722                if (dumpState.onTitlePrinted()) pw.println();
21723                pw.println("Service permissions:");
21724
21725                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21726                while (filterIterator.hasNext()) {
21727                    final ServiceIntentInfo info = filterIterator.next();
21728                    final ServiceInfo serviceInfo = info.service.info;
21729                    final String permission = serviceInfo.permission;
21730                    if (permission != null) {
21731                        pw.print("    ");
21732                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21733                        pw.print(": ");
21734                        pw.println(permission);
21735                    }
21736                }
21737            }
21738
21739            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21740                if (dumpState.onTitlePrinted()) pw.println();
21741                dumpDexoptStateLPr(pw, packageName);
21742            }
21743
21744            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21745                if (dumpState.onTitlePrinted()) pw.println();
21746                dumpCompilerStatsLPr(pw, packageName);
21747            }
21748
21749            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21750                if (dumpState.onTitlePrinted()) pw.println();
21751                mSettings.dumpReadMessagesLPr(pw, dumpState);
21752
21753                pw.println();
21754                pw.println("Package warning messages:");
21755                dumpCriticalInfo(pw, null);
21756            }
21757
21758            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21759                dumpCriticalInfo(pw, "msg,");
21760            }
21761        }
21762
21763        // PackageInstaller should be called outside of mPackages lock
21764        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21765            // XXX should handle packageName != null by dumping only install data that
21766            // the given package is involved with.
21767            if (dumpState.onTitlePrinted()) pw.println();
21768            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21769        }
21770    }
21771
21772    private void dumpProto(FileDescriptor fd) {
21773        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21774
21775        synchronized (mPackages) {
21776            final long requiredVerifierPackageToken =
21777                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21778            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21779            proto.write(
21780                    PackageServiceDumpProto.PackageShortProto.UID,
21781                    getPackageUid(
21782                            mRequiredVerifierPackage,
21783                            MATCH_DEBUG_TRIAGED_MISSING,
21784                            UserHandle.USER_SYSTEM));
21785            proto.end(requiredVerifierPackageToken);
21786
21787            if (mIntentFilterVerifierComponent != null) {
21788                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21789                final long verifierPackageToken =
21790                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21791                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21792                proto.write(
21793                        PackageServiceDumpProto.PackageShortProto.UID,
21794                        getPackageUid(
21795                                verifierPackageName,
21796                                MATCH_DEBUG_TRIAGED_MISSING,
21797                                UserHandle.USER_SYSTEM));
21798                proto.end(verifierPackageToken);
21799            }
21800
21801            dumpSharedLibrariesProto(proto);
21802            dumpFeaturesProto(proto);
21803            mSettings.dumpPackagesProto(proto);
21804            mSettings.dumpSharedUsersProto(proto);
21805            dumpCriticalInfo(proto);
21806        }
21807        proto.flush();
21808    }
21809
21810    private void dumpFeaturesProto(ProtoOutputStream proto) {
21811        synchronized (mAvailableFeatures) {
21812            final int count = mAvailableFeatures.size();
21813            for (int i = 0; i < count; i++) {
21814                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21815            }
21816        }
21817    }
21818
21819    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21820        final int count = mSharedLibraries.size();
21821        for (int i = 0; i < count; i++) {
21822            final String libName = mSharedLibraries.keyAt(i);
21823            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21824            if (versionedLib == null) {
21825                continue;
21826            }
21827            final int versionCount = versionedLib.size();
21828            for (int j = 0; j < versionCount; j++) {
21829                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21830                final long sharedLibraryToken =
21831                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21832                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21833                final boolean isJar = (libEntry.path != null);
21834                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21835                if (isJar) {
21836                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21837                } else {
21838                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21839                }
21840                proto.end(sharedLibraryToken);
21841            }
21842        }
21843    }
21844
21845    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21846        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21847        ipw.println();
21848        ipw.println("Dexopt state:");
21849        ipw.increaseIndent();
21850        Collection<PackageParser.Package> packages = null;
21851        if (packageName != null) {
21852            PackageParser.Package targetPackage = mPackages.get(packageName);
21853            if (targetPackage != null) {
21854                packages = Collections.singletonList(targetPackage);
21855            } else {
21856                ipw.println("Unable to find package: " + packageName);
21857                return;
21858            }
21859        } else {
21860            packages = mPackages.values();
21861        }
21862
21863        for (PackageParser.Package pkg : packages) {
21864            ipw.println("[" + pkg.packageName + "]");
21865            ipw.increaseIndent();
21866            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21867                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21868            ipw.decreaseIndent();
21869        }
21870    }
21871
21872    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21873        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21874        ipw.println();
21875        ipw.println("Compiler stats:");
21876        ipw.increaseIndent();
21877        Collection<PackageParser.Package> packages = null;
21878        if (packageName != null) {
21879            PackageParser.Package targetPackage = mPackages.get(packageName);
21880            if (targetPackage != null) {
21881                packages = Collections.singletonList(targetPackage);
21882            } else {
21883                ipw.println("Unable to find package: " + packageName);
21884                return;
21885            }
21886        } else {
21887            packages = mPackages.values();
21888        }
21889
21890        for (PackageParser.Package pkg : packages) {
21891            ipw.println("[" + pkg.packageName + "]");
21892            ipw.increaseIndent();
21893
21894            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21895            if (stats == null) {
21896                ipw.println("(No recorded stats)");
21897            } else {
21898                stats.dump(ipw);
21899            }
21900            ipw.decreaseIndent();
21901        }
21902    }
21903
21904    private String dumpDomainString(String packageName) {
21905        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21906                .getList();
21907        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21908
21909        ArraySet<String> result = new ArraySet<>();
21910        if (iviList.size() > 0) {
21911            for (IntentFilterVerificationInfo ivi : iviList) {
21912                for (String host : ivi.getDomains()) {
21913                    result.add(host);
21914                }
21915            }
21916        }
21917        if (filters != null && filters.size() > 0) {
21918            for (IntentFilter filter : filters) {
21919                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21920                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21921                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21922                    result.addAll(filter.getHostsList());
21923                }
21924            }
21925        }
21926
21927        StringBuilder sb = new StringBuilder(result.size() * 16);
21928        for (String domain : result) {
21929            if (sb.length() > 0) sb.append(" ");
21930            sb.append(domain);
21931        }
21932        return sb.toString();
21933    }
21934
21935    // ------- apps on sdcard specific code -------
21936    static final boolean DEBUG_SD_INSTALL = false;
21937
21938    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21939
21940    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21941
21942    private boolean mMediaMounted = false;
21943
21944    static String getEncryptKey() {
21945        try {
21946            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21947                    SD_ENCRYPTION_KEYSTORE_NAME);
21948            if (sdEncKey == null) {
21949                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21950                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21951                if (sdEncKey == null) {
21952                    Slog.e(TAG, "Failed to create encryption keys");
21953                    return null;
21954                }
21955            }
21956            return sdEncKey;
21957        } catch (NoSuchAlgorithmException nsae) {
21958            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21959            return null;
21960        } catch (IOException ioe) {
21961            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21962            return null;
21963        }
21964    }
21965
21966    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21967            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21968        final int size = infos.size();
21969        final String[] packageNames = new String[size];
21970        final int[] packageUids = new int[size];
21971        for (int i = 0; i < size; i++) {
21972            final ApplicationInfo info = infos.get(i);
21973            packageNames[i] = info.packageName;
21974            packageUids[i] = info.uid;
21975        }
21976        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21977                finishedReceiver);
21978    }
21979
21980    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21981            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21982        sendResourcesChangedBroadcast(mediaStatus, replacing,
21983                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21984    }
21985
21986    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21987            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21988        int size = pkgList.length;
21989        if (size > 0) {
21990            // Send broadcasts here
21991            Bundle extras = new Bundle();
21992            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21993            if (uidArr != null) {
21994                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21995            }
21996            if (replacing) {
21997                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21998            }
21999            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22000                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22001            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22002        }
22003    }
22004
22005    private void loadPrivatePackages(final VolumeInfo vol) {
22006        mHandler.post(new Runnable() {
22007            @Override
22008            public void run() {
22009                loadPrivatePackagesInner(vol);
22010            }
22011        });
22012    }
22013
22014    private void loadPrivatePackagesInner(VolumeInfo vol) {
22015        final String volumeUuid = vol.fsUuid;
22016        if (TextUtils.isEmpty(volumeUuid)) {
22017            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22018            return;
22019        }
22020
22021        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22022        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22023        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22024
22025        final VersionInfo ver;
22026        final List<PackageSetting> packages;
22027        synchronized (mPackages) {
22028            ver = mSettings.findOrCreateVersion(volumeUuid);
22029            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22030        }
22031
22032        for (PackageSetting ps : packages) {
22033            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22034            synchronized (mInstallLock) {
22035                final PackageParser.Package pkg;
22036                try {
22037                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22038                    loaded.add(pkg.applicationInfo);
22039
22040                } catch (PackageManagerException e) {
22041                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22042                }
22043
22044                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22045                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22046                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22047                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22048                }
22049            }
22050        }
22051
22052        // Reconcile app data for all started/unlocked users
22053        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22054        final UserManager um = mContext.getSystemService(UserManager.class);
22055        UserManagerInternal umInternal = getUserManagerInternal();
22056        for (UserInfo user : um.getUsers()) {
22057            final int flags;
22058            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22059                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22060            } else if (umInternal.isUserRunning(user.id)) {
22061                flags = StorageManager.FLAG_STORAGE_DE;
22062            } else {
22063                continue;
22064            }
22065
22066            try {
22067                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22068                synchronized (mInstallLock) {
22069                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22070                }
22071            } catch (IllegalStateException e) {
22072                // Device was probably ejected, and we'll process that event momentarily
22073                Slog.w(TAG, "Failed to prepare storage: " + e);
22074            }
22075        }
22076
22077        synchronized (mPackages) {
22078            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22079            if (sdkUpdated) {
22080                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22081                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22082            }
22083            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22084                    mPermissionCallback);
22085
22086            // Yay, everything is now upgraded
22087            ver.forceCurrent();
22088
22089            mSettings.writeLPr();
22090        }
22091
22092        for (PackageFreezer freezer : freezers) {
22093            freezer.close();
22094        }
22095
22096        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22097        sendResourcesChangedBroadcast(true, false, loaded, null);
22098        mLoadedVolumes.add(vol.getId());
22099    }
22100
22101    private void unloadPrivatePackages(final VolumeInfo vol) {
22102        mHandler.post(new Runnable() {
22103            @Override
22104            public void run() {
22105                unloadPrivatePackagesInner(vol);
22106            }
22107        });
22108    }
22109
22110    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22111        final String volumeUuid = vol.fsUuid;
22112        if (TextUtils.isEmpty(volumeUuid)) {
22113            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22114            return;
22115        }
22116
22117        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22118        synchronized (mInstallLock) {
22119        synchronized (mPackages) {
22120            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22121            for (PackageSetting ps : packages) {
22122                if (ps.pkg == null) continue;
22123
22124                final ApplicationInfo info = ps.pkg.applicationInfo;
22125                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22126                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22127
22128                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22129                        "unloadPrivatePackagesInner")) {
22130                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22131                            false, null)) {
22132                        unloaded.add(info);
22133                    } else {
22134                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22135                    }
22136                }
22137
22138                // Try very hard to release any references to this package
22139                // so we don't risk the system server being killed due to
22140                // open FDs
22141                AttributeCache.instance().removePackage(ps.name);
22142            }
22143
22144            mSettings.writeLPr();
22145        }
22146        }
22147
22148        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22149        sendResourcesChangedBroadcast(false, false, unloaded, null);
22150        mLoadedVolumes.remove(vol.getId());
22151
22152        // Try very hard to release any references to this path so we don't risk
22153        // the system server being killed due to open FDs
22154        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22155
22156        for (int i = 0; i < 3; i++) {
22157            System.gc();
22158            System.runFinalization();
22159        }
22160    }
22161
22162    private void assertPackageKnown(String volumeUuid, String packageName)
22163            throws PackageManagerException {
22164        synchronized (mPackages) {
22165            // Normalize package name to handle renamed packages
22166            packageName = normalizePackageNameLPr(packageName);
22167
22168            final PackageSetting ps = mSettings.mPackages.get(packageName);
22169            if (ps == null) {
22170                throw new PackageManagerException("Package " + packageName + " is unknown");
22171            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22172                throw new PackageManagerException(
22173                        "Package " + packageName + " found on unknown volume " + volumeUuid
22174                                + "; expected volume " + ps.volumeUuid);
22175            }
22176        }
22177    }
22178
22179    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22180            throws PackageManagerException {
22181        synchronized (mPackages) {
22182            // Normalize package name to handle renamed packages
22183            packageName = normalizePackageNameLPr(packageName);
22184
22185            final PackageSetting ps = mSettings.mPackages.get(packageName);
22186            if (ps == null) {
22187                throw new PackageManagerException("Package " + packageName + " is unknown");
22188            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22189                throw new PackageManagerException(
22190                        "Package " + packageName + " found on unknown volume " + volumeUuid
22191                                + "; expected volume " + ps.volumeUuid);
22192            } else if (!ps.getInstalled(userId)) {
22193                throw new PackageManagerException(
22194                        "Package " + packageName + " not installed for user " + userId);
22195            }
22196        }
22197    }
22198
22199    private List<String> collectAbsoluteCodePaths() {
22200        synchronized (mPackages) {
22201            List<String> codePaths = new ArrayList<>();
22202            final int packageCount = mSettings.mPackages.size();
22203            for (int i = 0; i < packageCount; i++) {
22204                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22205                codePaths.add(ps.codePath.getAbsolutePath());
22206            }
22207            return codePaths;
22208        }
22209    }
22210
22211    /**
22212     * Examine all apps present on given mounted volume, and destroy apps that
22213     * aren't expected, either due to uninstallation or reinstallation on
22214     * another volume.
22215     */
22216    private void reconcileApps(String volumeUuid) {
22217        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22218        List<File> filesToDelete = null;
22219
22220        final File[] files = FileUtils.listFilesOrEmpty(
22221                Environment.getDataAppDirectory(volumeUuid));
22222        for (File file : files) {
22223            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22224                    && !PackageInstallerService.isStageName(file.getName());
22225            if (!isPackage) {
22226                // Ignore entries which are not packages
22227                continue;
22228            }
22229
22230            String absolutePath = file.getAbsolutePath();
22231
22232            boolean pathValid = false;
22233            final int absoluteCodePathCount = absoluteCodePaths.size();
22234            for (int i = 0; i < absoluteCodePathCount; i++) {
22235                String absoluteCodePath = absoluteCodePaths.get(i);
22236                if (absolutePath.startsWith(absoluteCodePath)) {
22237                    pathValid = true;
22238                    break;
22239                }
22240            }
22241
22242            if (!pathValid) {
22243                if (filesToDelete == null) {
22244                    filesToDelete = new ArrayList<>();
22245                }
22246                filesToDelete.add(file);
22247            }
22248        }
22249
22250        if (filesToDelete != null) {
22251            final int fileToDeleteCount = filesToDelete.size();
22252            for (int i = 0; i < fileToDeleteCount; i++) {
22253                File fileToDelete = filesToDelete.get(i);
22254                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22255                synchronized (mInstallLock) {
22256                    removeCodePathLI(fileToDelete);
22257                }
22258            }
22259        }
22260    }
22261
22262    /**
22263     * Reconcile all app data for the given user.
22264     * <p>
22265     * Verifies that directories exist and that ownership and labeling is
22266     * correct for all installed apps on all mounted volumes.
22267     */
22268    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22269        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22270        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22271            final String volumeUuid = vol.getFsUuid();
22272            synchronized (mInstallLock) {
22273                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22274            }
22275        }
22276    }
22277
22278    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22279            boolean migrateAppData) {
22280        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22281    }
22282
22283    /**
22284     * Reconcile all app data on given mounted volume.
22285     * <p>
22286     * Destroys app data that isn't expected, either due to uninstallation or
22287     * reinstallation on another volume.
22288     * <p>
22289     * Verifies that directories exist and that ownership and labeling is
22290     * correct for all installed apps.
22291     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22292     */
22293    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22294            boolean migrateAppData, boolean onlyCoreApps) {
22295        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22296                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22297        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22298
22299        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22300        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22301
22302        // First look for stale data that doesn't belong, and check if things
22303        // have changed since we did our last restorecon
22304        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22305            if (StorageManager.isFileEncryptedNativeOrEmulated()
22306                    && !StorageManager.isUserKeyUnlocked(userId)) {
22307                throw new RuntimeException(
22308                        "Yikes, someone asked us to reconcile CE storage while " + userId
22309                                + " was still locked; this would have caused massive data loss!");
22310            }
22311
22312            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22313            for (File file : files) {
22314                final String packageName = file.getName();
22315                try {
22316                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22317                } catch (PackageManagerException e) {
22318                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22319                    try {
22320                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22321                                StorageManager.FLAG_STORAGE_CE, 0);
22322                    } catch (InstallerException e2) {
22323                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22324                    }
22325                }
22326            }
22327        }
22328        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22329            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22330            for (File file : files) {
22331                final String packageName = file.getName();
22332                try {
22333                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22334                } catch (PackageManagerException e) {
22335                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22336                    try {
22337                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22338                                StorageManager.FLAG_STORAGE_DE, 0);
22339                    } catch (InstallerException e2) {
22340                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22341                    }
22342                }
22343            }
22344        }
22345
22346        // Ensure that data directories are ready to roll for all packages
22347        // installed for this volume and user
22348        final List<PackageSetting> packages;
22349        synchronized (mPackages) {
22350            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22351        }
22352        int preparedCount = 0;
22353        for (PackageSetting ps : packages) {
22354            final String packageName = ps.name;
22355            if (ps.pkg == null) {
22356                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22357                // TODO: might be due to legacy ASEC apps; we should circle back
22358                // and reconcile again once they're scanned
22359                continue;
22360            }
22361            // Skip non-core apps if requested
22362            if (onlyCoreApps && !ps.pkg.coreApp) {
22363                result.add(packageName);
22364                continue;
22365            }
22366
22367            if (ps.getInstalled(userId)) {
22368                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22369                preparedCount++;
22370            }
22371        }
22372
22373        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22374        return result;
22375    }
22376
22377    /**
22378     * Prepare app data for the given app just after it was installed or
22379     * upgraded. This method carefully only touches users that it's installed
22380     * for, and it forces a restorecon to handle any seinfo changes.
22381     * <p>
22382     * Verifies that directories exist and that ownership and labeling is
22383     * correct for all installed apps. If there is an ownership mismatch, it
22384     * will try recovering system apps by wiping data; third-party app data is
22385     * left intact.
22386     * <p>
22387     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22388     */
22389    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22390        final PackageSetting ps;
22391        synchronized (mPackages) {
22392            ps = mSettings.mPackages.get(pkg.packageName);
22393            mSettings.writeKernelMappingLPr(ps);
22394        }
22395
22396        final UserManager um = mContext.getSystemService(UserManager.class);
22397        UserManagerInternal umInternal = getUserManagerInternal();
22398        for (UserInfo user : um.getUsers()) {
22399            final int flags;
22400            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22401                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22402            } else if (umInternal.isUserRunning(user.id)) {
22403                flags = StorageManager.FLAG_STORAGE_DE;
22404            } else {
22405                continue;
22406            }
22407
22408            if (ps.getInstalled(user.id)) {
22409                // TODO: when user data is locked, mark that we're still dirty
22410                prepareAppDataLIF(pkg, user.id, flags);
22411            }
22412        }
22413    }
22414
22415    /**
22416     * Prepare app data for the given app.
22417     * <p>
22418     * Verifies that directories exist and that ownership and labeling is
22419     * correct for all installed apps. If there is an ownership mismatch, this
22420     * will try recovering system apps by wiping data; third-party app data is
22421     * left intact.
22422     */
22423    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22424        if (pkg == null) {
22425            Slog.wtf(TAG, "Package was null!", new Throwable());
22426            return;
22427        }
22428        prepareAppDataLeafLIF(pkg, userId, flags);
22429        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22430        for (int i = 0; i < childCount; i++) {
22431            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22432        }
22433    }
22434
22435    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22436            boolean maybeMigrateAppData) {
22437        prepareAppDataLIF(pkg, userId, flags);
22438
22439        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22440            // We may have just shuffled around app data directories, so
22441            // prepare them one more time
22442            prepareAppDataLIF(pkg, userId, flags);
22443        }
22444    }
22445
22446    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22447        if (DEBUG_APP_DATA) {
22448            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22449                    + Integer.toHexString(flags));
22450        }
22451
22452        final PackageSetting ps;
22453        synchronized (mPackages) {
22454            ps = mSettings.mPackages.get(pkg.packageName);
22455        }
22456        final String volumeUuid = pkg.volumeUuid;
22457        final String packageName = pkg.packageName;
22458        final ApplicationInfo app = (ps == null)
22459                ? pkg.applicationInfo
22460                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22461
22462        final int appId = UserHandle.getAppId(app.uid);
22463
22464        Preconditions.checkNotNull(app.seInfo);
22465
22466        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22467        long ceDataInode = -1;
22468        try {
22469            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22470                    appId, seInfo, app.targetSdkVersion);
22471        } catch (InstallerException e) {
22472            if (app.isSystemApp()) {
22473                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22474                        + ", but trying to recover: " + e);
22475                destroyAppDataLeafLIF(pkg, userId, flags);
22476                try {
22477                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22478                            appId, seInfo, app.targetSdkVersion);
22479                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22480                } catch (InstallerException e2) {
22481                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22482                }
22483            } else {
22484                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22485            }
22486        }
22487        // Prepare the application profiles only for upgrades and first boot (so that we don't
22488        // repeat the same operation at each boot).
22489        // We only have to cover the upgrade and first boot here because for app installs we
22490        // prepare the profiles before invoking dexopt (in installPackageLI).
22491        //
22492        // We also have to cover non system users because we do not call the usual install package
22493        // methods for them.
22494        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22495            mArtManagerService.prepareAppProfiles(pkg, userId);
22496        }
22497
22498        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22499            // TODO: mark this structure as dirty so we persist it!
22500            synchronized (mPackages) {
22501                if (ps != null) {
22502                    ps.setCeDataInode(ceDataInode, userId);
22503                }
22504            }
22505        }
22506
22507        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22508    }
22509
22510    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22511        if (pkg == null) {
22512            Slog.wtf(TAG, "Package was null!", new Throwable());
22513            return;
22514        }
22515        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22516        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22517        for (int i = 0; i < childCount; i++) {
22518            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22519        }
22520    }
22521
22522    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22523        final String volumeUuid = pkg.volumeUuid;
22524        final String packageName = pkg.packageName;
22525        final ApplicationInfo app = pkg.applicationInfo;
22526
22527        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22528            // Create a native library symlink only if we have native libraries
22529            // and if the native libraries are 32 bit libraries. We do not provide
22530            // this symlink for 64 bit libraries.
22531            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22532                final String nativeLibPath = app.nativeLibraryDir;
22533                try {
22534                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22535                            nativeLibPath, userId);
22536                } catch (InstallerException e) {
22537                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22538                }
22539            }
22540        }
22541    }
22542
22543    /**
22544     * For system apps on non-FBE devices, this method migrates any existing
22545     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22546     * requested by the app.
22547     */
22548    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22549        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22550                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22551            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22552                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22553            try {
22554                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22555                        storageTarget);
22556            } catch (InstallerException e) {
22557                logCriticalInfo(Log.WARN,
22558                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22559            }
22560            return true;
22561        } else {
22562            return false;
22563        }
22564    }
22565
22566    public PackageFreezer freezePackage(String packageName, String killReason) {
22567        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22568    }
22569
22570    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22571        return new PackageFreezer(packageName, userId, killReason);
22572    }
22573
22574    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22575            String killReason) {
22576        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22577    }
22578
22579    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22580            String killReason) {
22581        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22582            return new PackageFreezer();
22583        } else {
22584            return freezePackage(packageName, userId, killReason);
22585        }
22586    }
22587
22588    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22589            String killReason) {
22590        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22591    }
22592
22593    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22594            String killReason) {
22595        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22596            return new PackageFreezer();
22597        } else {
22598            return freezePackage(packageName, userId, killReason);
22599        }
22600    }
22601
22602    /**
22603     * Class that freezes and kills the given package upon creation, and
22604     * unfreezes it upon closing. This is typically used when doing surgery on
22605     * app code/data to prevent the app from running while you're working.
22606     */
22607    private class PackageFreezer implements AutoCloseable {
22608        private final String mPackageName;
22609        private final PackageFreezer[] mChildren;
22610
22611        private final boolean mWeFroze;
22612
22613        private final AtomicBoolean mClosed = new AtomicBoolean();
22614        private final CloseGuard mCloseGuard = CloseGuard.get();
22615
22616        /**
22617         * Create and return a stub freezer that doesn't actually do anything,
22618         * typically used when someone requested
22619         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22620         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22621         */
22622        public PackageFreezer() {
22623            mPackageName = null;
22624            mChildren = null;
22625            mWeFroze = false;
22626            mCloseGuard.open("close");
22627        }
22628
22629        public PackageFreezer(String packageName, int userId, String killReason) {
22630            synchronized (mPackages) {
22631                mPackageName = packageName;
22632                mWeFroze = mFrozenPackages.add(mPackageName);
22633
22634                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22635                if (ps != null) {
22636                    killApplication(ps.name, ps.appId, userId, killReason);
22637                }
22638
22639                final PackageParser.Package p = mPackages.get(packageName);
22640                if (p != null && p.childPackages != null) {
22641                    final int N = p.childPackages.size();
22642                    mChildren = new PackageFreezer[N];
22643                    for (int i = 0; i < N; i++) {
22644                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22645                                userId, killReason);
22646                    }
22647                } else {
22648                    mChildren = null;
22649                }
22650            }
22651            mCloseGuard.open("close");
22652        }
22653
22654        @Override
22655        protected void finalize() throws Throwable {
22656            try {
22657                if (mCloseGuard != null) {
22658                    mCloseGuard.warnIfOpen();
22659                }
22660
22661                close();
22662            } finally {
22663                super.finalize();
22664            }
22665        }
22666
22667        @Override
22668        public void close() {
22669            mCloseGuard.close();
22670            if (mClosed.compareAndSet(false, true)) {
22671                synchronized (mPackages) {
22672                    if (mWeFroze) {
22673                        mFrozenPackages.remove(mPackageName);
22674                    }
22675
22676                    if (mChildren != null) {
22677                        for (PackageFreezer freezer : mChildren) {
22678                            freezer.close();
22679                        }
22680                    }
22681                }
22682            }
22683        }
22684    }
22685
22686    /**
22687     * Verify that given package is currently frozen.
22688     */
22689    private void checkPackageFrozen(String packageName) {
22690        synchronized (mPackages) {
22691            if (!mFrozenPackages.contains(packageName)) {
22692                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22693            }
22694        }
22695    }
22696
22697    @Override
22698    public int movePackage(final String packageName, final String volumeUuid) {
22699        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22700
22701        final int callingUid = Binder.getCallingUid();
22702        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22703        final int moveId = mNextMoveId.getAndIncrement();
22704        mHandler.post(new Runnable() {
22705            @Override
22706            public void run() {
22707                try {
22708                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22709                } catch (PackageManagerException e) {
22710                    Slog.w(TAG, "Failed to move " + packageName, e);
22711                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22712                }
22713            }
22714        });
22715        return moveId;
22716    }
22717
22718    private void movePackageInternal(final String packageName, final String volumeUuid,
22719            final int moveId, final int callingUid, UserHandle user)
22720                    throws PackageManagerException {
22721        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22722        final PackageManager pm = mContext.getPackageManager();
22723
22724        final boolean currentAsec;
22725        final String currentVolumeUuid;
22726        final File codeFile;
22727        final String installerPackageName;
22728        final String packageAbiOverride;
22729        final int appId;
22730        final String seinfo;
22731        final String label;
22732        final int targetSdkVersion;
22733        final PackageFreezer freezer;
22734        final int[] installedUserIds;
22735
22736        // reader
22737        synchronized (mPackages) {
22738            final PackageParser.Package pkg = mPackages.get(packageName);
22739            final PackageSetting ps = mSettings.mPackages.get(packageName);
22740            if (pkg == null
22741                    || ps == null
22742                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22743                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22744            }
22745            if (pkg.applicationInfo.isSystemApp()) {
22746                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22747                        "Cannot move system application");
22748            }
22749
22750            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22751            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22752                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22753            if (isInternalStorage && !allow3rdPartyOnInternal) {
22754                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22755                        "3rd party apps are not allowed on internal storage");
22756            }
22757
22758            if (pkg.applicationInfo.isExternalAsec()) {
22759                currentAsec = true;
22760                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22761            } else if (pkg.applicationInfo.isForwardLocked()) {
22762                currentAsec = true;
22763                currentVolumeUuid = "forward_locked";
22764            } else {
22765                currentAsec = false;
22766                currentVolumeUuid = ps.volumeUuid;
22767
22768                final File probe = new File(pkg.codePath);
22769                final File probeOat = new File(probe, "oat");
22770                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22771                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22772                            "Move only supported for modern cluster style installs");
22773                }
22774            }
22775
22776            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22777                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22778                        "Package already moved to " + volumeUuid);
22779            }
22780            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22781                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22782                        "Device admin cannot be moved");
22783            }
22784
22785            if (mFrozenPackages.contains(packageName)) {
22786                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22787                        "Failed to move already frozen package");
22788            }
22789
22790            codeFile = new File(pkg.codePath);
22791            installerPackageName = ps.installerPackageName;
22792            packageAbiOverride = ps.cpuAbiOverrideString;
22793            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22794            seinfo = pkg.applicationInfo.seInfo;
22795            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22796            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22797            freezer = freezePackage(packageName, "movePackageInternal");
22798            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22799        }
22800
22801        final Bundle extras = new Bundle();
22802        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22803        extras.putString(Intent.EXTRA_TITLE, label);
22804        mMoveCallbacks.notifyCreated(moveId, extras);
22805
22806        int installFlags;
22807        final boolean moveCompleteApp;
22808        final File measurePath;
22809
22810        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22811            installFlags = INSTALL_INTERNAL;
22812            moveCompleteApp = !currentAsec;
22813            measurePath = Environment.getDataAppDirectory(volumeUuid);
22814        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22815            installFlags = INSTALL_EXTERNAL;
22816            moveCompleteApp = false;
22817            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22818        } else {
22819            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22820            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22821                    || !volume.isMountedWritable()) {
22822                freezer.close();
22823                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22824                        "Move location not mounted private volume");
22825            }
22826
22827            Preconditions.checkState(!currentAsec);
22828
22829            installFlags = INSTALL_INTERNAL;
22830            moveCompleteApp = true;
22831            measurePath = Environment.getDataAppDirectory(volumeUuid);
22832        }
22833
22834        // If we're moving app data around, we need all the users unlocked
22835        if (moveCompleteApp) {
22836            for (int userId : installedUserIds) {
22837                if (StorageManager.isFileEncryptedNativeOrEmulated()
22838                        && !StorageManager.isUserKeyUnlocked(userId)) {
22839                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22840                            "User " + userId + " must be unlocked");
22841                }
22842            }
22843        }
22844
22845        final PackageStats stats = new PackageStats(null, -1);
22846        synchronized (mInstaller) {
22847            for (int userId : installedUserIds) {
22848                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22849                    freezer.close();
22850                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22851                            "Failed to measure package size");
22852                }
22853            }
22854        }
22855
22856        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22857                + stats.dataSize);
22858
22859        final long startFreeBytes = measurePath.getUsableSpace();
22860        final long sizeBytes;
22861        if (moveCompleteApp) {
22862            sizeBytes = stats.codeSize + stats.dataSize;
22863        } else {
22864            sizeBytes = stats.codeSize;
22865        }
22866
22867        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22868            freezer.close();
22869            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22870                    "Not enough free space to move");
22871        }
22872
22873        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22874
22875        final CountDownLatch installedLatch = new CountDownLatch(1);
22876        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22877            @Override
22878            public void onUserActionRequired(Intent intent) throws RemoteException {
22879                throw new IllegalStateException();
22880            }
22881
22882            @Override
22883            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22884                    Bundle extras) throws RemoteException {
22885                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22886                        + PackageManager.installStatusToString(returnCode, msg));
22887
22888                installedLatch.countDown();
22889                freezer.close();
22890
22891                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22892                switch (status) {
22893                    case PackageInstaller.STATUS_SUCCESS:
22894                        mMoveCallbacks.notifyStatusChanged(moveId,
22895                                PackageManager.MOVE_SUCCEEDED);
22896                        break;
22897                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22898                        mMoveCallbacks.notifyStatusChanged(moveId,
22899                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22900                        break;
22901                    default:
22902                        mMoveCallbacks.notifyStatusChanged(moveId,
22903                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22904                        break;
22905                }
22906            }
22907        };
22908
22909        final MoveInfo move;
22910        if (moveCompleteApp) {
22911            // Kick off a thread to report progress estimates
22912            new Thread() {
22913                @Override
22914                public void run() {
22915                    while (true) {
22916                        try {
22917                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22918                                break;
22919                            }
22920                        } catch (InterruptedException ignored) {
22921                        }
22922
22923                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22924                        final int progress = 10 + (int) MathUtils.constrain(
22925                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22926                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22927                    }
22928                }
22929            }.start();
22930
22931            final String dataAppName = codeFile.getName();
22932            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22933                    dataAppName, appId, seinfo, targetSdkVersion);
22934        } else {
22935            move = null;
22936        }
22937
22938        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22939
22940        final Message msg = mHandler.obtainMessage(INIT_COPY);
22941        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22942        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22943                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22944                packageAbiOverride, null /*grantedPermissions*/,
22945                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22946        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22947        msg.obj = params;
22948
22949        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22950                System.identityHashCode(msg.obj));
22951        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22952                System.identityHashCode(msg.obj));
22953
22954        mHandler.sendMessage(msg);
22955    }
22956
22957    @Override
22958    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22959        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22960
22961        final int realMoveId = mNextMoveId.getAndIncrement();
22962        final Bundle extras = new Bundle();
22963        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22964        mMoveCallbacks.notifyCreated(realMoveId, extras);
22965
22966        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22967            @Override
22968            public void onCreated(int moveId, Bundle extras) {
22969                // Ignored
22970            }
22971
22972            @Override
22973            public void onStatusChanged(int moveId, int status, long estMillis) {
22974                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22975            }
22976        };
22977
22978        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22979        storage.setPrimaryStorageUuid(volumeUuid, callback);
22980        return realMoveId;
22981    }
22982
22983    @Override
22984    public int getMoveStatus(int moveId) {
22985        mContext.enforceCallingOrSelfPermission(
22986                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22987        return mMoveCallbacks.mLastStatus.get(moveId);
22988    }
22989
22990    @Override
22991    public void registerMoveCallback(IPackageMoveObserver callback) {
22992        mContext.enforceCallingOrSelfPermission(
22993                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22994        mMoveCallbacks.register(callback);
22995    }
22996
22997    @Override
22998    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22999        mContext.enforceCallingOrSelfPermission(
23000                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23001        mMoveCallbacks.unregister(callback);
23002    }
23003
23004    @Override
23005    public boolean setInstallLocation(int loc) {
23006        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23007                null);
23008        if (getInstallLocation() == loc) {
23009            return true;
23010        }
23011        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23012                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23013            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23014                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23015            return true;
23016        }
23017        return false;
23018   }
23019
23020    @Override
23021    public int getInstallLocation() {
23022        // allow instant app access
23023        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23024                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23025                PackageHelper.APP_INSTALL_AUTO);
23026    }
23027
23028    /** Called by UserManagerService */
23029    void cleanUpUser(UserManagerService userManager, int userHandle) {
23030        synchronized (mPackages) {
23031            mDirtyUsers.remove(userHandle);
23032            mUserNeedsBadging.delete(userHandle);
23033            mSettings.removeUserLPw(userHandle);
23034            mPendingBroadcasts.remove(userHandle);
23035            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23036            removeUnusedPackagesLPw(userManager, userHandle);
23037        }
23038    }
23039
23040    /**
23041     * We're removing userHandle and would like to remove any downloaded packages
23042     * that are no longer in use by any other user.
23043     * @param userHandle the user being removed
23044     */
23045    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23046        final boolean DEBUG_CLEAN_APKS = false;
23047        int [] users = userManager.getUserIds();
23048        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23049        while (psit.hasNext()) {
23050            PackageSetting ps = psit.next();
23051            if (ps.pkg == null) {
23052                continue;
23053            }
23054            final String packageName = ps.pkg.packageName;
23055            // Skip over if system app
23056            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23057                continue;
23058            }
23059            if (DEBUG_CLEAN_APKS) {
23060                Slog.i(TAG, "Checking package " + packageName);
23061            }
23062            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23063            if (keep) {
23064                if (DEBUG_CLEAN_APKS) {
23065                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23066                }
23067            } else {
23068                for (int i = 0; i < users.length; i++) {
23069                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23070                        keep = true;
23071                        if (DEBUG_CLEAN_APKS) {
23072                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23073                                    + users[i]);
23074                        }
23075                        break;
23076                    }
23077                }
23078            }
23079            if (!keep) {
23080                if (DEBUG_CLEAN_APKS) {
23081                    Slog.i(TAG, "  Removing package " + packageName);
23082                }
23083                mHandler.post(new Runnable() {
23084                    public void run() {
23085                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23086                                userHandle, 0);
23087                    } //end run
23088                });
23089            }
23090        }
23091    }
23092
23093    /** Called by UserManagerService */
23094    void createNewUser(int userId, String[] disallowedPackages) {
23095        synchronized (mInstallLock) {
23096            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23097        }
23098        synchronized (mPackages) {
23099            scheduleWritePackageRestrictionsLocked(userId);
23100            scheduleWritePackageListLocked(userId);
23101            applyFactoryDefaultBrowserLPw(userId);
23102            primeDomainVerificationsLPw(userId);
23103        }
23104    }
23105
23106    void onNewUserCreated(final int userId) {
23107        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23108        synchronized(mPackages) {
23109            // If permission review for legacy apps is required, we represent
23110            // dagerous permissions for such apps as always granted runtime
23111            // permissions to keep per user flag state whether review is needed.
23112            // Hence, if a new user is added we have to propagate dangerous
23113            // permission grants for these legacy apps.
23114            if (mSettings.mPermissions.mPermissionReviewRequired) {
23115// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23116                mPermissionManager.updateAllPermissions(
23117                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23118                        mPermissionCallback);
23119            }
23120        }
23121    }
23122
23123    @Override
23124    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23125        mContext.enforceCallingOrSelfPermission(
23126                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23127                "Only package verification agents can read the verifier device identity");
23128
23129        synchronized (mPackages) {
23130            return mSettings.getVerifierDeviceIdentityLPw();
23131        }
23132    }
23133
23134    @Override
23135    public void setPermissionEnforced(String permission, boolean enforced) {
23136        // TODO: Now that we no longer change GID for storage, this should to away.
23137        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23138                "setPermissionEnforced");
23139        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23140            synchronized (mPackages) {
23141                if (mSettings.mReadExternalStorageEnforced == null
23142                        || mSettings.mReadExternalStorageEnforced != enforced) {
23143                    mSettings.mReadExternalStorageEnforced =
23144                            enforced ? Boolean.TRUE : Boolean.FALSE;
23145                    mSettings.writeLPr();
23146                }
23147            }
23148            // kill any non-foreground processes so we restart them and
23149            // grant/revoke the GID.
23150            final IActivityManager am = ActivityManager.getService();
23151            if (am != null) {
23152                final long token = Binder.clearCallingIdentity();
23153                try {
23154                    am.killProcessesBelowForeground("setPermissionEnforcement");
23155                } catch (RemoteException e) {
23156                } finally {
23157                    Binder.restoreCallingIdentity(token);
23158                }
23159            }
23160        } else {
23161            throw new IllegalArgumentException("No selective enforcement for " + permission);
23162        }
23163    }
23164
23165    @Override
23166    @Deprecated
23167    public boolean isPermissionEnforced(String permission) {
23168        // allow instant applications
23169        return true;
23170    }
23171
23172    @Override
23173    public boolean isStorageLow() {
23174        // allow instant applications
23175        final long token = Binder.clearCallingIdentity();
23176        try {
23177            final DeviceStorageMonitorInternal
23178                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23179            if (dsm != null) {
23180                return dsm.isMemoryLow();
23181            } else {
23182                return false;
23183            }
23184        } finally {
23185            Binder.restoreCallingIdentity(token);
23186        }
23187    }
23188
23189    @Override
23190    public IPackageInstaller getPackageInstaller() {
23191        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23192            return null;
23193        }
23194        return mInstallerService;
23195    }
23196
23197    @Override
23198    public IArtManager getArtManager() {
23199        return mArtManagerService;
23200    }
23201
23202    private boolean userNeedsBadging(int userId) {
23203        int index = mUserNeedsBadging.indexOfKey(userId);
23204        if (index < 0) {
23205            final UserInfo userInfo;
23206            final long token = Binder.clearCallingIdentity();
23207            try {
23208                userInfo = sUserManager.getUserInfo(userId);
23209            } finally {
23210                Binder.restoreCallingIdentity(token);
23211            }
23212            final boolean b;
23213            if (userInfo != null && userInfo.isManagedProfile()) {
23214                b = true;
23215            } else {
23216                b = false;
23217            }
23218            mUserNeedsBadging.put(userId, b);
23219            return b;
23220        }
23221        return mUserNeedsBadging.valueAt(index);
23222    }
23223
23224    @Override
23225    public KeySet getKeySetByAlias(String packageName, String alias) {
23226        if (packageName == null || alias == null) {
23227            return null;
23228        }
23229        synchronized(mPackages) {
23230            final PackageParser.Package pkg = mPackages.get(packageName);
23231            if (pkg == null) {
23232                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23233                throw new IllegalArgumentException("Unknown package: " + packageName);
23234            }
23235            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23236            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23237                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23238                throw new IllegalArgumentException("Unknown package: " + packageName);
23239            }
23240            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23241            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23242        }
23243    }
23244
23245    @Override
23246    public KeySet getSigningKeySet(String packageName) {
23247        if (packageName == null) {
23248            return null;
23249        }
23250        synchronized(mPackages) {
23251            final int callingUid = Binder.getCallingUid();
23252            final int callingUserId = UserHandle.getUserId(callingUid);
23253            final PackageParser.Package pkg = mPackages.get(packageName);
23254            if (pkg == null) {
23255                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23256                throw new IllegalArgumentException("Unknown package: " + packageName);
23257            }
23258            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23259            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23260                // filter and pretend the package doesn't exist
23261                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23262                        + ", uid:" + callingUid);
23263                throw new IllegalArgumentException("Unknown package: " + packageName);
23264            }
23265            if (pkg.applicationInfo.uid != callingUid
23266                    && Process.SYSTEM_UID != callingUid) {
23267                throw new SecurityException("May not access signing KeySet of other apps.");
23268            }
23269            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23270            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23271        }
23272    }
23273
23274    @Override
23275    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23276        final int callingUid = Binder.getCallingUid();
23277        if (getInstantAppPackageName(callingUid) != null) {
23278            return false;
23279        }
23280        if (packageName == null || ks == null) {
23281            return false;
23282        }
23283        synchronized(mPackages) {
23284            final PackageParser.Package pkg = mPackages.get(packageName);
23285            if (pkg == null
23286                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23287                            UserHandle.getUserId(callingUid))) {
23288                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23289                throw new IllegalArgumentException("Unknown package: " + packageName);
23290            }
23291            IBinder ksh = ks.getToken();
23292            if (ksh instanceof KeySetHandle) {
23293                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23294                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23295            }
23296            return false;
23297        }
23298    }
23299
23300    @Override
23301    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23302        final int callingUid = Binder.getCallingUid();
23303        if (getInstantAppPackageName(callingUid) != null) {
23304            return false;
23305        }
23306        if (packageName == null || ks == null) {
23307            return false;
23308        }
23309        synchronized(mPackages) {
23310            final PackageParser.Package pkg = mPackages.get(packageName);
23311            if (pkg == null
23312                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23313                            UserHandle.getUserId(callingUid))) {
23314                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23315                throw new IllegalArgumentException("Unknown package: " + packageName);
23316            }
23317            IBinder ksh = ks.getToken();
23318            if (ksh instanceof KeySetHandle) {
23319                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23320                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23321            }
23322            return false;
23323        }
23324    }
23325
23326    private void deletePackageIfUnusedLPr(final String packageName) {
23327        PackageSetting ps = mSettings.mPackages.get(packageName);
23328        if (ps == null) {
23329            return;
23330        }
23331        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23332            // TODO Implement atomic delete if package is unused
23333            // It is currently possible that the package will be deleted even if it is installed
23334            // after this method returns.
23335            mHandler.post(new Runnable() {
23336                public void run() {
23337                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23338                            0, PackageManager.DELETE_ALL_USERS);
23339                }
23340            });
23341        }
23342    }
23343
23344    /**
23345     * Check and throw if the given before/after packages would be considered a
23346     * downgrade.
23347     */
23348    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23349            throws PackageManagerException {
23350        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23351            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23352                    "Update version code " + after.versionCode + " is older than current "
23353                    + before.getLongVersionCode());
23354        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23355            if (after.baseRevisionCode < before.baseRevisionCode) {
23356                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23357                        "Update base revision code " + after.baseRevisionCode
23358                        + " is older than current " + before.baseRevisionCode);
23359            }
23360
23361            if (!ArrayUtils.isEmpty(after.splitNames)) {
23362                for (int i = 0; i < after.splitNames.length; i++) {
23363                    final String splitName = after.splitNames[i];
23364                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23365                    if (j != -1) {
23366                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23367                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23368                                    "Update split " + splitName + " revision code "
23369                                    + after.splitRevisionCodes[i] + " is older than current "
23370                                    + before.splitRevisionCodes[j]);
23371                        }
23372                    }
23373                }
23374            }
23375        }
23376    }
23377
23378    private static class MoveCallbacks extends Handler {
23379        private static final int MSG_CREATED = 1;
23380        private static final int MSG_STATUS_CHANGED = 2;
23381
23382        private final RemoteCallbackList<IPackageMoveObserver>
23383                mCallbacks = new RemoteCallbackList<>();
23384
23385        private final SparseIntArray mLastStatus = new SparseIntArray();
23386
23387        public MoveCallbacks(Looper looper) {
23388            super(looper);
23389        }
23390
23391        public void register(IPackageMoveObserver callback) {
23392            mCallbacks.register(callback);
23393        }
23394
23395        public void unregister(IPackageMoveObserver callback) {
23396            mCallbacks.unregister(callback);
23397        }
23398
23399        @Override
23400        public void handleMessage(Message msg) {
23401            final SomeArgs args = (SomeArgs) msg.obj;
23402            final int n = mCallbacks.beginBroadcast();
23403            for (int i = 0; i < n; i++) {
23404                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23405                try {
23406                    invokeCallback(callback, msg.what, args);
23407                } catch (RemoteException ignored) {
23408                }
23409            }
23410            mCallbacks.finishBroadcast();
23411            args.recycle();
23412        }
23413
23414        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23415                throws RemoteException {
23416            switch (what) {
23417                case MSG_CREATED: {
23418                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23419                    break;
23420                }
23421                case MSG_STATUS_CHANGED: {
23422                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23423                    break;
23424                }
23425            }
23426        }
23427
23428        private void notifyCreated(int moveId, Bundle extras) {
23429            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23430
23431            final SomeArgs args = SomeArgs.obtain();
23432            args.argi1 = moveId;
23433            args.arg2 = extras;
23434            obtainMessage(MSG_CREATED, args).sendToTarget();
23435        }
23436
23437        private void notifyStatusChanged(int moveId, int status) {
23438            notifyStatusChanged(moveId, status, -1);
23439        }
23440
23441        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23442            Slog.v(TAG, "Move " + moveId + " status " + status);
23443
23444            final SomeArgs args = SomeArgs.obtain();
23445            args.argi1 = moveId;
23446            args.argi2 = status;
23447            args.arg3 = estMillis;
23448            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23449
23450            synchronized (mLastStatus) {
23451                mLastStatus.put(moveId, status);
23452            }
23453        }
23454    }
23455
23456    private final static class OnPermissionChangeListeners extends Handler {
23457        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23458
23459        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23460                new RemoteCallbackList<>();
23461
23462        public OnPermissionChangeListeners(Looper looper) {
23463            super(looper);
23464        }
23465
23466        @Override
23467        public void handleMessage(Message msg) {
23468            switch (msg.what) {
23469                case MSG_ON_PERMISSIONS_CHANGED: {
23470                    final int uid = msg.arg1;
23471                    handleOnPermissionsChanged(uid);
23472                } break;
23473            }
23474        }
23475
23476        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23477            mPermissionListeners.register(listener);
23478
23479        }
23480
23481        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23482            mPermissionListeners.unregister(listener);
23483        }
23484
23485        public void onPermissionsChanged(int uid) {
23486            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23487                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23488            }
23489        }
23490
23491        private void handleOnPermissionsChanged(int uid) {
23492            final int count = mPermissionListeners.beginBroadcast();
23493            try {
23494                for (int i = 0; i < count; i++) {
23495                    IOnPermissionsChangeListener callback = mPermissionListeners
23496                            .getBroadcastItem(i);
23497                    try {
23498                        callback.onPermissionsChanged(uid);
23499                    } catch (RemoteException e) {
23500                        Log.e(TAG, "Permission listener is dead", e);
23501                    }
23502                }
23503            } finally {
23504                mPermissionListeners.finishBroadcast();
23505            }
23506        }
23507    }
23508
23509    private class PackageManagerNative extends IPackageManagerNative.Stub {
23510        @Override
23511        public String[] getNamesForUids(int[] uids) throws RemoteException {
23512            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23513            // massage results so they can be parsed by the native binder
23514            for (int i = results.length - 1; i >= 0; --i) {
23515                if (results[i] == null) {
23516                    results[i] = "";
23517                }
23518            }
23519            return results;
23520        }
23521
23522        // NB: this differentiates between preloads and sideloads
23523        @Override
23524        public String getInstallerForPackage(String packageName) throws RemoteException {
23525            final String installerName = getInstallerPackageName(packageName);
23526            if (!TextUtils.isEmpty(installerName)) {
23527                return installerName;
23528            }
23529            // differentiate between preload and sideload
23530            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23531            ApplicationInfo appInfo = getApplicationInfo(packageName,
23532                                    /*flags*/ 0,
23533                                    /*userId*/ callingUser);
23534            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23535                return "preload";
23536            }
23537            return "";
23538        }
23539
23540        @Override
23541        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23542            try {
23543                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23544                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23545                if (pInfo != null) {
23546                    return pInfo.getLongVersionCode();
23547                }
23548            } catch (Exception e) {
23549            }
23550            return 0;
23551        }
23552    }
23553
23554    private class PackageManagerInternalImpl extends PackageManagerInternal {
23555        @Override
23556        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23557                int flagValues, int userId) {
23558            PackageManagerService.this.updatePermissionFlags(
23559                    permName, packageName, flagMask, flagValues, userId);
23560        }
23561
23562        @Override
23563        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23564            SigningDetails sd = getSigningDetails(packageName);
23565            if (sd == null) {
23566                return false;
23567            }
23568            return sd.hasSha256Certificate(restoringFromSigHash,
23569                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23570        }
23571
23572        @Override
23573        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23574            SigningDetails sd = getSigningDetails(packageName);
23575            if (sd == null) {
23576                return false;
23577            }
23578            return sd.hasCertificate(restoringFromSig,
23579                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23580        }
23581
23582        private SigningDetails getSigningDetails(@NonNull String packageName) {
23583            synchronized (mPackages) {
23584                PackageParser.Package p = mPackages.get(packageName);
23585                if (p == null) {
23586                    return null;
23587                }
23588                return p.mSigningDetails;
23589            }
23590        }
23591
23592        @Override
23593        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23594            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23595        }
23596
23597        @Override
23598        public boolean isInstantApp(String packageName, int userId) {
23599            return PackageManagerService.this.isInstantApp(packageName, userId);
23600        }
23601
23602        @Override
23603        public String getInstantAppPackageName(int uid) {
23604            return PackageManagerService.this.getInstantAppPackageName(uid);
23605        }
23606
23607        @Override
23608        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23609            synchronized (mPackages) {
23610                return PackageManagerService.this.filterAppAccessLPr(
23611                        (PackageSetting) pkg.mExtras, callingUid, userId);
23612            }
23613        }
23614
23615        @Override
23616        public PackageParser.Package getPackage(String packageName) {
23617            synchronized (mPackages) {
23618                packageName = resolveInternalPackageNameLPr(
23619                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23620                return mPackages.get(packageName);
23621            }
23622        }
23623
23624        @Override
23625        public PackageList getPackageList(PackageListObserver observer) {
23626            synchronized (mPackages) {
23627                final int N = mPackages.size();
23628                final ArrayList<String> list = new ArrayList<>(N);
23629                for (int i = 0; i < N; i++) {
23630                    list.add(mPackages.keyAt(i));
23631                }
23632                final PackageList packageList = new PackageList(list, observer);
23633                if (observer != null) {
23634                    mPackageListObservers.add(packageList);
23635                }
23636                return packageList;
23637            }
23638        }
23639
23640        @Override
23641        public void removePackageListObserver(PackageListObserver observer) {
23642            synchronized (mPackages) {
23643                mPackageListObservers.remove(observer);
23644            }
23645        }
23646
23647        @Override
23648        public PackageParser.Package getDisabledPackage(String packageName) {
23649            synchronized (mPackages) {
23650                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23651                return (ps != null) ? ps.pkg : null;
23652            }
23653        }
23654
23655        @Override
23656        public String getKnownPackageName(int knownPackage, int userId) {
23657            switch(knownPackage) {
23658                case PackageManagerInternal.PACKAGE_BROWSER:
23659                    return getDefaultBrowserPackageName(userId);
23660                case PackageManagerInternal.PACKAGE_INSTALLER:
23661                    return mRequiredInstallerPackage;
23662                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23663                    return mSetupWizardPackage;
23664                case PackageManagerInternal.PACKAGE_SYSTEM:
23665                    return "android";
23666                case PackageManagerInternal.PACKAGE_VERIFIER:
23667                    return mRequiredVerifierPackage;
23668                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23669                    return mSystemTextClassifierPackage;
23670            }
23671            return null;
23672        }
23673
23674        @Override
23675        public boolean isResolveActivityComponent(ComponentInfo component) {
23676            return mResolveActivity.packageName.equals(component.packageName)
23677                    && mResolveActivity.name.equals(component.name);
23678        }
23679
23680        @Override
23681        public void setLocationPackagesProvider(PackagesProvider provider) {
23682            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23683        }
23684
23685        @Override
23686        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23687            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23688        }
23689
23690        @Override
23691        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23692            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23693        }
23694
23695        @Override
23696        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23697            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23698        }
23699
23700        @Override
23701        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23702            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23703        }
23704
23705        @Override
23706        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23707            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23708        }
23709
23710        @Override
23711        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23712            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23713        }
23714
23715        @Override
23716        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23717            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23718        }
23719
23720        @Override
23721        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23722            synchronized (mPackages) {
23723                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23724            }
23725            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23726        }
23727
23728        @Override
23729        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23730            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23731                    packageName, userId);
23732        }
23733
23734        @Override
23735        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23736            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23737                    packageName, userId);
23738        }
23739
23740        @Override
23741        public void setKeepUninstalledPackages(final List<String> packageList) {
23742            Preconditions.checkNotNull(packageList);
23743            List<String> removedFromList = null;
23744            synchronized (mPackages) {
23745                if (mKeepUninstalledPackages != null) {
23746                    final int packagesCount = mKeepUninstalledPackages.size();
23747                    for (int i = 0; i < packagesCount; i++) {
23748                        String oldPackage = mKeepUninstalledPackages.get(i);
23749                        if (packageList != null && packageList.contains(oldPackage)) {
23750                            continue;
23751                        }
23752                        if (removedFromList == null) {
23753                            removedFromList = new ArrayList<>();
23754                        }
23755                        removedFromList.add(oldPackage);
23756                    }
23757                }
23758                mKeepUninstalledPackages = new ArrayList<>(packageList);
23759                if (removedFromList != null) {
23760                    final int removedCount = removedFromList.size();
23761                    for (int i = 0; i < removedCount; i++) {
23762                        deletePackageIfUnusedLPr(removedFromList.get(i));
23763                    }
23764                }
23765            }
23766        }
23767
23768        @Override
23769        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23770            synchronized (mPackages) {
23771                return mPermissionManager.isPermissionsReviewRequired(
23772                        mPackages.get(packageName), userId);
23773            }
23774        }
23775
23776        @Override
23777        public PackageInfo getPackageInfo(
23778                String packageName, int flags, int filterCallingUid, int userId) {
23779            return PackageManagerService.this
23780                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23781                            flags, filterCallingUid, userId);
23782        }
23783
23784        @Override
23785        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23786            synchronized (mPackages) {
23787                final PackageSetting ps = mSettings.mPackages.get(packageName);
23788                PersistableBundle launcherExtras = null;
23789                if (ps != null) {
23790                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23791                }
23792                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23793            }
23794        }
23795
23796        @Override
23797        public boolean isPackageSuspended(String packageName, int userId) {
23798            synchronized (mPackages) {
23799                final PackageSetting ps = mSettings.mPackages.get(packageName);
23800                return (ps != null) ? ps.getSuspended(userId) : false;
23801            }
23802        }
23803
23804        @Override
23805        public String getSuspendingPackage(String suspendedPackage, int userId) {
23806            synchronized (mPackages) {
23807                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23808                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23809            }
23810        }
23811
23812        @Override
23813        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23814            synchronized (mPackages) {
23815                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23816                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23817            }
23818        }
23819
23820        @Override
23821        public int getPackageUid(String packageName, int flags, int userId) {
23822            return PackageManagerService.this
23823                    .getPackageUid(packageName, flags, userId);
23824        }
23825
23826        @Override
23827        public ApplicationInfo getApplicationInfo(
23828                String packageName, int flags, int filterCallingUid, int userId) {
23829            return PackageManagerService.this
23830                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23831        }
23832
23833        @Override
23834        public ActivityInfo getActivityInfo(
23835                ComponentName component, int flags, int filterCallingUid, int userId) {
23836            return PackageManagerService.this
23837                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23838        }
23839
23840        @Override
23841        public List<ResolveInfo> queryIntentActivities(
23842                Intent intent, int flags, int filterCallingUid, int userId) {
23843            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23844            return PackageManagerService.this
23845                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23846                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23847        }
23848
23849        @Override
23850        public List<ResolveInfo> queryIntentServices(
23851                Intent intent, int flags, int callingUid, int userId) {
23852            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23853            return PackageManagerService.this
23854                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23855                            false);
23856        }
23857
23858        @Override
23859        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23860                int userId) {
23861            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23862        }
23863
23864        @Override
23865        public ComponentName getDefaultHomeActivity(int userId) {
23866            return PackageManagerService.this.getDefaultHomeActivity(userId);
23867        }
23868
23869        @Override
23870        public void setDeviceAndProfileOwnerPackages(
23871                int deviceOwnerUserId, String deviceOwnerPackage,
23872                SparseArray<String> profileOwnerPackages) {
23873            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23874                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23875        }
23876
23877        @Override
23878        public boolean isPackageDataProtected(int userId, String packageName) {
23879            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23880        }
23881
23882        @Override
23883        public boolean isPackageEphemeral(int userId, String packageName) {
23884            synchronized (mPackages) {
23885                final PackageSetting ps = mSettings.mPackages.get(packageName);
23886                return ps != null ? ps.getInstantApp(userId) : false;
23887            }
23888        }
23889
23890        @Override
23891        public boolean wasPackageEverLaunched(String packageName, int userId) {
23892            synchronized (mPackages) {
23893                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23894            }
23895        }
23896
23897        @Override
23898        public void grantRuntimePermission(String packageName, String permName, int userId,
23899                boolean overridePolicy) {
23900            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23901                    permName, packageName, overridePolicy, getCallingUid(), userId,
23902                    mPermissionCallback);
23903        }
23904
23905        @Override
23906        public void revokeRuntimePermission(String packageName, String permName, int userId,
23907                boolean overridePolicy) {
23908            mPermissionManager.revokeRuntimePermission(
23909                    permName, packageName, overridePolicy, getCallingUid(), userId,
23910                    mPermissionCallback);
23911        }
23912
23913        @Override
23914        public String getNameForUid(int uid) {
23915            return PackageManagerService.this.getNameForUid(uid);
23916        }
23917
23918        @Override
23919        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23920                Intent origIntent, String resolvedType, String callingPackage,
23921                Bundle verificationBundle, int userId) {
23922            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23923                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23924                    userId);
23925        }
23926
23927        @Override
23928        public void grantEphemeralAccess(int userId, Intent intent,
23929                int targetAppId, int ephemeralAppId) {
23930            synchronized (mPackages) {
23931                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23932                        targetAppId, ephemeralAppId);
23933            }
23934        }
23935
23936        @Override
23937        public boolean isInstantAppInstallerComponent(ComponentName component) {
23938            synchronized (mPackages) {
23939                return mInstantAppInstallerActivity != null
23940                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23941            }
23942        }
23943
23944        @Override
23945        public void pruneInstantApps() {
23946            mInstantAppRegistry.pruneInstantApps();
23947        }
23948
23949        @Override
23950        public String getSetupWizardPackageName() {
23951            return mSetupWizardPackage;
23952        }
23953
23954        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23955            if (policy != null) {
23956                mExternalSourcesPolicy = policy;
23957            }
23958        }
23959
23960        @Override
23961        public boolean isPackagePersistent(String packageName) {
23962            synchronized (mPackages) {
23963                PackageParser.Package pkg = mPackages.get(packageName);
23964                return pkg != null
23965                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23966                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23967                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23968                        : false;
23969            }
23970        }
23971
23972        @Override
23973        public boolean isLegacySystemApp(Package pkg) {
23974            synchronized (mPackages) {
23975                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23976                return mPromoteSystemApps
23977                        && ps.isSystem()
23978                        && mExistingSystemPackages.contains(ps.name);
23979            }
23980        }
23981
23982        @Override
23983        public List<PackageInfo> getOverlayPackages(int userId) {
23984            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23985            synchronized (mPackages) {
23986                for (PackageParser.Package p : mPackages.values()) {
23987                    if (p.mOverlayTarget != null) {
23988                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23989                        if (pkg != null) {
23990                            overlayPackages.add(pkg);
23991                        }
23992                    }
23993                }
23994            }
23995            return overlayPackages;
23996        }
23997
23998        @Override
23999        public List<String> getTargetPackageNames(int userId) {
24000            List<String> targetPackages = new ArrayList<>();
24001            synchronized (mPackages) {
24002                for (PackageParser.Package p : mPackages.values()) {
24003                    if (p.mOverlayTarget == null) {
24004                        targetPackages.add(p.packageName);
24005                    }
24006                }
24007            }
24008            return targetPackages;
24009        }
24010
24011        @Override
24012        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24013                @Nullable List<String> overlayPackageNames) {
24014            synchronized (mPackages) {
24015                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24016                    Slog.e(TAG, "failed to find package " + targetPackageName);
24017                    return false;
24018                }
24019                ArrayList<String> overlayPaths = null;
24020                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24021                    final int N = overlayPackageNames.size();
24022                    overlayPaths = new ArrayList<>(N);
24023                    for (int i = 0; i < N; i++) {
24024                        final String packageName = overlayPackageNames.get(i);
24025                        final PackageParser.Package pkg = mPackages.get(packageName);
24026                        if (pkg == null) {
24027                            Slog.e(TAG, "failed to find package " + packageName);
24028                            return false;
24029                        }
24030                        overlayPaths.add(pkg.baseCodePath);
24031                    }
24032                }
24033
24034                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24035                ps.setOverlayPaths(overlayPaths, userId);
24036                return true;
24037            }
24038        }
24039
24040        @Override
24041        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24042                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24043            return resolveIntentInternal(
24044                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24045        }
24046
24047        @Override
24048        public ResolveInfo resolveService(Intent intent, String resolvedType,
24049                int flags, int userId, int callingUid) {
24050            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24051        }
24052
24053        @Override
24054        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24055            return PackageManagerService.this.resolveContentProviderInternal(
24056                    name, flags, userId);
24057        }
24058
24059        @Override
24060        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24061            synchronized (mPackages) {
24062                mIsolatedOwners.put(isolatedUid, ownerUid);
24063            }
24064        }
24065
24066        @Override
24067        public void removeIsolatedUid(int isolatedUid) {
24068            synchronized (mPackages) {
24069                mIsolatedOwners.delete(isolatedUid);
24070            }
24071        }
24072
24073        @Override
24074        public int getUidTargetSdkVersion(int uid) {
24075            synchronized (mPackages) {
24076                return getUidTargetSdkVersionLockedLPr(uid);
24077            }
24078        }
24079
24080        @Override
24081        public int getPackageTargetSdkVersion(String packageName) {
24082            synchronized (mPackages) {
24083                return getPackageTargetSdkVersionLockedLPr(packageName);
24084            }
24085        }
24086
24087        @Override
24088        public boolean canAccessInstantApps(int callingUid, int userId) {
24089            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24090        }
24091
24092        @Override
24093        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24094            synchronized (mPackages) {
24095                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24096                return !PackageManagerService.this.filterAppAccessLPr(
24097                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24098            }
24099        }
24100
24101        @Override
24102        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24103            synchronized (mPackages) {
24104                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24105            }
24106        }
24107
24108        @Override
24109        public void notifyPackageUse(String packageName, int reason) {
24110            synchronized (mPackages) {
24111                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24112            }
24113        }
24114    }
24115
24116    @Override
24117    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24118        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24119        synchronized (mPackages) {
24120            final long identity = Binder.clearCallingIdentity();
24121            try {
24122                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24123                        packageNames, userId);
24124            } finally {
24125                Binder.restoreCallingIdentity(identity);
24126            }
24127        }
24128    }
24129
24130    @Override
24131    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24132        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24133        synchronized (mPackages) {
24134            final long identity = Binder.clearCallingIdentity();
24135            try {
24136                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24137                        packageNames, userId);
24138            } finally {
24139                Binder.restoreCallingIdentity(identity);
24140            }
24141        }
24142    }
24143
24144    @Override
24145    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24146            String[] packageNames, int userId) {
24147        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24148        synchronized (mPackages) {
24149            Binder.withCleanCallingIdentity( () -> {
24150                mDefaultPermissionPolicy.
24151                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24152                                packageNames, userId);
24153            });
24154        }
24155    }
24156
24157    @Override
24158    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24159            String[] packageNames, int userId) {
24160        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24161        synchronized (mPackages) {
24162            Binder.withCleanCallingIdentity( () -> {
24163                mDefaultPermissionPolicy.
24164                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24165                                packageNames, userId);
24166            });
24167        }
24168    }
24169
24170    @Override
24171    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24172        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24173        synchronized (mPackages) {
24174            final long identity = Binder.clearCallingIdentity();
24175            try {
24176                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24177                        packageName, userId);
24178            } finally {
24179                Binder.restoreCallingIdentity(identity);
24180            }
24181        }
24182    }
24183
24184    @Override
24185    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24186        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24187        synchronized (mPackages) {
24188            final long identity = Binder.clearCallingIdentity();
24189            try {
24190                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24191            } finally {
24192                Binder.restoreCallingIdentity(identity);
24193            }
24194        }
24195    }
24196
24197    private static void enforceSystemOrPhoneCaller(String tag) {
24198        int callingUid = Binder.getCallingUid();
24199        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24200            throw new SecurityException(
24201                    "Cannot call " + tag + " from UID " + callingUid);
24202        }
24203    }
24204
24205    boolean isHistoricalPackageUsageAvailable() {
24206        return mPackageUsage.isHistoricalPackageUsageAvailable();
24207    }
24208
24209    /**
24210     * Return a <b>copy</b> of the collection of packages known to the package manager.
24211     * @return A copy of the values of mPackages.
24212     */
24213    Collection<PackageParser.Package> getPackages() {
24214        synchronized (mPackages) {
24215            return new ArrayList<>(mPackages.values());
24216        }
24217    }
24218
24219    /**
24220     * Logs process start information (including base APK hash) to the security log.
24221     * @hide
24222     */
24223    @Override
24224    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24225            String apkFile, int pid) {
24226        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24227            return;
24228        }
24229        if (!SecurityLog.isLoggingEnabled()) {
24230            return;
24231        }
24232        Bundle data = new Bundle();
24233        data.putLong("startTimestamp", System.currentTimeMillis());
24234        data.putString("processName", processName);
24235        data.putInt("uid", uid);
24236        data.putString("seinfo", seinfo);
24237        data.putString("apkFile", apkFile);
24238        data.putInt("pid", pid);
24239        Message msg = mProcessLoggingHandler.obtainMessage(
24240                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24241        msg.setData(data);
24242        mProcessLoggingHandler.sendMessage(msg);
24243    }
24244
24245    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24246        return mCompilerStats.getPackageStats(pkgName);
24247    }
24248
24249    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24250        return getOrCreateCompilerPackageStats(pkg.packageName);
24251    }
24252
24253    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24254        return mCompilerStats.getOrCreatePackageStats(pkgName);
24255    }
24256
24257    public void deleteCompilerPackageStats(String pkgName) {
24258        mCompilerStats.deletePackageStats(pkgName);
24259    }
24260
24261    @Override
24262    public int getInstallReason(String packageName, int userId) {
24263        final int callingUid = Binder.getCallingUid();
24264        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24265                true /* requireFullPermission */, false /* checkShell */,
24266                "get install reason");
24267        synchronized (mPackages) {
24268            final PackageSetting ps = mSettings.mPackages.get(packageName);
24269            if (filterAppAccessLPr(ps, callingUid, userId)) {
24270                return PackageManager.INSTALL_REASON_UNKNOWN;
24271            }
24272            if (ps != null) {
24273                return ps.getInstallReason(userId);
24274            }
24275        }
24276        return PackageManager.INSTALL_REASON_UNKNOWN;
24277    }
24278
24279    @Override
24280    public boolean canRequestPackageInstalls(String packageName, int userId) {
24281        return canRequestPackageInstallsInternal(packageName, 0, userId,
24282                true /* throwIfPermNotDeclared*/);
24283    }
24284
24285    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24286            boolean throwIfPermNotDeclared) {
24287        int callingUid = Binder.getCallingUid();
24288        int uid = getPackageUid(packageName, 0, userId);
24289        if (callingUid != uid && callingUid != Process.ROOT_UID
24290                && callingUid != Process.SYSTEM_UID) {
24291            throw new SecurityException(
24292                    "Caller uid " + callingUid + " does not own package " + packageName);
24293        }
24294        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24295        if (info == null) {
24296            return false;
24297        }
24298        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24299            return false;
24300        }
24301        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24302        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24303        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24304            if (throwIfPermNotDeclared) {
24305                throw new SecurityException("Need to declare " + appOpPermission
24306                        + " to call this api");
24307            } else {
24308                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24309                return false;
24310            }
24311        }
24312        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24313            return false;
24314        }
24315        if (mExternalSourcesPolicy != null) {
24316            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24317            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24318                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24319            }
24320        }
24321        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24322    }
24323
24324    @Override
24325    public ComponentName getInstantAppResolverSettingsComponent() {
24326        return mInstantAppResolverSettingsComponent;
24327    }
24328
24329    @Override
24330    public ComponentName getInstantAppInstallerComponent() {
24331        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24332            return null;
24333        }
24334        return mInstantAppInstallerActivity == null
24335                ? null : mInstantAppInstallerActivity.getComponentName();
24336    }
24337
24338    @Override
24339    public String getInstantAppAndroidId(String packageName, int userId) {
24340        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24341                "getInstantAppAndroidId");
24342        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24343                true /* requireFullPermission */, false /* checkShell */,
24344                "getInstantAppAndroidId");
24345        // Make sure the target is an Instant App.
24346        if (!isInstantApp(packageName, userId)) {
24347            return null;
24348        }
24349        synchronized (mPackages) {
24350            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24351        }
24352    }
24353
24354    boolean canHaveOatDir(String packageName) {
24355        synchronized (mPackages) {
24356            PackageParser.Package p = mPackages.get(packageName);
24357            if (p == null) {
24358                return false;
24359            }
24360            return p.canHaveOatDir();
24361        }
24362    }
24363
24364    private String getOatDir(PackageParser.Package pkg) {
24365        if (!pkg.canHaveOatDir()) {
24366            return null;
24367        }
24368        File codePath = new File(pkg.codePath);
24369        if (codePath.isDirectory()) {
24370            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24371        }
24372        return null;
24373    }
24374
24375    void deleteOatArtifactsOfPackage(String packageName) {
24376        final String[] instructionSets;
24377        final List<String> codePaths;
24378        final String oatDir;
24379        final PackageParser.Package pkg;
24380        synchronized (mPackages) {
24381            pkg = mPackages.get(packageName);
24382        }
24383        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24384        codePaths = pkg.getAllCodePaths();
24385        oatDir = getOatDir(pkg);
24386
24387        for (String codePath : codePaths) {
24388            for (String isa : instructionSets) {
24389                try {
24390                    mInstaller.deleteOdex(codePath, isa, oatDir);
24391                } catch (InstallerException e) {
24392                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24393                }
24394            }
24395        }
24396    }
24397
24398    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24399        Set<String> unusedPackages = new HashSet<>();
24400        long currentTimeInMillis = System.currentTimeMillis();
24401        synchronized (mPackages) {
24402            for (PackageParser.Package pkg : mPackages.values()) {
24403                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24404                if (ps == null) {
24405                    continue;
24406                }
24407                PackageDexUsage.PackageUseInfo packageUseInfo =
24408                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24409                if (PackageManagerServiceUtils
24410                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24411                                downgradeTimeThresholdMillis, packageUseInfo,
24412                                pkg.getLatestPackageUseTimeInMills(),
24413                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24414                    unusedPackages.add(pkg.packageName);
24415                }
24416            }
24417        }
24418        return unusedPackages;
24419    }
24420
24421    @Override
24422    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24423            int userId) {
24424        final int callingUid = Binder.getCallingUid();
24425        final int callingAppId = UserHandle.getAppId(callingUid);
24426
24427        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24428                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24429
24430        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24431                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24432            throw new SecurityException("Caller must have the "
24433                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24434        }
24435
24436        synchronized(mPackages) {
24437            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24438            scheduleWritePackageRestrictionsLocked(userId);
24439        }
24440    }
24441
24442    @Nullable
24443    @Override
24444    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24445        final int callingUid = Binder.getCallingUid();
24446        final int callingAppId = UserHandle.getAppId(callingUid);
24447
24448        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24449                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24450
24451        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24452                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24453            throw new SecurityException("Caller must have the "
24454                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24455        }
24456
24457        synchronized(mPackages) {
24458            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24459        }
24460    }
24461
24462    @Override
24463    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24464        final int callingUid = Binder.getCallingUid();
24465        final int callingAppId = UserHandle.getAppId(callingUid);
24466
24467        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24468                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24469
24470        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24471                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24472            throw new SecurityException("Caller must have the "
24473                    + MANAGE_DEVICE_ADMINS + " permission.");
24474        }
24475
24476        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24477    }
24478}
24479
24480interface PackageSender {
24481    /**
24482     * @param userIds User IDs where the action occurred on a full application
24483     * @param instantUserIds User IDs where the action occurred on an instant application
24484     */
24485    void sendPackageBroadcast(final String action, final String pkg,
24486        final Bundle extras, final int flags, final String targetPkg,
24487        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24488    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24489        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24490    void notifyPackageAdded(String packageName);
24491    void notifyPackageRemoved(String packageName);
24492}
24493