PackageManagerService.java revision 19b41f34a5cb29c621848e352220017b46cf66f1
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.MANAGE_DEVICE_ADMINS;
21import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
22import static android.Manifest.permission.INSTALL_PACKAGES;
23import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
24import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
25import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
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.PackageManagerInternal;
171import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
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.ServiceInfo;
190import android.content.pm.SharedLibraryInfo;
191import android.content.pm.Signature;
192import android.content.pm.UserInfo;
193import android.content.pm.VerifierDeviceIdentity;
194import android.content.pm.VerifierInfo;
195import android.content.pm.VersionedPackage;
196import android.content.pm.dex.ArtManager;
197import android.content.pm.dex.DexMetadataHelper;
198import android.content.pm.dex.IArtManager;
199import android.content.res.Resources;
200import android.database.ContentObserver;
201import android.graphics.Bitmap;
202import android.hardware.display.DisplayManager;
203import android.net.Uri;
204import android.os.Binder;
205import android.os.Build;
206import android.os.Bundle;
207import android.os.Debug;
208import android.os.Environment;
209import android.os.Environment.UserEnvironment;
210import android.os.FileUtils;
211import android.os.Handler;
212import android.os.IBinder;
213import android.os.Looper;
214import android.os.Message;
215import android.os.Parcel;
216import android.os.ParcelFileDescriptor;
217import android.os.PatternMatcher;
218import android.os.PersistableBundle;
219import android.os.Process;
220import android.os.RemoteCallbackList;
221import android.os.RemoteException;
222import android.os.ResultReceiver;
223import android.os.SELinux;
224import android.os.ServiceManager;
225import android.os.ShellCallback;
226import android.os.SystemClock;
227import android.os.SystemProperties;
228import android.os.Trace;
229import android.os.UserHandle;
230import android.os.UserManager;
231import android.os.UserManagerInternal;
232import android.os.storage.IStorageManager;
233import android.os.storage.StorageEventListener;
234import android.os.storage.StorageManager;
235import android.os.storage.StorageManagerInternal;
236import android.os.storage.VolumeInfo;
237import android.os.storage.VolumeRecord;
238import android.provider.Settings.Global;
239import android.provider.Settings.Secure;
240import android.security.KeyStore;
241import android.security.SystemKeyStore;
242import android.service.pm.PackageServiceDumpProto;
243import android.system.ErrnoException;
244import android.system.Os;
245import android.text.TextUtils;
246import android.text.format.DateUtils;
247import android.util.ArrayMap;
248import android.util.ArraySet;
249import android.util.Base64;
250import android.util.ByteStringUtils;
251import android.util.DisplayMetrics;
252import android.util.EventLog;
253import android.util.ExceptionUtils;
254import android.util.Log;
255import android.util.LogPrinter;
256import android.util.LongSparseArray;
257import android.util.LongSparseLongArray;
258import android.util.MathUtils;
259import android.util.PackageUtils;
260import android.util.Pair;
261import android.util.PrintStreamPrinter;
262import android.util.Slog;
263import android.util.SparseArray;
264import android.util.SparseBooleanArray;
265import android.util.SparseIntArray;
266import android.util.TimingsTraceLog;
267import android.util.Xml;
268import android.util.jar.StrictJarFile;
269import android.util.proto.ProtoOutputStream;
270import android.view.Display;
271
272import com.android.internal.R;
273import com.android.internal.annotations.GuardedBy;
274import com.android.internal.app.IMediaContainerService;
275import com.android.internal.app.ResolverActivity;
276import com.android.internal.content.NativeLibraryHelper;
277import com.android.internal.content.PackageHelper;
278import com.android.internal.logging.MetricsLogger;
279import com.android.internal.os.IParcelFileDescriptorFactory;
280import com.android.internal.os.SomeArgs;
281import com.android.internal.os.Zygote;
282import com.android.internal.telephony.CarrierAppUtils;
283import com.android.internal.util.ArrayUtils;
284import com.android.internal.util.ConcurrentUtils;
285import com.android.internal.util.DumpUtils;
286import com.android.internal.util.FastXmlSerializer;
287import com.android.internal.util.IndentingPrintWriter;
288import com.android.internal.util.Preconditions;
289import com.android.internal.util.XmlUtils;
290import com.android.server.AttributeCache;
291import com.android.server.DeviceIdleController;
292import com.android.server.EventLogTags;
293import com.android.server.FgThread;
294import com.android.server.IntentResolver;
295import com.android.server.LocalServices;
296import com.android.server.LockGuard;
297import com.android.server.ServiceThread;
298import com.android.server.SystemConfig;
299import com.android.server.SystemServerInitThreadPool;
300import com.android.server.Watchdog;
301import com.android.server.net.NetworkPolicyManagerInternal;
302import com.android.server.pm.Installer.InstallerException;
303import com.android.server.pm.Settings.DatabaseVersion;
304import com.android.server.pm.Settings.VersionInfo;
305import com.android.server.pm.dex.ArtManagerService;
306import com.android.server.pm.dex.DexLogger;
307import com.android.server.pm.dex.DexManager;
308import com.android.server.pm.dex.DexoptOptions;
309import com.android.server.pm.dex.PackageDexUsage;
310import com.android.server.pm.permission.BasePermission;
311import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
312import com.android.server.pm.permission.PermissionManagerService;
313import com.android.server.pm.permission.PermissionManagerInternal;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
315import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
316import com.android.server.pm.permission.PermissionsState;
317import com.android.server.pm.permission.PermissionsState.PermissionState;
318import com.android.server.security.VerityUtils;
319import com.android.server.storage.DeviceStorageMonitorInternal;
320
321import dalvik.system.CloseGuard;
322import dalvik.system.VMRuntime;
323
324import libcore.io.IoUtils;
325
326import org.xmlpull.v1.XmlPullParser;
327import org.xmlpull.v1.XmlPullParserException;
328import org.xmlpull.v1.XmlSerializer;
329
330import java.io.BufferedOutputStream;
331import java.io.ByteArrayInputStream;
332import java.io.ByteArrayOutputStream;
333import java.io.File;
334import java.io.FileDescriptor;
335import java.io.FileInputStream;
336import java.io.FileOutputStream;
337import java.io.FilenameFilter;
338import java.io.IOException;
339import java.io.PrintWriter;
340import java.lang.annotation.Retention;
341import java.lang.annotation.RetentionPolicy;
342import java.nio.charset.StandardCharsets;
343import java.security.DigestException;
344import java.security.DigestInputStream;
345import java.security.MessageDigest;
346import java.security.NoSuchAlgorithmException;
347import java.security.PublicKey;
348import java.security.SecureRandom;
349import java.security.cert.CertificateException;
350import java.util.ArrayList;
351import java.util.Arrays;
352import java.util.Collection;
353import java.util.Collections;
354import java.util.Comparator;
355import java.util.HashMap;
356import java.util.HashSet;
357import java.util.Iterator;
358import java.util.LinkedHashSet;
359import java.util.List;
360import java.util.Map;
361import java.util.Objects;
362import java.util.Set;
363import java.util.concurrent.CountDownLatch;
364import java.util.concurrent.Future;
365import java.util.concurrent.TimeUnit;
366import java.util.concurrent.atomic.AtomicBoolean;
367import java.util.concurrent.atomic.AtomicInteger;
368
369/**
370 * Keep track of all those APKs everywhere.
371 * <p>
372 * Internally there are two important locks:
373 * <ul>
374 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
375 * and other related state. It is a fine-grained lock that should only be held
376 * momentarily, as it's one of the most contended locks in the system.
377 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
378 * operations typically involve heavy lifting of application data on disk. Since
379 * {@code installd} is single-threaded, and it's operations can often be slow,
380 * this lock should never be acquired while already holding {@link #mPackages}.
381 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
382 * holding {@link #mInstallLock}.
383 * </ul>
384 * Many internal methods rely on the caller to hold the appropriate locks, and
385 * this contract is expressed through method name suffixes:
386 * <ul>
387 * <li>fooLI(): the caller must hold {@link #mInstallLock}
388 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
389 * being modified must be frozen
390 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
391 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
392 * </ul>
393 * <p>
394 * Because this class is very central to the platform's security; please run all
395 * CTS and unit tests whenever making modifications:
396 *
397 * <pre>
398 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
399 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
400 * </pre>
401 */
402public class PackageManagerService extends IPackageManager.Stub
403        implements PackageSender {
404    static final String TAG = "PackageManager";
405    public static final boolean DEBUG_SETTINGS = false;
406    static final boolean DEBUG_PREFERRED = false;
407    static final boolean DEBUG_UPGRADE = false;
408    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
409    private static final boolean DEBUG_BACKUP = false;
410    public static final boolean DEBUG_INSTALL = false;
411    public static final boolean DEBUG_REMOVE = true;
412    private static final boolean DEBUG_BROADCASTS = false;
413    private static final boolean DEBUG_SHOW_INFO = false;
414    private static final boolean DEBUG_PACKAGE_INFO = false;
415    private static final boolean DEBUG_INTENT_MATCHING = false;
416    public static final boolean DEBUG_PACKAGE_SCANNING = false;
417    private static final boolean DEBUG_VERIFY = false;
418    private static final boolean DEBUG_FILTERS = false;
419    public static final boolean DEBUG_PERMISSIONS = false;
420    private static final boolean DEBUG_SHARED_LIBRARIES = false;
421    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
422
423    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
424    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
425    // user, but by default initialize to this.
426    public static final boolean DEBUG_DEXOPT = false;
427
428    private static final boolean DEBUG_ABI_SELECTION = false;
429    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
430    private static final boolean DEBUG_TRIAGED_MISSING = false;
431    private static final boolean DEBUG_APP_DATA = false;
432
433    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
434    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
435
436    private static final boolean HIDE_EPHEMERAL_APIS = false;
437
438    private static final boolean ENABLE_FREE_CACHE_V2 =
439            SystemProperties.getBoolean("fw.free_cache_v2", true);
440
441    private static final int RADIO_UID = Process.PHONE_UID;
442    private static final int LOG_UID = Process.LOG_UID;
443    private static final int NFC_UID = Process.NFC_UID;
444    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
445    private static final int SHELL_UID = Process.SHELL_UID;
446    private static final int SE_UID = Process.SE_UID;
447
448    // Suffix used during package installation when copying/moving
449    // package apks to install directory.
450    private static final String INSTALL_PACKAGE_SUFFIX = "-";
451
452    static final int SCAN_NO_DEX = 1<<0;
453    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
454    static final int SCAN_NEW_INSTALL = 1<<2;
455    static final int SCAN_UPDATE_TIME = 1<<3;
456    static final int SCAN_BOOTING = 1<<4;
457    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
458    static final int SCAN_REQUIRE_KNOWN = 1<<7;
459    static final int SCAN_MOVE = 1<<8;
460    static final int SCAN_INITIAL = 1<<9;
461    static final int SCAN_CHECK_ONLY = 1<<10;
462    static final int SCAN_DONT_KILL_APP = 1<<11;
463    static final int SCAN_IGNORE_FROZEN = 1<<12;
464    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
465    static final int SCAN_AS_INSTANT_APP = 1<<14;
466    static final int SCAN_AS_FULL_APP = 1<<15;
467    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
468    static final int SCAN_AS_SYSTEM = 1<<17;
469    static final int SCAN_AS_PRIVILEGED = 1<<18;
470    static final int SCAN_AS_OEM = 1<<19;
471    static final int SCAN_AS_VENDOR = 1<<20;
472    static final int SCAN_AS_PRODUCT = 1<<21;
473
474    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
475            SCAN_NO_DEX,
476            SCAN_UPDATE_SIGNATURE,
477            SCAN_NEW_INSTALL,
478            SCAN_UPDATE_TIME,
479            SCAN_BOOTING,
480            SCAN_DELETE_DATA_ON_FAILURES,
481            SCAN_REQUIRE_KNOWN,
482            SCAN_MOVE,
483            SCAN_INITIAL,
484            SCAN_CHECK_ONLY,
485            SCAN_DONT_KILL_APP,
486            SCAN_IGNORE_FROZEN,
487            SCAN_FIRST_BOOT_OR_UPGRADE,
488            SCAN_AS_INSTANT_APP,
489            SCAN_AS_FULL_APP,
490            SCAN_AS_VIRTUAL_PRELOAD,
491    })
492    @Retention(RetentionPolicy.SOURCE)
493    public @interface ScanFlags {}
494
495    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
496    /** Extension of the compressed packages */
497    public final static String COMPRESSED_EXTENSION = ".gz";
498    /** Suffix of stub packages on the system partition */
499    public final static String STUB_SUFFIX = "-Stub";
500
501    private static final int[] EMPTY_INT_ARRAY = new int[0];
502
503    private static final int TYPE_UNKNOWN = 0;
504    private static final int TYPE_ACTIVITY = 1;
505    private static final int TYPE_RECEIVER = 2;
506    private static final int TYPE_SERVICE = 3;
507    private static final int TYPE_PROVIDER = 4;
508    @IntDef(prefix = { "TYPE_" }, value = {
509            TYPE_UNKNOWN,
510            TYPE_ACTIVITY,
511            TYPE_RECEIVER,
512            TYPE_SERVICE,
513            TYPE_PROVIDER,
514    })
515    @Retention(RetentionPolicy.SOURCE)
516    public @interface ComponentType {}
517
518    /**
519     * Timeout (in milliseconds) after which the watchdog should declare that
520     * our handler thread is wedged.  The usual default for such things is one
521     * minute but we sometimes do very lengthy I/O operations on this thread,
522     * such as installing multi-gigabyte applications, so ours needs to be longer.
523     */
524    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
525
526    /**
527     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
528     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
529     * settings entry if available, otherwise we use the hardcoded default.  If it's been
530     * more than this long since the last fstrim, we force one during the boot sequence.
531     *
532     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
533     * one gets run at the next available charging+idle time.  This final mandatory
534     * no-fstrim check kicks in only of the other scheduling criteria is never met.
535     */
536    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
537
538    /**
539     * Whether verification is enabled by default.
540     */
541    private static final boolean DEFAULT_VERIFY_ENABLE = true;
542
543    /**
544     * The default maximum time to wait for the verification agent to return in
545     * milliseconds.
546     */
547    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
548
549    /**
550     * The default response for package verification timeout.
551     *
552     * This can be either PackageManager.VERIFICATION_ALLOW or
553     * PackageManager.VERIFICATION_REJECT.
554     */
555    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
556
557    public static final String PLATFORM_PACKAGE_NAME = "android";
558
559    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
560
561    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
562            DEFAULT_CONTAINER_PACKAGE,
563            "com.android.defcontainer.DefaultContainerService");
564
565    private static final String KILL_APP_REASON_GIDS_CHANGED =
566            "permission grant or revoke changed gids";
567
568    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
569            "permissions revoked";
570
571    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
572
573    private static final String PACKAGE_SCHEME = "package";
574
575    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
576
577    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
578
579    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
580
581    /** Canonical intent used to identify what counts as a "web browser" app */
582    private static final Intent sBrowserIntent;
583    static {
584        sBrowserIntent = new Intent();
585        sBrowserIntent.setAction(Intent.ACTION_VIEW);
586        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
587        sBrowserIntent.setData(Uri.parse("http:"));
588        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
589    }
590
591    /**
592     * The set of all protected actions [i.e. those actions for which a high priority
593     * intent filter is disallowed].
594     */
595    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
596    static {
597        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
598        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
599        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
600        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
601    }
602
603    // Compilation reasons.
604    public static final int REASON_UNKNOWN = -1;
605    public static final int REASON_FIRST_BOOT = 0;
606    public static final int REASON_BOOT = 1;
607    public static final int REASON_INSTALL = 2;
608    public static final int REASON_BACKGROUND_DEXOPT = 3;
609    public static final int REASON_AB_OTA = 4;
610    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
611    public static final int REASON_SHARED = 6;
612
613    public static final int REASON_LAST = REASON_SHARED;
614
615    /**
616     * Version number for the package parser cache. Increment this whenever the format or
617     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
618     */
619    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
620
621    /**
622     * Whether the package parser cache is enabled.
623     */
624    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
625
626    /**
627     * Permissions required in order to receive instant application lifecycle broadcasts.
628     */
629    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
630            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
631
632    final ServiceThread mHandlerThread;
633
634    final PackageHandler mHandler;
635
636    private final ProcessLoggingHandler mProcessLoggingHandler;
637
638    /**
639     * Messages for {@link #mHandler} that need to wait for system ready before
640     * being dispatched.
641     */
642    private ArrayList<Message> mPostSystemReadyMessages;
643
644    final int mSdkVersion = Build.VERSION.SDK_INT;
645
646    final Context mContext;
647    final boolean mFactoryTest;
648    final boolean mOnlyCore;
649    final DisplayMetrics mMetrics;
650    final int mDefParseFlags;
651    final String[] mSeparateProcesses;
652    final boolean mIsUpgrade;
653    final boolean mIsPreNUpgrade;
654    final boolean mIsPreNMR1Upgrade;
655
656    // Have we told the Activity Manager to whitelist the default container service by uid yet?
657    @GuardedBy("mPackages")
658    boolean mDefaultContainerWhitelisted = false;
659
660    @GuardedBy("mPackages")
661    private boolean mDexOptDialogShown;
662
663    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
664    // LOCK HELD.  Can be called with mInstallLock held.
665    @GuardedBy("mInstallLock")
666    final Installer mInstaller;
667
668    /** Directory where installed applications are stored */
669    private static final File sAppInstallDir =
670            new File(Environment.getDataDirectory(), "app");
671    /** Directory where installed application's 32-bit native libraries are copied. */
672    private static final File sAppLib32InstallDir =
673            new File(Environment.getDataDirectory(), "app-lib");
674    /** Directory where code and non-resource assets of forward-locked applications are stored */
675    private static final File sDrmAppPrivateInstallDir =
676            new File(Environment.getDataDirectory(), "app-private");
677
678    // ----------------------------------------------------------------
679
680    // Lock for state used when installing and doing other long running
681    // operations.  Methods that must be called with this lock held have
682    // the suffix "LI".
683    final Object mInstallLock = new Object();
684
685    // ----------------------------------------------------------------
686
687    // Keys are String (package name), values are Package.  This also serves
688    // as the lock for the global state.  Methods that must be called with
689    // this lock held have the prefix "LP".
690    @GuardedBy("mPackages")
691    final ArrayMap<String, PackageParser.Package> mPackages =
692            new ArrayMap<String, PackageParser.Package>();
693
694    final ArrayMap<String, Set<String>> mKnownCodebase =
695            new ArrayMap<String, Set<String>>();
696
697    // Keys are isolated uids and values are the uid of the application
698    // that created the isolated proccess.
699    @GuardedBy("mPackages")
700    final SparseIntArray mIsolatedOwners = new SparseIntArray();
701
702    /**
703     * Tracks new system packages [received in an OTA] that we expect to
704     * find updated user-installed versions. Keys are package name, values
705     * are package location.
706     */
707    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
708    /**
709     * Tracks high priority intent filters for protected actions. During boot, certain
710     * filter actions are protected and should never be allowed to have a high priority
711     * intent filter for them. However, there is one, and only one exception -- the
712     * setup wizard. It must be able to define a high priority intent filter for these
713     * actions to ensure there are no escapes from the wizard. We need to delay processing
714     * of these during boot as we need to look at all of the system packages in order
715     * to know which component is the setup wizard.
716     */
717    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
718    /**
719     * Whether or not processing protected filters should be deferred.
720     */
721    private boolean mDeferProtectedFilters = true;
722
723    /**
724     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
725     */
726    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
727    /**
728     * Whether or not system app permissions should be promoted from install to runtime.
729     */
730    boolean mPromoteSystemApps;
731
732    @GuardedBy("mPackages")
733    final Settings mSettings;
734
735    /**
736     * Set of package names that are currently "frozen", which means active
737     * surgery is being done on the code/data for that package. The platform
738     * will refuse to launch frozen packages to avoid race conditions.
739     *
740     * @see PackageFreezer
741     */
742    @GuardedBy("mPackages")
743    final ArraySet<String> mFrozenPackages = new ArraySet<>();
744
745    final ProtectedPackages mProtectedPackages;
746
747    @GuardedBy("mLoadedVolumes")
748    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
749
750    boolean mFirstBoot;
751
752    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
753
754    @GuardedBy("mAvailableFeatures")
755    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
756
757    private final InstantAppRegistry mInstantAppRegistry;
758
759    @GuardedBy("mPackages")
760    int mChangedPackagesSequenceNumber;
761    /**
762     * List of changed [installed, removed or updated] packages.
763     * mapping from user id -> sequence number -> package name
764     */
765    @GuardedBy("mPackages")
766    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
767    /**
768     * The sequence number of the last change to a package.
769     * mapping from user id -> package name -> sequence number
770     */
771    @GuardedBy("mPackages")
772    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
773
774    @GuardedBy("mPackages")
775    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
776
777    class PackageParserCallback implements PackageParser.Callback {
778        @Override public final boolean hasFeature(String feature) {
779            return PackageManagerService.this.hasSystemFeature(feature, 0);
780        }
781
782        final List<PackageParser.Package> getStaticOverlayPackages(
783                Collection<PackageParser.Package> allPackages, String targetPackageName) {
784            if ("android".equals(targetPackageName)) {
785                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
786                // native AssetManager.
787                return null;
788            }
789
790            List<PackageParser.Package> overlayPackages = null;
791            for (PackageParser.Package p : allPackages) {
792                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
793                    if (overlayPackages == null) {
794                        overlayPackages = new ArrayList<PackageParser.Package>();
795                    }
796                    overlayPackages.add(p);
797                }
798            }
799            if (overlayPackages != null) {
800                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
801                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
802                        return p1.mOverlayPriority - p2.mOverlayPriority;
803                    }
804                };
805                Collections.sort(overlayPackages, cmp);
806            }
807            return overlayPackages;
808        }
809
810        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
811                String targetPath) {
812            if (overlayPackages == null || overlayPackages.isEmpty()) {
813                return null;
814            }
815            List<String> overlayPathList = null;
816            for (PackageParser.Package overlayPackage : overlayPackages) {
817                if (targetPath == null) {
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                    continue;
823                }
824
825                try {
826                    // Creates idmaps for system to parse correctly the Android manifest of the
827                    // target package.
828                    //
829                    // OverlayManagerService will update each of them with a correct gid from its
830                    // target package app id.
831                    synchronized (mInstallLock) {
832                        mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                                UserHandle.getSharedAppGid(
834                                        UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    }
836                    if (overlayPathList == null) {
837                        overlayPathList = new ArrayList<String>();
838                    }
839                    overlayPathList.add(overlayPackage.baseCodePath);
840                } catch (InstallerException e) {
841                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
842                            overlayPackage.baseCodePath);
843                }
844            }
845            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
846        }
847
848        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
849            List<PackageParser.Package> overlayPackages;
850            synchronized (mPackages) {
851                overlayPackages = getStaticOverlayPackages(
852                        mPackages.values(), targetPackageName);
853            }
854            // It is safe to keep overlayPackages without holding mPackages because static overlay
855            // packages can't be uninstalled or disabled.
856            return getStaticOverlayPaths(overlayPackages, targetPath);
857        }
858
859        @Override public final String[] getOverlayApks(String targetPackageName) {
860            return getStaticOverlayPaths(targetPackageName, null);
861        }
862
863        @Override public final String[] getOverlayPaths(String targetPackageName,
864                String targetPath) {
865            return getStaticOverlayPaths(targetPackageName, targetPath);
866        }
867    }
868
869    class ParallelPackageParserCallback extends PackageParserCallback {
870        List<PackageParser.Package> mOverlayPackages = null;
871
872        void findStaticOverlayPackages() {
873            synchronized (mPackages) {
874                for (PackageParser.Package p : mPackages.values()) {
875                    if (p.mOverlayIsStatic) {
876                        if (mOverlayPackages == null) {
877                            mOverlayPackages = new ArrayList<PackageParser.Package>();
878                        }
879                        mOverlayPackages.add(p);
880                    }
881                }
882            }
883        }
884
885        @Override
886        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
887            // We can trust mOverlayPackages without holding mPackages because package uninstall
888            // can't happen while running parallel parsing.
889            // Moreover holding mPackages on each parsing thread causes dead-lock.
890            return mOverlayPackages == null ? null :
891                    getStaticOverlayPaths(
892                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
893                            targetPath);
894        }
895    }
896
897    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
898    final ParallelPackageParserCallback mParallelPackageParserCallback =
899            new ParallelPackageParserCallback();
900
901    public static final class SharedLibraryEntry {
902        public final @Nullable String path;
903        public final @Nullable String apk;
904        public final @NonNull SharedLibraryInfo info;
905
906        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
907                String declaringPackageName, long declaringPackageVersionCode) {
908            path = _path;
909            apk = _apk;
910            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
911                    declaringPackageName, declaringPackageVersionCode), null);
912        }
913    }
914
915    // Currently known shared libraries.
916    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
917    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
918            new ArrayMap<>();
919
920    // All available activities, for your resolving pleasure.
921    final ActivityIntentResolver mActivities =
922            new ActivityIntentResolver();
923
924    // All available receivers, for your resolving pleasure.
925    final ActivityIntentResolver mReceivers =
926            new ActivityIntentResolver();
927
928    // All available services, for your resolving pleasure.
929    final ServiceIntentResolver mServices = new ServiceIntentResolver();
930
931    // All available providers, for your resolving pleasure.
932    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
933
934    // Mapping from provider base names (first directory in content URI codePath)
935    // to the provider information.
936    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
937            new ArrayMap<String, PackageParser.Provider>();
938
939    // Mapping from instrumentation class names to info about them.
940    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
941            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
942
943    // Packages whose data we have transfered into another package, thus
944    // should no longer exist.
945    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
946
947    // Broadcast actions that are only available to the system.
948    @GuardedBy("mProtectedBroadcasts")
949    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
950
951    /** List of packages waiting for verification. */
952    final SparseArray<PackageVerificationState> mPendingVerification
953            = new SparseArray<PackageVerificationState>();
954
955    final PackageInstallerService mInstallerService;
956
957    final ArtManagerService mArtManagerService;
958
959    private final PackageDexOptimizer mPackageDexOptimizer;
960    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
961    // is used by other apps).
962    private final DexManager mDexManager;
963
964    private AtomicInteger mNextMoveId = new AtomicInteger();
965    private final MoveCallbacks mMoveCallbacks;
966
967    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
968
969    // Cache of users who need badging.
970    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
971
972    /** Token for keys in mPendingVerification. */
973    private int mPendingVerificationToken = 0;
974
975    volatile boolean mSystemReady;
976    volatile boolean mSafeMode;
977    volatile boolean mHasSystemUidErrors;
978    private volatile boolean mWebInstantAppsDisabled;
979
980    ApplicationInfo mAndroidApplication;
981    final ActivityInfo mResolveActivity = new ActivityInfo();
982    final ResolveInfo mResolveInfo = new ResolveInfo();
983    ComponentName mResolveComponentName;
984    PackageParser.Package mPlatformPackage;
985    ComponentName mCustomResolverComponentName;
986
987    boolean mResolverReplaced = false;
988
989    private final @Nullable ComponentName mIntentFilterVerifierComponent;
990    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
991
992    private int mIntentFilterVerificationToken = 0;
993
994    /** The service connection to the ephemeral resolver */
995    final InstantAppResolverConnection mInstantAppResolverConnection;
996    /** Component used to show resolver settings for Instant Apps */
997    final ComponentName mInstantAppResolverSettingsComponent;
998
999    /** Activity used to install instant applications */
1000    ActivityInfo mInstantAppInstallerActivity;
1001    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1002
1003    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1004            = new SparseArray<IntentFilterVerificationState>();
1005
1006    // TODO remove this and go through mPermissonManager directly
1007    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1008    private final PermissionManagerInternal mPermissionManager;
1009
1010    // List of packages names to keep cached, even if they are uninstalled for all users
1011    private List<String> mKeepUninstalledPackages;
1012
1013    private UserManagerInternal mUserManagerInternal;
1014    private ActivityManagerInternal mActivityManagerInternal;
1015
1016    private DeviceIdleController.LocalService mDeviceIdleController;
1017
1018    private File mCacheDir;
1019
1020    private Future<?> mPrepareAppDataFuture;
1021
1022    private static class IFVerificationParams {
1023        PackageParser.Package pkg;
1024        boolean replacing;
1025        int userId;
1026        int verifierUid;
1027
1028        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1029                int _userId, int _verifierUid) {
1030            pkg = _pkg;
1031            replacing = _replacing;
1032            userId = _userId;
1033            replacing = _replacing;
1034            verifierUid = _verifierUid;
1035        }
1036    }
1037
1038    private interface IntentFilterVerifier<T extends IntentFilter> {
1039        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1040                                               T filter, String packageName);
1041        void startVerifications(int userId);
1042        void receiveVerificationResponse(int verificationId);
1043    }
1044
1045    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1046        private Context mContext;
1047        private ComponentName mIntentFilterVerifierComponent;
1048        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1049
1050        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1051            mContext = context;
1052            mIntentFilterVerifierComponent = verifierComponent;
1053        }
1054
1055        private String getDefaultScheme() {
1056            return IntentFilter.SCHEME_HTTPS;
1057        }
1058
1059        @Override
1060        public void startVerifications(int userId) {
1061            // Launch verifications requests
1062            int count = mCurrentIntentFilterVerifications.size();
1063            for (int n=0; n<count; n++) {
1064                int verificationId = mCurrentIntentFilterVerifications.get(n);
1065                final IntentFilterVerificationState ivs =
1066                        mIntentFilterVerificationStates.get(verificationId);
1067
1068                String packageName = ivs.getPackageName();
1069
1070                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1071                final int filterCount = filters.size();
1072                ArraySet<String> domainsSet = new ArraySet<>();
1073                for (int m=0; m<filterCount; m++) {
1074                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1075                    domainsSet.addAll(filter.getHostsList());
1076                }
1077                synchronized (mPackages) {
1078                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1079                            packageName, domainsSet) != null) {
1080                        scheduleWriteSettingsLocked();
1081                    }
1082                }
1083                sendVerificationRequest(verificationId, ivs);
1084            }
1085            mCurrentIntentFilterVerifications.clear();
1086        }
1087
1088        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1089            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1092                    verificationId);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1095                    getDefaultScheme());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1098                    ivs.getHostsString());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1101                    ivs.getPackageName());
1102            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1103            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1104
1105            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1106            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1107                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1108                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1109
1110            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1111            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1112                    "Sending IntentFilter verification broadcast");
1113        }
1114
1115        public void receiveVerificationResponse(int verificationId) {
1116            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1117
1118            final boolean verified = ivs.isVerified();
1119
1120            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1121            final int count = filters.size();
1122            if (DEBUG_DOMAIN_VERIFICATION) {
1123                Slog.i(TAG, "Received verification response " + verificationId
1124                        + " for " + count + " filters, verified=" + verified);
1125            }
1126            for (int n=0; n<count; n++) {
1127                PackageParser.ActivityIntentInfo filter = filters.get(n);
1128                filter.setVerified(verified);
1129
1130                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1131                        + " verified with result:" + verified + " and hosts:"
1132                        + ivs.getHostsString());
1133            }
1134
1135            mIntentFilterVerificationStates.remove(verificationId);
1136
1137            final String packageName = ivs.getPackageName();
1138            IntentFilterVerificationInfo ivi = null;
1139
1140            synchronized (mPackages) {
1141                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1142            }
1143            if (ivi == null) {
1144                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1145                        + verificationId + " packageName:" + packageName);
1146                return;
1147            }
1148            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1149                    "Updating IntentFilterVerificationInfo for package " + packageName
1150                            +" verificationId:" + verificationId);
1151
1152            synchronized (mPackages) {
1153                if (verified) {
1154                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1155                } else {
1156                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1157                }
1158                scheduleWriteSettingsLocked();
1159
1160                final int userId = ivs.getUserId();
1161                if (userId != UserHandle.USER_ALL) {
1162                    final int userStatus =
1163                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1164
1165                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1166                    boolean needUpdate = false;
1167
1168                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1169                    // already been set by the User thru the Disambiguation dialog
1170                    switch (userStatus) {
1171                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1172                            if (verified) {
1173                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1174                            } else {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1176                            }
1177                            needUpdate = true;
1178                            break;
1179
1180                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1181                            if (verified) {
1182                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1183                                needUpdate = true;
1184                            }
1185                            break;
1186
1187                        default:
1188                            // Nothing to do
1189                    }
1190
1191                    if (needUpdate) {
1192                        mSettings.updateIntentFilterVerificationStatusLPw(
1193                                packageName, updatedStatus, userId);
1194                        scheduleWritePackageRestrictionsLocked(userId);
1195                    }
1196                }
1197            }
1198        }
1199
1200        @Override
1201        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1202                    ActivityIntentInfo filter, String packageName) {
1203            if (!hasValidDomains(filter)) {
1204                return false;
1205            }
1206            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1207            if (ivs == null) {
1208                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1209                        packageName);
1210            }
1211            if (DEBUG_DOMAIN_VERIFICATION) {
1212                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1213            }
1214            ivs.addFilter(filter);
1215            return true;
1216        }
1217
1218        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1219                int userId, int verificationId, String packageName) {
1220            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1221                    verifierUid, userId, packageName);
1222            ivs.setPendingState();
1223            synchronized (mPackages) {
1224                mIntentFilterVerificationStates.append(verificationId, ivs);
1225                mCurrentIntentFilterVerifications.add(verificationId);
1226            }
1227            return ivs;
1228        }
1229    }
1230
1231    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1232        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1233                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1234                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1235    }
1236
1237    // Set of pending broadcasts for aggregating enable/disable of components.
1238    static class PendingPackageBroadcasts {
1239        // for each user id, a map of <package name -> components within that package>
1240        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1241
1242        public PendingPackageBroadcasts() {
1243            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1244        }
1245
1246        public ArrayList<String> get(int userId, String packageName) {
1247            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1248            return packages.get(packageName);
1249        }
1250
1251        public void put(int userId, String packageName, ArrayList<String> components) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            packages.put(packageName, components);
1254        }
1255
1256        public void remove(int userId, String packageName) {
1257            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1258            if (packages != null) {
1259                packages.remove(packageName);
1260            }
1261        }
1262
1263        public void remove(int userId) {
1264            mUidMap.remove(userId);
1265        }
1266
1267        public int userIdCount() {
1268            return mUidMap.size();
1269        }
1270
1271        public int userIdAt(int n) {
1272            return mUidMap.keyAt(n);
1273        }
1274
1275        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1276            return mUidMap.get(userId);
1277        }
1278
1279        public int size() {
1280            // total number of pending broadcast entries across all userIds
1281            int num = 0;
1282            for (int i = 0; i< mUidMap.size(); i++) {
1283                num += mUidMap.valueAt(i).size();
1284            }
1285            return num;
1286        }
1287
1288        public void clear() {
1289            mUidMap.clear();
1290        }
1291
1292        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1293            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1294            if (map == null) {
1295                map = new ArrayMap<String, ArrayList<String>>();
1296                mUidMap.put(userId, map);
1297            }
1298            return map;
1299        }
1300    }
1301    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1302
1303    // Service Connection to remote media container service to copy
1304    // package uri's from external media onto secure containers
1305    // or internal storage.
1306    private IMediaContainerService mContainerService = null;
1307
1308    static final int SEND_PENDING_BROADCAST = 1;
1309    static final int MCS_BOUND = 3;
1310    static final int END_COPY = 4;
1311    static final int INIT_COPY = 5;
1312    static final int MCS_UNBIND = 6;
1313    static final int START_CLEANING_PACKAGE = 7;
1314    static final int FIND_INSTALL_LOC = 8;
1315    static final int POST_INSTALL = 9;
1316    static final int MCS_RECONNECT = 10;
1317    static final int MCS_GIVE_UP = 11;
1318    static final int WRITE_SETTINGS = 13;
1319    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1320    static final int PACKAGE_VERIFIED = 15;
1321    static final int CHECK_PENDING_VERIFICATION = 16;
1322    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1323    static final int INTENT_FILTER_VERIFIED = 18;
1324    static final int WRITE_PACKAGE_LIST = 19;
1325    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1326
1327    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1328
1329    // Delay time in millisecs
1330    static final int BROADCAST_DELAY = 10 * 1000;
1331
1332    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1333            2 * 60 * 60 * 1000L; /* two hours */
1334
1335    static UserManagerService sUserManager;
1336
1337    // Stores a list of users whose package restrictions file needs to be updated
1338    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1339
1340    final private DefaultContainerConnection mDefContainerConn =
1341            new DefaultContainerConnection();
1342    class DefaultContainerConnection implements ServiceConnection {
1343        public void onServiceConnected(ComponentName name, IBinder service) {
1344            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1345            final IMediaContainerService imcs = IMediaContainerService.Stub
1346                    .asInterface(Binder.allowBlocking(service));
1347            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1348        }
1349
1350        public void onServiceDisconnected(ComponentName name) {
1351            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1352        }
1353    }
1354
1355    // Recordkeeping of restore-after-install operations that are currently in flight
1356    // between the Package Manager and the Backup Manager
1357    static class PostInstallData {
1358        public InstallArgs args;
1359        public PackageInstalledInfo res;
1360
1361        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1362            args = _a;
1363            res = _r;
1364        }
1365    }
1366
1367    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1368    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1369
1370    // XML tags for backup/restore of various bits of state
1371    private static final String TAG_PREFERRED_BACKUP = "pa";
1372    private static final String TAG_DEFAULT_APPS = "da";
1373    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1374
1375    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1376    private static final String TAG_ALL_GRANTS = "rt-grants";
1377    private static final String TAG_GRANT = "grant";
1378    private static final String ATTR_PACKAGE_NAME = "pkg";
1379
1380    private static final String TAG_PERMISSION = "perm";
1381    private static final String ATTR_PERMISSION_NAME = "name";
1382    private static final String ATTR_IS_GRANTED = "g";
1383    private static final String ATTR_USER_SET = "set";
1384    private static final String ATTR_USER_FIXED = "fixed";
1385    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1386
1387    // System/policy permission grants are not backed up
1388    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_POLICY_FIXED
1390            | FLAG_PERMISSION_SYSTEM_FIXED
1391            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1392
1393    // And we back up these user-adjusted states
1394    private static final int USER_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_USER_SET
1396            | FLAG_PERMISSION_USER_FIXED
1397            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1398
1399    final @Nullable String mRequiredVerifierPackage;
1400    final @NonNull String mRequiredInstallerPackage;
1401    final @NonNull String mRequiredUninstallerPackage;
1402    final @Nullable String mSetupWizardPackage;
1403    final @Nullable String mStorageManagerPackage;
1404    final @Nullable String mSystemTextClassifierPackage;
1405    final @NonNull String mServicesSystemSharedLibraryPackageName;
1406    final @NonNull String mSharedSystemSharedLibraryPackageName;
1407
1408    private final PackageUsage mPackageUsage = new PackageUsage();
1409    private final CompilerStats mCompilerStats = new CompilerStats();
1410
1411    class PackageHandler extends Handler {
1412        private boolean mBound = false;
1413        final ArrayList<HandlerParams> mPendingInstalls =
1414            new ArrayList<HandlerParams>();
1415
1416        private boolean connectToService() {
1417            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1418                    " DefaultContainerService");
1419            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1420            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1421            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1422                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1423                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1424                mBound = true;
1425                return true;
1426            }
1427            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428            return false;
1429        }
1430
1431        private void disconnectService() {
1432            mContainerService = null;
1433            mBound = false;
1434            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1435            mContext.unbindService(mDefContainerConn);
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1437        }
1438
1439        PackageHandler(Looper looper) {
1440            super(looper);
1441        }
1442
1443        public void handleMessage(Message msg) {
1444            try {
1445                doHandleMessage(msg);
1446            } finally {
1447                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1448            }
1449        }
1450
1451        void doHandleMessage(Message msg) {
1452            switch (msg.what) {
1453                case INIT_COPY: {
1454                    HandlerParams params = (HandlerParams) msg.obj;
1455                    int idx = mPendingInstalls.size();
1456                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1457                    // If a bind was already initiated we dont really
1458                    // need to do anything. The pending install
1459                    // will be processed later on.
1460                    if (!mBound) {
1461                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1462                                System.identityHashCode(mHandler));
1463                        // If this is the only one pending we might
1464                        // have to bind to the service again.
1465                        if (!connectToService()) {
1466                            Slog.e(TAG, "Failed to bind to media container service");
1467                            params.serviceError();
1468                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1469                                    System.identityHashCode(mHandler));
1470                            if (params.traceMethod != null) {
1471                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1472                                        params.traceCookie);
1473                            }
1474                            return;
1475                        } else {
1476                            // Once we bind to the service, the first
1477                            // pending request will be processed.
1478                            mPendingInstalls.add(idx, params);
1479                        }
1480                    } else {
1481                        mPendingInstalls.add(idx, params);
1482                        // Already bound to the service. Just make
1483                        // sure we trigger off processing the first request.
1484                        if (idx == 0) {
1485                            mHandler.sendEmptyMessage(MCS_BOUND);
1486                        }
1487                    }
1488                    break;
1489                }
1490                case MCS_BOUND: {
1491                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1492                    if (msg.obj != null) {
1493                        mContainerService = (IMediaContainerService) msg.obj;
1494                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1495                                System.identityHashCode(mHandler));
1496                    }
1497                    if (mContainerService == null) {
1498                        if (!mBound) {
1499                            // Something seriously wrong since we are not bound and we are not
1500                            // waiting for connection. Bail out.
1501                            Slog.e(TAG, "Cannot bind to media container service");
1502                            for (HandlerParams params : mPendingInstalls) {
1503                                // Indicate service bind error
1504                                params.serviceError();
1505                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                                        System.identityHashCode(params));
1507                                if (params.traceMethod != null) {
1508                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1509                                            params.traceMethod, params.traceCookie);
1510                                }
1511                                return;
1512                            }
1513                            mPendingInstalls.clear();
1514                        } else {
1515                            Slog.w(TAG, "Waiting to connect to media container service");
1516                        }
1517                    } else if (mPendingInstalls.size() > 0) {
1518                        HandlerParams params = mPendingInstalls.get(0);
1519                        if (params != null) {
1520                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1521                                    System.identityHashCode(params));
1522                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1523                            if (params.startCopy()) {
1524                                // We are done...  look for more work or to
1525                                // go idle.
1526                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                        "Checking for more work or unbind...");
1528                                // Delete pending install
1529                                if (mPendingInstalls.size() > 0) {
1530                                    mPendingInstalls.remove(0);
1531                                }
1532                                if (mPendingInstalls.size() == 0) {
1533                                    if (mBound) {
1534                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                                "Posting delayed MCS_UNBIND");
1536                                        removeMessages(MCS_UNBIND);
1537                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1538                                        // Unbind after a little delay, to avoid
1539                                        // continual thrashing.
1540                                        sendMessageDelayed(ubmsg, 10000);
1541                                    }
1542                                } else {
1543                                    // There are more pending requests in queue.
1544                                    // Just post MCS_BOUND message to trigger processing
1545                                    // of next pending install.
1546                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1547                                            "Posting MCS_BOUND for next work");
1548                                    mHandler.sendEmptyMessage(MCS_BOUND);
1549                                }
1550                            }
1551                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1552                        }
1553                    } else {
1554                        // Should never happen ideally.
1555                        Slog.w(TAG, "Empty queue");
1556                    }
1557                    break;
1558                }
1559                case MCS_RECONNECT: {
1560                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1561                    if (mPendingInstalls.size() > 0) {
1562                        if (mBound) {
1563                            disconnectService();
1564                        }
1565                        if (!connectToService()) {
1566                            Slog.e(TAG, "Failed to bind to media container service");
1567                            for (HandlerParams params : mPendingInstalls) {
1568                                // Indicate service bind error
1569                                params.serviceError();
1570                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1571                                        System.identityHashCode(params));
1572                            }
1573                            mPendingInstalls.clear();
1574                        }
1575                    }
1576                    break;
1577                }
1578                case MCS_UNBIND: {
1579                    // If there is no actual work left, then time to unbind.
1580                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1581
1582                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1583                        if (mBound) {
1584                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1585
1586                            disconnectService();
1587                        }
1588                    } else if (mPendingInstalls.size() > 0) {
1589                        // There are more pending requests in queue.
1590                        // Just post MCS_BOUND message to trigger processing
1591                        // of next pending install.
1592                        mHandler.sendEmptyMessage(MCS_BOUND);
1593                    }
1594
1595                    break;
1596                }
1597                case MCS_GIVE_UP: {
1598                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1599                    HandlerParams params = mPendingInstalls.remove(0);
1600                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1601                            System.identityHashCode(params));
1602                    break;
1603                }
1604                case SEND_PENDING_BROADCAST: {
1605                    String packages[];
1606                    ArrayList<String> components[];
1607                    int size = 0;
1608                    int uids[];
1609                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1610                    synchronized (mPackages) {
1611                        if (mPendingBroadcasts == null) {
1612                            return;
1613                        }
1614                        size = mPendingBroadcasts.size();
1615                        if (size <= 0) {
1616                            // Nothing to be done. Just return
1617                            return;
1618                        }
1619                        packages = new String[size];
1620                        components = new ArrayList[size];
1621                        uids = new int[size];
1622                        int i = 0;  // filling out the above arrays
1623
1624                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1625                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1626                            Iterator<Map.Entry<String, ArrayList<String>>> it
1627                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1628                                            .entrySet().iterator();
1629                            while (it.hasNext() && i < size) {
1630                                Map.Entry<String, ArrayList<String>> ent = it.next();
1631                                packages[i] = ent.getKey();
1632                                components[i] = ent.getValue();
1633                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1634                                uids[i] = (ps != null)
1635                                        ? UserHandle.getUid(packageUserId, ps.appId)
1636                                        : -1;
1637                                i++;
1638                            }
1639                        }
1640                        size = i;
1641                        mPendingBroadcasts.clear();
1642                    }
1643                    // Send broadcasts
1644                    for (int i = 0; i < size; i++) {
1645                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1646                    }
1647                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1648                    break;
1649                }
1650                case START_CLEANING_PACKAGE: {
1651                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1652                    final String packageName = (String)msg.obj;
1653                    final int userId = msg.arg1;
1654                    final boolean andCode = msg.arg2 != 0;
1655                    synchronized (mPackages) {
1656                        if (userId == UserHandle.USER_ALL) {
1657                            int[] users = sUserManager.getUserIds();
1658                            for (int user : users) {
1659                                mSettings.addPackageToCleanLPw(
1660                                        new PackageCleanItem(user, packageName, andCode));
1661                            }
1662                        } else {
1663                            mSettings.addPackageToCleanLPw(
1664                                    new PackageCleanItem(userId, packageName, andCode));
1665                        }
1666                    }
1667                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1668                    startCleaningPackages();
1669                } break;
1670                case POST_INSTALL: {
1671                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1672
1673                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1674                    final boolean didRestore = (msg.arg2 != 0);
1675                    mRunningInstalls.delete(msg.arg1);
1676
1677                    if (data != null) {
1678                        InstallArgs args = data.args;
1679                        PackageInstalledInfo parentRes = data.res;
1680
1681                        final boolean grantPermissions = (args.installFlags
1682                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1683                        final boolean killApp = (args.installFlags
1684                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1685                        final boolean virtualPreload = ((args.installFlags
1686                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1687                        final String[] grantedPermissions = args.installGrantPermissions;
1688
1689                        // Handle the parent package
1690                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1691                                virtualPreload, grantedPermissions, didRestore,
1692                                args.installerPackageName, args.observer);
1693
1694                        // Handle the child packages
1695                        final int childCount = (parentRes.addedChildPackages != null)
1696                                ? parentRes.addedChildPackages.size() : 0;
1697                        for (int i = 0; i < childCount; i++) {
1698                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1699                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1700                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1701                                    args.installerPackageName, args.observer);
1702                        }
1703
1704                        // Log tracing if needed
1705                        if (args.traceMethod != null) {
1706                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1707                                    args.traceCookie);
1708                        }
1709                    } else {
1710                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1711                    }
1712
1713                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1714                } break;
1715                case WRITE_SETTINGS: {
1716                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1717                    synchronized (mPackages) {
1718                        removeMessages(WRITE_SETTINGS);
1719                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1720                        mSettings.writeLPr();
1721                        mDirtyUsers.clear();
1722                    }
1723                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1724                } break;
1725                case WRITE_PACKAGE_RESTRICTIONS: {
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1727                    synchronized (mPackages) {
1728                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1729                        for (int userId : mDirtyUsers) {
1730                            mSettings.writePackageRestrictionsLPr(userId);
1731                        }
1732                        mDirtyUsers.clear();
1733                    }
1734                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1735                } break;
1736                case WRITE_PACKAGE_LIST: {
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1738                    synchronized (mPackages) {
1739                        removeMessages(WRITE_PACKAGE_LIST);
1740                        mSettings.writePackageListLPr(msg.arg1);
1741                    }
1742                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1743                } break;
1744                case CHECK_PENDING_VERIFICATION: {
1745                    final int verificationId = msg.arg1;
1746                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1747
1748                    if ((state != null) && !state.timeoutExtended()) {
1749                        final InstallArgs args = state.getInstallArgs();
1750                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1751
1752                        Slog.i(TAG, "Verification timed out for " + originUri);
1753                        mPendingVerification.remove(verificationId);
1754
1755                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1756
1757                        final UserHandle user = args.getUser();
1758                        if (getDefaultVerificationResponse(user)
1759                                == PackageManager.VERIFICATION_ALLOW) {
1760                            Slog.i(TAG, "Continuing with installation of " + originUri);
1761                            state.setVerifierResponse(Binder.getCallingUid(),
1762                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1763                            broadcastPackageVerified(verificationId, originUri,
1764                                    PackageManager.VERIFICATION_ALLOW, user);
1765                            try {
1766                                ret = args.copyApk(mContainerService, true);
1767                            } catch (RemoteException e) {
1768                                Slog.e(TAG, "Could not contact the ContainerService");
1769                            }
1770                        } else {
1771                            broadcastPackageVerified(verificationId, originUri,
1772                                    PackageManager.VERIFICATION_REJECT, user);
1773                        }
1774
1775                        Trace.asyncTraceEnd(
1776                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1777
1778                        processPendingInstall(args, ret);
1779                        mHandler.sendEmptyMessage(MCS_UNBIND);
1780                    }
1781                    break;
1782                }
1783                case PACKAGE_VERIFIED: {
1784                    final int verificationId = msg.arg1;
1785
1786                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1787                    if (state == null) {
1788                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1789                        break;
1790                    }
1791
1792                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1793
1794                    state.setVerifierResponse(response.callerUid, response.code);
1795
1796                    if (state.isVerificationComplete()) {
1797                        mPendingVerification.remove(verificationId);
1798
1799                        final InstallArgs args = state.getInstallArgs();
1800                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1801
1802                        int ret;
1803                        if (state.isInstallAllowed()) {
1804                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1805                            broadcastPackageVerified(verificationId, originUri,
1806                                    response.code, state.getInstallArgs().getUser());
1807                            try {
1808                                ret = args.copyApk(mContainerService, true);
1809                            } catch (RemoteException e) {
1810                                Slog.e(TAG, "Could not contact the ContainerService");
1811                            }
1812                        } else {
1813                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1814                        }
1815
1816                        Trace.asyncTraceEnd(
1817                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1818
1819                        processPendingInstall(args, ret);
1820                        mHandler.sendEmptyMessage(MCS_UNBIND);
1821                    }
1822
1823                    break;
1824                }
1825                case START_INTENT_FILTER_VERIFICATIONS: {
1826                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1827                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1828                            params.replacing, params.pkg);
1829                    break;
1830                }
1831                case INTENT_FILTER_VERIFIED: {
1832                    final int verificationId = msg.arg1;
1833
1834                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1835                            verificationId);
1836                    if (state == null) {
1837                        Slog.w(TAG, "Invalid IntentFilter verification token "
1838                                + verificationId + " received");
1839                        break;
1840                    }
1841
1842                    final int userId = state.getUserId();
1843
1844                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1845                            "Processing IntentFilter verification with token:"
1846                            + verificationId + " and userId:" + userId);
1847
1848                    final IntentFilterVerificationResponse response =
1849                            (IntentFilterVerificationResponse) msg.obj;
1850
1851                    state.setVerifierResponse(response.callerUid, response.code);
1852
1853                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1854                            "IntentFilter verification with token:" + verificationId
1855                            + " and userId:" + userId
1856                            + " is settings verifier response with response code:"
1857                            + response.code);
1858
1859                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1860                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1861                                + response.getFailedDomainsString());
1862                    }
1863
1864                    if (state.isVerificationComplete()) {
1865                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1866                    } else {
1867                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1868                                "IntentFilter verification with token:" + verificationId
1869                                + " was not said to be complete");
1870                    }
1871
1872                    break;
1873                }
1874                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1875                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1876                            mInstantAppResolverConnection,
1877                            (InstantAppRequest) msg.obj,
1878                            mInstantAppInstallerActivity,
1879                            mHandler);
1880                }
1881            }
1882        }
1883    }
1884
1885    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1886        @Override
1887        public void onGidsChanged(int appId, int userId) {
1888            mHandler.post(new Runnable() {
1889                @Override
1890                public void run() {
1891                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1892                }
1893            });
1894        }
1895        @Override
1896        public void onPermissionGranted(int uid, int userId) {
1897            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1898
1899            // Not critical; if this is lost, the application has to request again.
1900            synchronized (mPackages) {
1901                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1902            }
1903        }
1904        @Override
1905        public void onInstallPermissionGranted() {
1906            synchronized (mPackages) {
1907                scheduleWriteSettingsLocked();
1908            }
1909        }
1910        @Override
1911        public void onPermissionRevoked(int uid, int userId) {
1912            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1913
1914            synchronized (mPackages) {
1915                // Critical; after this call the application should never have the permission
1916                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1917            }
1918
1919            final int appId = UserHandle.getAppId(uid);
1920            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1921        }
1922        @Override
1923        public void onInstallPermissionRevoked() {
1924            synchronized (mPackages) {
1925                scheduleWriteSettingsLocked();
1926            }
1927        }
1928        @Override
1929        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1930            synchronized (mPackages) {
1931                for (int userId : updatedUserIds) {
1932                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1933                }
1934            }
1935        }
1936        @Override
1937        public void onInstallPermissionUpdated() {
1938            synchronized (mPackages) {
1939                scheduleWriteSettingsLocked();
1940            }
1941        }
1942        @Override
1943        public void onPermissionRemoved() {
1944            synchronized (mPackages) {
1945                mSettings.writeLPr();
1946            }
1947        }
1948    };
1949
1950    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1951            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1952            boolean launchedForRestore, String installerPackage,
1953            IPackageInstallObserver2 installObserver) {
1954        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1955            // Send the removed broadcasts
1956            if (res.removedInfo != null) {
1957                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1958            }
1959
1960            // Now that we successfully installed the package, grant runtime
1961            // permissions if requested before broadcasting the install. Also
1962            // for legacy apps in permission review mode we clear the permission
1963            // review flag which is used to emulate runtime permissions for
1964            // legacy apps.
1965            if (grantPermissions) {
1966                final int callingUid = Binder.getCallingUid();
1967                mPermissionManager.grantRequestedRuntimePermissions(
1968                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1969                        mPermissionCallback);
1970            }
1971
1972            final boolean update = res.removedInfo != null
1973                    && res.removedInfo.removedPackage != null;
1974            final String installerPackageName =
1975                    res.installerPackageName != null
1976                            ? res.installerPackageName
1977                            : res.removedInfo != null
1978                                    ? res.removedInfo.installerPackageName
1979                                    : null;
1980
1981            // If this is the first time we have child packages for a disabled privileged
1982            // app that had no children, we grant requested runtime permissions to the new
1983            // children if the parent on the system image had them already granted.
1984            if (res.pkg.parentPackage != null) {
1985                final int callingUid = Binder.getCallingUid();
1986                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1987                        res.pkg, callingUid, mPermissionCallback);
1988            }
1989
1990            synchronized (mPackages) {
1991                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1992            }
1993
1994            final String packageName = res.pkg.applicationInfo.packageName;
1995
1996            // Determine the set of users who are adding this package for
1997            // the first time vs. those who are seeing an update.
1998            int[] firstUserIds = EMPTY_INT_ARRAY;
1999            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2000            int[] updateUserIds = EMPTY_INT_ARRAY;
2001            int[] instantUserIds = EMPTY_INT_ARRAY;
2002            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2003            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2004            for (int newUser : res.newUsers) {
2005                final boolean isInstantApp = ps.getInstantApp(newUser);
2006                if (allNewUsers) {
2007                    if (isInstantApp) {
2008                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2009                    } else {
2010                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2011                    }
2012                    continue;
2013                }
2014                boolean isNew = true;
2015                for (int origUser : res.origUsers) {
2016                    if (origUser == newUser) {
2017                        isNew = false;
2018                        break;
2019                    }
2020                }
2021                if (isNew) {
2022                    if (isInstantApp) {
2023                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2024                    } else {
2025                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2026                    }
2027                } else {
2028                    if (isInstantApp) {
2029                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2030                    } else {
2031                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2032                    }
2033                }
2034            }
2035
2036            // Send installed broadcasts if the package is not a static shared lib.
2037            if (res.pkg.staticSharedLibName == null) {
2038                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2039
2040                // Send added for users that see the package for the first time
2041                // sendPackageAddedForNewUsers also deals with system apps
2042                int appId = UserHandle.getAppId(res.uid);
2043                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2044                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2045                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2046
2047                // Send added for users that don't see the package for the first time
2048                Bundle extras = new Bundle(1);
2049                extras.putInt(Intent.EXTRA_UID, res.uid);
2050                if (update) {
2051                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2052                }
2053                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2054                        extras, 0 /*flags*/,
2055                        null /*targetPackage*/, null /*finishedReceiver*/,
2056                        updateUserIds, instantUserIds);
2057                if (installerPackageName != null) {
2058                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2059                            extras, 0 /*flags*/,
2060                            installerPackageName, null /*finishedReceiver*/,
2061                            updateUserIds, instantUserIds);
2062                }
2063
2064                // Send replaced for users that don't see the package for the first time
2065                if (update) {
2066                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2067                            packageName, extras, 0 /*flags*/,
2068                            null /*targetPackage*/, null /*finishedReceiver*/,
2069                            updateUserIds, instantUserIds);
2070                    if (installerPackageName != null) {
2071                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2072                                extras, 0 /*flags*/,
2073                                installerPackageName, null /*finishedReceiver*/,
2074                                updateUserIds, instantUserIds);
2075                    }
2076                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2077                            null /*package*/, null /*extras*/, 0 /*flags*/,
2078                            packageName /*targetPackage*/,
2079                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2080                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2081                    // First-install and we did a restore, so we're responsible for the
2082                    // first-launch broadcast.
2083                    if (DEBUG_BACKUP) {
2084                        Slog.i(TAG, "Post-restore of " + packageName
2085                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2086                    }
2087                    sendFirstLaunchBroadcast(packageName, installerPackage,
2088                            firstUserIds, firstInstantUserIds);
2089                }
2090
2091                // Send broadcast package appeared if forward locked/external for all users
2092                // treat asec-hosted packages like removable media on upgrade
2093                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2094                    if (DEBUG_INSTALL) {
2095                        Slog.i(TAG, "upgrading pkg " + res.pkg
2096                                + " is ASEC-hosted -> AVAILABLE");
2097                    }
2098                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2099                    ArrayList<String> pkgList = new ArrayList<>(1);
2100                    pkgList.add(packageName);
2101                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2102                }
2103            }
2104
2105            // Work that needs to happen on first install within each user
2106            if (firstUserIds != null && firstUserIds.length > 0) {
2107                synchronized (mPackages) {
2108                    for (int userId : firstUserIds) {
2109                        // If this app is a browser and it's newly-installed for some
2110                        // users, clear any default-browser state in those users. The
2111                        // app's nature doesn't depend on the user, so we can just check
2112                        // its browser nature in any user and generalize.
2113                        if (packageIsBrowser(packageName, userId)) {
2114                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2115                        }
2116
2117                        // We may also need to apply pending (restored) runtime
2118                        // permission grants within these users.
2119                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2120                    }
2121                }
2122            }
2123
2124            if (allNewUsers && !update) {
2125                notifyPackageAdded(packageName);
2126            }
2127
2128            // Log current value of "unknown sources" setting
2129            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2130                    getUnknownSourcesSettings());
2131
2132            // Remove the replaced package's older resources safely now
2133            // We delete after a gc for applications  on sdcard.
2134            if (res.removedInfo != null && res.removedInfo.args != null) {
2135                Runtime.getRuntime().gc();
2136                synchronized (mInstallLock) {
2137                    res.removedInfo.args.doPostDeleteLI(true);
2138                }
2139            } else {
2140                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2141                // and not block here.
2142                VMRuntime.getRuntime().requestConcurrentGC();
2143            }
2144
2145            // Notify DexManager that the package was installed for new users.
2146            // The updated users should already be indexed and the package code paths
2147            // should not change.
2148            // Don't notify the manager for ephemeral apps as they are not expected to
2149            // survive long enough to benefit of background optimizations.
2150            for (int userId : firstUserIds) {
2151                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2152                // There's a race currently where some install events may interleave with an uninstall.
2153                // This can lead to package info being null (b/36642664).
2154                if (info != null) {
2155                    mDexManager.notifyPackageInstalled(info, userId);
2156                }
2157            }
2158        }
2159
2160        // If someone is watching installs - notify them
2161        if (installObserver != null) {
2162            try {
2163                Bundle extras = extrasForInstallResult(res);
2164                installObserver.onPackageInstalled(res.name, res.returnCode,
2165                        res.returnMsg, extras);
2166            } catch (RemoteException e) {
2167                Slog.i(TAG, "Observer no longer exists.");
2168            }
2169        }
2170    }
2171
2172    private StorageEventListener mStorageListener = new StorageEventListener() {
2173        @Override
2174        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2175            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2176                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2177                    final String volumeUuid = vol.getFsUuid();
2178
2179                    // Clean up any users or apps that were removed or recreated
2180                    // while this volume was missing
2181                    sUserManager.reconcileUsers(volumeUuid);
2182                    reconcileApps(volumeUuid);
2183
2184                    // Clean up any install sessions that expired or were
2185                    // cancelled while this volume was missing
2186                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2187
2188                    loadPrivatePackages(vol);
2189
2190                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2191                    unloadPrivatePackages(vol);
2192                }
2193            }
2194        }
2195
2196        @Override
2197        public void onVolumeForgotten(String fsUuid) {
2198            if (TextUtils.isEmpty(fsUuid)) {
2199                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2200                return;
2201            }
2202
2203            // Remove any apps installed on the forgotten volume
2204            synchronized (mPackages) {
2205                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2206                for (PackageSetting ps : packages) {
2207                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2208                    deletePackageVersioned(new VersionedPackage(ps.name,
2209                            PackageManager.VERSION_CODE_HIGHEST),
2210                            new LegacyPackageDeleteObserver(null).getBinder(),
2211                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2212                    // Try very hard to release any references to this package
2213                    // so we don't risk the system server being killed due to
2214                    // open FDs
2215                    AttributeCache.instance().removePackage(ps.name);
2216                }
2217
2218                mSettings.onVolumeForgotten(fsUuid);
2219                mSettings.writeLPr();
2220            }
2221        }
2222    };
2223
2224    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2225        Bundle extras = null;
2226        switch (res.returnCode) {
2227            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2228                extras = new Bundle();
2229                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2230                        res.origPermission);
2231                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2232                        res.origPackage);
2233                break;
2234            }
2235            case PackageManager.INSTALL_SUCCEEDED: {
2236                extras = new Bundle();
2237                extras.putBoolean(Intent.EXTRA_REPLACING,
2238                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2239                break;
2240            }
2241        }
2242        return extras;
2243    }
2244
2245    void scheduleWriteSettingsLocked() {
2246        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2247            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2248        }
2249    }
2250
2251    void scheduleWritePackageListLocked(int userId) {
2252        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2253            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2254            msg.arg1 = userId;
2255            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2256        }
2257    }
2258
2259    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2260        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2261        scheduleWritePackageRestrictionsLocked(userId);
2262    }
2263
2264    void scheduleWritePackageRestrictionsLocked(int userId) {
2265        final int[] userIds = (userId == UserHandle.USER_ALL)
2266                ? sUserManager.getUserIds() : new int[]{userId};
2267        for (int nextUserId : userIds) {
2268            if (!sUserManager.exists(nextUserId)) return;
2269            mDirtyUsers.add(nextUserId);
2270            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2271                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2272            }
2273        }
2274    }
2275
2276    public static PackageManagerService main(Context context, Installer installer,
2277            boolean factoryTest, boolean onlyCore) {
2278        // Self-check for initial settings.
2279        PackageManagerServiceCompilerMapping.checkProperties();
2280
2281        PackageManagerService m = new PackageManagerService(context, installer,
2282                factoryTest, onlyCore);
2283        m.enableSystemUserPackages();
2284        ServiceManager.addService("package", m);
2285        final PackageManagerNative pmn = m.new PackageManagerNative();
2286        ServiceManager.addService("package_native", pmn);
2287        return m;
2288    }
2289
2290    private void enableSystemUserPackages() {
2291        if (!UserManager.isSplitSystemUser()) {
2292            return;
2293        }
2294        // For system user, enable apps based on the following conditions:
2295        // - app is whitelisted or belong to one of these groups:
2296        //   -- system app which has no launcher icons
2297        //   -- system app which has INTERACT_ACROSS_USERS permission
2298        //   -- system IME app
2299        // - app is not in the blacklist
2300        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2301        Set<String> enableApps = new ArraySet<>();
2302        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2303                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2304                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2305        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2306        enableApps.addAll(wlApps);
2307        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2308                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2309        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2310        enableApps.removeAll(blApps);
2311        Log.i(TAG, "Applications installed for system user: " + enableApps);
2312        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2313                UserHandle.SYSTEM);
2314        final int allAppsSize = allAps.size();
2315        synchronized (mPackages) {
2316            for (int i = 0; i < allAppsSize; i++) {
2317                String pName = allAps.get(i);
2318                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2319                // Should not happen, but we shouldn't be failing if it does
2320                if (pkgSetting == null) {
2321                    continue;
2322                }
2323                boolean install = enableApps.contains(pName);
2324                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2325                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2326                            + " for system user");
2327                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2328                }
2329            }
2330            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2331        }
2332    }
2333
2334    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2335        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2336                Context.DISPLAY_SERVICE);
2337        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2338    }
2339
2340    /**
2341     * Requests that files preopted on a secondary system partition be copied to the data partition
2342     * if possible.  Note that the actual copying of the files is accomplished by init for security
2343     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2344     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2345     */
2346    private static void requestCopyPreoptedFiles() {
2347        final int WAIT_TIME_MS = 100;
2348        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2349        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2350            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2351            // We will wait for up to 100 seconds.
2352            final long timeStart = SystemClock.uptimeMillis();
2353            final long timeEnd = timeStart + 100 * 1000;
2354            long timeNow = timeStart;
2355            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2356                try {
2357                    Thread.sleep(WAIT_TIME_MS);
2358                } catch (InterruptedException e) {
2359                    // Do nothing
2360                }
2361                timeNow = SystemClock.uptimeMillis();
2362                if (timeNow > timeEnd) {
2363                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2364                    Slog.wtf(TAG, "cppreopt did not finish!");
2365                    break;
2366                }
2367            }
2368
2369            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2370        }
2371    }
2372
2373    public PackageManagerService(Context context, Installer installer,
2374            boolean factoryTest, boolean onlyCore) {
2375        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2376        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2377        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2378                SystemClock.uptimeMillis());
2379
2380        if (mSdkVersion <= 0) {
2381            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2382        }
2383
2384        mContext = context;
2385
2386        mFactoryTest = factoryTest;
2387        mOnlyCore = onlyCore;
2388        mMetrics = new DisplayMetrics();
2389        mInstaller = installer;
2390
2391        // Create sub-components that provide services / data. Order here is important.
2392        synchronized (mInstallLock) {
2393        synchronized (mPackages) {
2394            // Expose private service for system components to use.
2395            LocalServices.addService(
2396                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2397            sUserManager = new UserManagerService(context, this,
2398                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2399            mPermissionManager = PermissionManagerService.create(context,
2400                    new DefaultPermissionGrantedCallback() {
2401                        @Override
2402                        public void onDefaultRuntimePermissionsGranted(int userId) {
2403                            synchronized(mPackages) {
2404                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2405                            }
2406                        }
2407                    }, mPackages /*externalLock*/);
2408            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2409            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2410        }
2411        }
2412        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2415                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2416        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2417                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2418        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2419                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2420        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2421                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2422        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2423                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2424        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2425                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2426
2427        String separateProcesses = SystemProperties.get("debug.separate_processes");
2428        if (separateProcesses != null && separateProcesses.length() > 0) {
2429            if ("*".equals(separateProcesses)) {
2430                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2431                mSeparateProcesses = null;
2432                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2433            } else {
2434                mDefParseFlags = 0;
2435                mSeparateProcesses = separateProcesses.split(",");
2436                Slog.w(TAG, "Running with debug.separate_processes: "
2437                        + separateProcesses);
2438            }
2439        } else {
2440            mDefParseFlags = 0;
2441            mSeparateProcesses = null;
2442        }
2443
2444        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2445                "*dexopt*");
2446        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2447                installer, mInstallLock);
2448        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2449                dexManagerListener);
2450        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2451        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2452
2453        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2454                FgThread.get().getLooper());
2455
2456        getDefaultDisplayMetrics(context, mMetrics);
2457
2458        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2459        SystemConfig systemConfig = SystemConfig.getInstance();
2460        mAvailableFeatures = systemConfig.getAvailableFeatures();
2461        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2462
2463        mProtectedPackages = new ProtectedPackages(mContext);
2464
2465        synchronized (mInstallLock) {
2466        // writer
2467        synchronized (mPackages) {
2468            mHandlerThread = new ServiceThread(TAG,
2469                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2470            mHandlerThread.start();
2471            mHandler = new PackageHandler(mHandlerThread.getLooper());
2472            mProcessLoggingHandler = new ProcessLoggingHandler();
2473            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2474            mInstantAppRegistry = new InstantAppRegistry(this);
2475
2476            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2477            final int builtInLibCount = libConfig.size();
2478            for (int i = 0; i < builtInLibCount; i++) {
2479                String name = libConfig.keyAt(i);
2480                String path = libConfig.valueAt(i);
2481                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2482                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2483            }
2484
2485            SELinuxMMAC.readInstallPolicy();
2486
2487            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2488            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2489            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2490
2491            // Clean up orphaned packages for which the code path doesn't exist
2492            // and they are an update to a system app - caused by bug/32321269
2493            final int packageSettingCount = mSettings.mPackages.size();
2494            for (int i = packageSettingCount - 1; i >= 0; i--) {
2495                PackageSetting ps = mSettings.mPackages.valueAt(i);
2496                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2497                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2498                    mSettings.mPackages.removeAt(i);
2499                    mSettings.enableSystemPackageLPw(ps.name);
2500                }
2501            }
2502
2503            if (mFirstBoot) {
2504                requestCopyPreoptedFiles();
2505            }
2506
2507            String customResolverActivity = Resources.getSystem().getString(
2508                    R.string.config_customResolverActivity);
2509            if (TextUtils.isEmpty(customResolverActivity)) {
2510                customResolverActivity = null;
2511            } else {
2512                mCustomResolverComponentName = ComponentName.unflattenFromString(
2513                        customResolverActivity);
2514            }
2515
2516            long startTime = SystemClock.uptimeMillis();
2517
2518            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2519                    startTime);
2520
2521            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2522            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2523
2524            if (bootClassPath == null) {
2525                Slog.w(TAG, "No BOOTCLASSPATH found!");
2526            }
2527
2528            if (systemServerClassPath == null) {
2529                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2530            }
2531
2532            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2533
2534            final VersionInfo ver = mSettings.getInternalVersion();
2535            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2536            if (mIsUpgrade) {
2537                logCriticalInfo(Log.INFO,
2538                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2539            }
2540
2541            // when upgrading from pre-M, promote system app permissions from install to runtime
2542            mPromoteSystemApps =
2543                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2544
2545            // When upgrading from pre-N, we need to handle package extraction like first boot,
2546            // as there is no profiling data available.
2547            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2548
2549            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2550
2551            // save off the names of pre-existing system packages prior to scanning; we don't
2552            // want to automatically grant runtime permissions for new system apps
2553            if (mPromoteSystemApps) {
2554                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2555                while (pkgSettingIter.hasNext()) {
2556                    PackageSetting ps = pkgSettingIter.next();
2557                    if (isSystemApp(ps)) {
2558                        mExistingSystemPackages.add(ps.name);
2559                    }
2560                }
2561            }
2562
2563            mCacheDir = preparePackageParserCache(mIsUpgrade);
2564
2565            // Set flag to monitor and not change apk file paths when
2566            // scanning install directories.
2567            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2568
2569            if (mIsUpgrade || mFirstBoot) {
2570                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2571            }
2572
2573            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2574            // For security and version matching reason, only consider
2575            // overlay packages if they reside in the right directory.
2576            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2577                    mDefParseFlags
2578                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2579                    scanFlags
2580                    | SCAN_AS_SYSTEM
2581                    | SCAN_AS_VENDOR,
2582                    0);
2583            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2584                    mDefParseFlags
2585                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2586                    scanFlags
2587                    | SCAN_AS_SYSTEM
2588                    | SCAN_AS_PRODUCT,
2589                    0);
2590
2591            mParallelPackageParserCallback.findStaticOverlayPackages();
2592
2593            // Find base frameworks (resource packages without code).
2594            scanDirTracedLI(frameworkDir,
2595                    mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2597                    scanFlags
2598                    | SCAN_NO_DEX
2599                    | SCAN_AS_SYSTEM
2600                    | SCAN_AS_PRIVILEGED,
2601                    0);
2602
2603            // Collect privileged system packages.
2604            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2605            scanDirTracedLI(privilegedAppDir,
2606                    mDefParseFlags
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2608                    scanFlags
2609                    | SCAN_AS_SYSTEM
2610                    | SCAN_AS_PRIVILEGED,
2611                    0);
2612
2613            // Collect ordinary system packages.
2614            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2615            scanDirTracedLI(systemAppDir,
2616                    mDefParseFlags
2617                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2618                    scanFlags
2619                    | SCAN_AS_SYSTEM,
2620                    0);
2621
2622            // Collect privileged vendor packages.
2623            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2624            try {
2625                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2626            } catch (IOException e) {
2627                // failed to look up canonical path, continue with original one
2628            }
2629            scanDirTracedLI(privilegedVendorAppDir,
2630                    mDefParseFlags
2631                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2632                    scanFlags
2633                    | SCAN_AS_SYSTEM
2634                    | SCAN_AS_VENDOR
2635                    | SCAN_AS_PRIVILEGED,
2636                    0);
2637
2638            // Collect ordinary vendor packages.
2639            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2640            try {
2641                vendorAppDir = vendorAppDir.getCanonicalFile();
2642            } catch (IOException e) {
2643                // failed to look up canonical path, continue with original one
2644            }
2645            scanDirTracedLI(vendorAppDir,
2646                    mDefParseFlags
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2648                    scanFlags
2649                    | SCAN_AS_SYSTEM
2650                    | SCAN_AS_VENDOR,
2651                    0);
2652
2653            // Collect privileged odm packages. /odm is another vendor partition
2654            // other than /vendor.
2655            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2656                        "priv-app");
2657            try {
2658                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2659            } catch (IOException e) {
2660                // failed to look up canonical path, continue with original one
2661            }
2662            scanDirTracedLI(privilegedOdmAppDir,
2663                    mDefParseFlags
2664                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2665                    scanFlags
2666                    | SCAN_AS_SYSTEM
2667                    | SCAN_AS_VENDOR
2668                    | SCAN_AS_PRIVILEGED,
2669                    0);
2670
2671            // Collect ordinary odm packages. /odm is another vendor partition
2672            // other than /vendor.
2673            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2674            try {
2675                odmAppDir = odmAppDir.getCanonicalFile();
2676            } catch (IOException e) {
2677                // failed to look up canonical path, continue with original one
2678            }
2679            scanDirTracedLI(odmAppDir,
2680                    mDefParseFlags
2681                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2682                    scanFlags
2683                    | SCAN_AS_SYSTEM
2684                    | SCAN_AS_VENDOR,
2685                    0);
2686
2687            // Collect all OEM packages.
2688            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2689            scanDirTracedLI(oemAppDir,
2690                    mDefParseFlags
2691                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2692                    scanFlags
2693                    | SCAN_AS_SYSTEM
2694                    | SCAN_AS_OEM,
2695                    0);
2696
2697            // Collected privileged product packages.
2698            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2699            try {
2700                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2701            } catch (IOException e) {
2702                // failed to look up canonical path, continue with original one
2703            }
2704            scanDirTracedLI(privilegedProductAppDir,
2705                    mDefParseFlags
2706                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2707                    scanFlags
2708                    | SCAN_AS_SYSTEM
2709                    | SCAN_AS_PRODUCT
2710                    | SCAN_AS_PRIVILEGED,
2711                    0);
2712
2713            // Collect ordinary product packages.
2714            File productAppDir = new File(Environment.getProductDirectory(), "app");
2715            try {
2716                productAppDir = productAppDir.getCanonicalFile();
2717            } catch (IOException e) {
2718                // failed to look up canonical path, continue with original one
2719            }
2720            scanDirTracedLI(productAppDir,
2721                    mDefParseFlags
2722                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2723                    scanFlags
2724                    | SCAN_AS_SYSTEM
2725                    | SCAN_AS_PRODUCT,
2726                    0);
2727
2728            // Prune any system packages that no longer exist.
2729            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2730            // Stub packages must either be replaced with full versions in the /data
2731            // partition or be disabled.
2732            final List<String> stubSystemApps = new ArrayList<>();
2733            if (!mOnlyCore) {
2734                // do this first before mucking with mPackages for the "expecting better" case
2735                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2736                while (pkgIterator.hasNext()) {
2737                    final PackageParser.Package pkg = pkgIterator.next();
2738                    if (pkg.isStub) {
2739                        stubSystemApps.add(pkg.packageName);
2740                    }
2741                }
2742
2743                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2744                while (psit.hasNext()) {
2745                    PackageSetting ps = psit.next();
2746
2747                    /*
2748                     * If this is not a system app, it can't be a
2749                     * disable system app.
2750                     */
2751                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2752                        continue;
2753                    }
2754
2755                    /*
2756                     * If the package is scanned, it's not erased.
2757                     */
2758                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2759                    if (scannedPkg != null) {
2760                        /*
2761                         * If the system app is both scanned and in the
2762                         * disabled packages list, then it must have been
2763                         * added via OTA. Remove it from the currently
2764                         * scanned package so the previously user-installed
2765                         * application can be scanned.
2766                         */
2767                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2768                            logCriticalInfo(Log.WARN,
2769                                    "Expecting better updated system app for " + ps.name
2770                                    + "; removing system app.  Last known"
2771                                    + " codePath=" + ps.codePathString
2772                                    + ", versionCode=" + ps.versionCode
2773                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2774                            removePackageLI(scannedPkg, true);
2775                            mExpectingBetter.put(ps.name, ps.codePath);
2776                        }
2777
2778                        continue;
2779                    }
2780
2781                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2782                        psit.remove();
2783                        logCriticalInfo(Log.WARN, "System package " + ps.name
2784                                + " no longer exists; it's data will be wiped");
2785                        // Actual deletion of code and data will be handled by later
2786                        // reconciliation step
2787                    } else {
2788                        // we still have a disabled system package, but, it still might have
2789                        // been removed. check the code path still exists and check there's
2790                        // still a package. the latter can happen if an OTA keeps the same
2791                        // code path, but, changes the package name.
2792                        final PackageSetting disabledPs =
2793                                mSettings.getDisabledSystemPkgLPr(ps.name);
2794                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2795                                || disabledPs.pkg == null) {
2796                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2797                        }
2798                    }
2799                }
2800            }
2801
2802            //delete tmp files
2803            deleteTempPackageFiles();
2804
2805            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2806
2807            // Remove any shared userIDs that have no associated packages
2808            mSettings.pruneSharedUsersLPw();
2809            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2810            final int systemPackagesCount = mPackages.size();
2811            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2812                    + " ms, packageCount: " + systemPackagesCount
2813                    + " , timePerPackage: "
2814                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2815                    + " , cached: " + cachedSystemApps);
2816            if (mIsUpgrade && systemPackagesCount > 0) {
2817                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2818                        ((int) systemScanTime) / systemPackagesCount);
2819            }
2820            if (!mOnlyCore) {
2821                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2822                        SystemClock.uptimeMillis());
2823                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2824
2825                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2826                        | PackageParser.PARSE_FORWARD_LOCK,
2827                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2828
2829                // Remove disable package settings for updated system apps that were
2830                // removed via an OTA. If the update is no longer present, remove the
2831                // app completely. Otherwise, revoke their system privileges.
2832                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2833                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2834                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2835                    final String msg;
2836                    if (deletedPkg == null) {
2837                        // should have found an update, but, we didn't; remove everything
2838                        msg = "Updated system package " + deletedAppName
2839                                + " no longer exists; removing its data";
2840                        // Actual deletion of code and data will be handled by later
2841                        // reconciliation step
2842                    } else {
2843                        // found an update; revoke system privileges
2844                        msg = "Updated system package + " + deletedAppName
2845                                + " no longer exists; revoking system privileges";
2846
2847                        // Don't do anything if a stub is removed from the system image. If
2848                        // we were to remove the uncompressed version from the /data partition,
2849                        // this is where it'd be done.
2850
2851                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2852                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2853                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2854                    }
2855                    logCriticalInfo(Log.WARN, msg);
2856                }
2857
2858                /*
2859                 * Make sure all system apps that we expected to appear on
2860                 * the userdata partition actually showed up. If they never
2861                 * appeared, crawl back and revive the system version.
2862                 */
2863                for (int i = 0; i < mExpectingBetter.size(); i++) {
2864                    final String packageName = mExpectingBetter.keyAt(i);
2865                    if (!mPackages.containsKey(packageName)) {
2866                        final File scanFile = mExpectingBetter.valueAt(i);
2867
2868                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2869                                + " but never showed up; reverting to system");
2870
2871                        final @ParseFlags int reparseFlags;
2872                        final @ScanFlags int rescanFlags;
2873                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2874                            reparseFlags =
2875                                    mDefParseFlags |
2876                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2877                            rescanFlags =
2878                                    scanFlags
2879                                    | SCAN_AS_SYSTEM
2880                                    | SCAN_AS_PRIVILEGED;
2881                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2882                            reparseFlags =
2883                                    mDefParseFlags |
2884                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2885                            rescanFlags =
2886                                    scanFlags
2887                                    | SCAN_AS_SYSTEM;
2888                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2889                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2890                            reparseFlags =
2891                                    mDefParseFlags |
2892                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2893                            rescanFlags =
2894                                    scanFlags
2895                                    | SCAN_AS_SYSTEM
2896                                    | SCAN_AS_VENDOR
2897                                    | SCAN_AS_PRIVILEGED;
2898                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2899                                || FileUtils.contains(odmAppDir, scanFile)) {
2900                            reparseFlags =
2901                                    mDefParseFlags |
2902                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2903                            rescanFlags =
2904                                    scanFlags
2905                                    | SCAN_AS_SYSTEM
2906                                    | SCAN_AS_VENDOR;
2907                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2908                            reparseFlags =
2909                                    mDefParseFlags |
2910                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2911                            rescanFlags =
2912                                    scanFlags
2913                                    | SCAN_AS_SYSTEM
2914                                    | SCAN_AS_OEM;
2915                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2916                            reparseFlags =
2917                                    mDefParseFlags |
2918                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2919                            rescanFlags =
2920                                    scanFlags
2921                                    | SCAN_AS_SYSTEM
2922                                    | SCAN_AS_PRODUCT
2923                                    | SCAN_AS_PRIVILEGED;
2924                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2925                            reparseFlags =
2926                                    mDefParseFlags |
2927                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2928                            rescanFlags =
2929                                    scanFlags
2930                                    | SCAN_AS_SYSTEM
2931                                    | SCAN_AS_PRODUCT;
2932                        } else {
2933                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2934                            continue;
2935                        }
2936
2937                        mSettings.enableSystemPackageLPw(packageName);
2938
2939                        try {
2940                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2941                        } catch (PackageManagerException e) {
2942                            Slog.e(TAG, "Failed to parse original system package: "
2943                                    + e.getMessage());
2944                        }
2945                    }
2946                }
2947
2948                // Uncompress and install any stubbed system applications.
2949                // This must be done last to ensure all stubs are replaced or disabled.
2950                decompressSystemApplications(stubSystemApps, scanFlags);
2951
2952                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2953                                - cachedSystemApps;
2954
2955                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2956                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2957                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2958                        + " ms, packageCount: " + dataPackagesCount
2959                        + " , timePerPackage: "
2960                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2961                        + " , cached: " + cachedNonSystemApps);
2962                if (mIsUpgrade && dataPackagesCount > 0) {
2963                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2964                            ((int) dataScanTime) / dataPackagesCount);
2965                }
2966            }
2967            mExpectingBetter.clear();
2968
2969            // Resolve the storage manager.
2970            mStorageManagerPackage = getStorageManagerPackageName();
2971
2972            // Resolve protected action filters. Only the setup wizard is allowed to
2973            // have a high priority filter for these actions.
2974            mSetupWizardPackage = getSetupWizardPackageName();
2975            if (mProtectedFilters.size() > 0) {
2976                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2977                    Slog.i(TAG, "No setup wizard;"
2978                        + " All protected intents capped to priority 0");
2979                }
2980                for (ActivityIntentInfo filter : mProtectedFilters) {
2981                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2982                        if (DEBUG_FILTERS) {
2983                            Slog.i(TAG, "Found setup wizard;"
2984                                + " allow priority " + filter.getPriority() + ";"
2985                                + " package: " + filter.activity.info.packageName
2986                                + " activity: " + filter.activity.className
2987                                + " priority: " + filter.getPriority());
2988                        }
2989                        // skip setup wizard; allow it to keep the high priority filter
2990                        continue;
2991                    }
2992                    if (DEBUG_FILTERS) {
2993                        Slog.i(TAG, "Protected action; cap priority to 0;"
2994                                + " package: " + filter.activity.info.packageName
2995                                + " activity: " + filter.activity.className
2996                                + " origPrio: " + filter.getPriority());
2997                    }
2998                    filter.setPriority(0);
2999                }
3000            }
3001
3002            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3003
3004            mDeferProtectedFilters = false;
3005            mProtectedFilters.clear();
3006
3007            // Now that we know all of the shared libraries, update all clients to have
3008            // the correct library paths.
3009            updateAllSharedLibrariesLPw(null);
3010
3011            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3012                // NOTE: We ignore potential failures here during a system scan (like
3013                // the rest of the commands above) because there's precious little we
3014                // can do about it. A settings error is reported, though.
3015                final List<String> changedAbiCodePath =
3016                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3017                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3018                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3019                        final String codePathString = changedAbiCodePath.get(i);
3020                        try {
3021                            mInstaller.rmdex(codePathString,
3022                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3023                        } catch (InstallerException ignored) {
3024                        }
3025                    }
3026                }
3027                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3028                // SELinux domain.
3029                setting.fixSeInfoLocked();
3030            }
3031
3032            // Now that we know all the packages we are keeping,
3033            // read and update their last usage times.
3034            mPackageUsage.read(mPackages);
3035            mCompilerStats.read();
3036
3037            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3038                    SystemClock.uptimeMillis());
3039            Slog.i(TAG, "Time to scan packages: "
3040                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3041                    + " seconds");
3042
3043            // If the platform SDK has changed since the last time we booted,
3044            // we need to re-grant app permission to catch any new ones that
3045            // appear.  This is really a hack, and means that apps can in some
3046            // cases get permissions that the user didn't initially explicitly
3047            // allow...  it would be nice to have some better way to handle
3048            // this situation.
3049            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3050            if (sdkUpdated) {
3051                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3052                        + mSdkVersion + "; regranting permissions for internal storage");
3053            }
3054            mPermissionManager.updateAllPermissions(
3055                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3056                    mPermissionCallback);
3057            ver.sdkVersion = mSdkVersion;
3058
3059            // If this is the first boot or an update from pre-M, and it is a normal
3060            // boot, then we need to initialize the default preferred apps across
3061            // all defined users.
3062            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3063                for (UserInfo user : sUserManager.getUsers(true)) {
3064                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3065                    applyFactoryDefaultBrowserLPw(user.id);
3066                    primeDomainVerificationsLPw(user.id);
3067                }
3068            }
3069
3070            // Prepare storage for system user really early during boot,
3071            // since core system apps like SettingsProvider and SystemUI
3072            // can't wait for user to start
3073            final int storageFlags;
3074            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3075                storageFlags = StorageManager.FLAG_STORAGE_DE;
3076            } else {
3077                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3078            }
3079            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3080                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3081                    true /* onlyCoreApps */);
3082            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3083                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3084                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3085                traceLog.traceBegin("AppDataFixup");
3086                try {
3087                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3088                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3089                } catch (InstallerException e) {
3090                    Slog.w(TAG, "Trouble fixing GIDs", e);
3091                }
3092                traceLog.traceEnd();
3093
3094                traceLog.traceBegin("AppDataPrepare");
3095                if (deferPackages == null || deferPackages.isEmpty()) {
3096                    return;
3097                }
3098                int count = 0;
3099                for (String pkgName : deferPackages) {
3100                    PackageParser.Package pkg = null;
3101                    synchronized (mPackages) {
3102                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3103                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3104                            pkg = ps.pkg;
3105                        }
3106                    }
3107                    if (pkg != null) {
3108                        synchronized (mInstallLock) {
3109                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3110                                    true /* maybeMigrateAppData */);
3111                        }
3112                        count++;
3113                    }
3114                }
3115                traceLog.traceEnd();
3116                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3117            }, "prepareAppData");
3118
3119            // If this is first boot after an OTA, and a normal boot, then
3120            // we need to clear code cache directories.
3121            // Note that we do *not* clear the application profiles. These remain valid
3122            // across OTAs and are used to drive profile verification (post OTA) and
3123            // profile compilation (without waiting to collect a fresh set of profiles).
3124            if (mIsUpgrade && !onlyCore) {
3125                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3126                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3127                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3128                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3129                        // No apps are running this early, so no need to freeze
3130                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3131                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3132                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3133                    }
3134                }
3135                ver.fingerprint = Build.FINGERPRINT;
3136            }
3137
3138            checkDefaultBrowser();
3139
3140            // clear only after permissions and other defaults have been updated
3141            mExistingSystemPackages.clear();
3142            mPromoteSystemApps = false;
3143
3144            // All the changes are done during package scanning.
3145            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3146
3147            // can downgrade to reader
3148            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3149            mSettings.writeLPr();
3150            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3151            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3152                    SystemClock.uptimeMillis());
3153
3154            if (!mOnlyCore) {
3155                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3156                mRequiredInstallerPackage = getRequiredInstallerLPr();
3157                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3158                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3159                if (mIntentFilterVerifierComponent != null) {
3160                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3161                            mIntentFilterVerifierComponent);
3162                } else {
3163                    mIntentFilterVerifier = null;
3164                }
3165                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3166                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3167                        SharedLibraryInfo.VERSION_UNDEFINED);
3168                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3169                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3170                        SharedLibraryInfo.VERSION_UNDEFINED);
3171            } else {
3172                mRequiredVerifierPackage = null;
3173                mRequiredInstallerPackage = null;
3174                mRequiredUninstallerPackage = null;
3175                mIntentFilterVerifierComponent = null;
3176                mIntentFilterVerifier = null;
3177                mServicesSystemSharedLibraryPackageName = null;
3178                mSharedSystemSharedLibraryPackageName = null;
3179            }
3180
3181            mInstallerService = new PackageInstallerService(context, this);
3182            final Pair<ComponentName, String> instantAppResolverComponent =
3183                    getInstantAppResolverLPr();
3184            if (instantAppResolverComponent != null) {
3185                if (DEBUG_INSTANT) {
3186                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3187                }
3188                mInstantAppResolverConnection = new InstantAppResolverConnection(
3189                        mContext, instantAppResolverComponent.first,
3190                        instantAppResolverComponent.second);
3191                mInstantAppResolverSettingsComponent =
3192                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3193            } else {
3194                mInstantAppResolverConnection = null;
3195                mInstantAppResolverSettingsComponent = null;
3196            }
3197            updateInstantAppInstallerLocked(null);
3198
3199            // Read and update the usage of dex files.
3200            // Do this at the end of PM init so that all the packages have their
3201            // data directory reconciled.
3202            // At this point we know the code paths of the packages, so we can validate
3203            // the disk file and build the internal cache.
3204            // The usage file is expected to be small so loading and verifying it
3205            // should take a fairly small time compare to the other activities (e.g. package
3206            // scanning).
3207            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3208            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3209            for (int userId : currentUserIds) {
3210                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3211            }
3212            mDexManager.load(userPackages);
3213            if (mIsUpgrade) {
3214                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3215                        (int) (SystemClock.uptimeMillis() - startTime));
3216            }
3217        } // synchronized (mPackages)
3218        } // synchronized (mInstallLock)
3219
3220        // Now after opening every single application zip, make sure they
3221        // are all flushed.  Not really needed, but keeps things nice and
3222        // tidy.
3223        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3224        Runtime.getRuntime().gc();
3225        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3226
3227        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3228        FallbackCategoryProvider.loadFallbacks();
3229        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3230
3231        // The initial scanning above does many calls into installd while
3232        // holding the mPackages lock, but we're mostly interested in yelling
3233        // once we have a booted system.
3234        mInstaller.setWarnIfHeld(mPackages);
3235
3236        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3237    }
3238
3239    /**
3240     * Uncompress and install stub applications.
3241     * <p>In order to save space on the system partition, some applications are shipped in a
3242     * compressed form. In addition the compressed bits for the full application, the
3243     * system image contains a tiny stub comprised of only the Android manifest.
3244     * <p>During the first boot, attempt to uncompress and install the full application. If
3245     * the application can't be installed for any reason, disable the stub and prevent
3246     * uncompressing the full application during future boots.
3247     * <p>In order to forcefully attempt an installation of a full application, go to app
3248     * settings and enable the application.
3249     */
3250    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3251        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3252            final String pkgName = stubSystemApps.get(i);
3253            // skip if the system package is already disabled
3254            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3255                stubSystemApps.remove(i);
3256                continue;
3257            }
3258            // skip if the package isn't installed (?!); this should never happen
3259            final PackageParser.Package pkg = mPackages.get(pkgName);
3260            if (pkg == null) {
3261                stubSystemApps.remove(i);
3262                continue;
3263            }
3264            // skip if the package has been disabled by the user
3265            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3266            if (ps != null) {
3267                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3268                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3269                    stubSystemApps.remove(i);
3270                    continue;
3271                }
3272            }
3273
3274            if (DEBUG_COMPRESSION) {
3275                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3276            }
3277
3278            // uncompress the binary to its eventual destination on /data
3279            final File scanFile = decompressPackage(pkg);
3280            if (scanFile == null) {
3281                continue;
3282            }
3283
3284            // install the package to replace the stub on /system
3285            try {
3286                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3287                removePackageLI(pkg, true /*chatty*/);
3288                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3289                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3290                        UserHandle.USER_SYSTEM, "android");
3291                stubSystemApps.remove(i);
3292                continue;
3293            } catch (PackageManagerException e) {
3294                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3295            }
3296
3297            // any failed attempt to install the package will be cleaned up later
3298        }
3299
3300        // disable any stub still left; these failed to install the full application
3301        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3302            final String pkgName = stubSystemApps.get(i);
3303            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3304            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3305                    UserHandle.USER_SYSTEM, "android");
3306            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3307        }
3308    }
3309
3310    /**
3311     * Decompresses the given package on the system image onto
3312     * the /data partition.
3313     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3314     */
3315    private File decompressPackage(PackageParser.Package pkg) {
3316        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3317        if (compressedFiles == null || compressedFiles.length == 0) {
3318            if (DEBUG_COMPRESSION) {
3319                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3320            }
3321            return null;
3322        }
3323        final File dstCodePath =
3324                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3325        int ret = PackageManager.INSTALL_SUCCEEDED;
3326        try {
3327            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3328            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3329            for (File srcFile : compressedFiles) {
3330                final String srcFileName = srcFile.getName();
3331                final String dstFileName = srcFileName.substring(
3332                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3333                final File dstFile = new File(dstCodePath, dstFileName);
3334                ret = decompressFile(srcFile, dstFile);
3335                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3336                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3337                            + "; pkg: " + pkg.packageName
3338                            + ", file: " + dstFileName);
3339                    break;
3340                }
3341            }
3342        } catch (ErrnoException e) {
3343            logCriticalInfo(Log.ERROR, "Failed to decompress"
3344                    + "; pkg: " + pkg.packageName
3345                    + ", err: " + e.errno);
3346        }
3347        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3348            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3349            NativeLibraryHelper.Handle handle = null;
3350            try {
3351                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3352                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3353                        null /*abiOverride*/);
3354            } catch (IOException e) {
3355                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3356                        + "; pkg: " + pkg.packageName);
3357                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3358            } finally {
3359                IoUtils.closeQuietly(handle);
3360            }
3361        }
3362        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3363            if (dstCodePath == null || !dstCodePath.exists()) {
3364                return null;
3365            }
3366            removeCodePathLI(dstCodePath);
3367            return null;
3368        }
3369
3370        return dstCodePath;
3371    }
3372
3373    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3374        // we're only interested in updating the installer appliction when 1) it's not
3375        // already set or 2) the modified package is the installer
3376        if (mInstantAppInstallerActivity != null
3377                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3378                        .equals(modifiedPackage)) {
3379            return;
3380        }
3381        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3382    }
3383
3384    private static File preparePackageParserCache(boolean isUpgrade) {
3385        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3386            return null;
3387        }
3388
3389        // Disable package parsing on eng builds to allow for faster incremental development.
3390        if (Build.IS_ENG) {
3391            return null;
3392        }
3393
3394        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3395            Slog.i(TAG, "Disabling package parser cache due to system property.");
3396            return null;
3397        }
3398
3399        // The base directory for the package parser cache lives under /data/system/.
3400        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3401                "package_cache");
3402        if (cacheBaseDir == null) {
3403            return null;
3404        }
3405
3406        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3407        // This also serves to "GC" unused entries when the package cache version changes (which
3408        // can only happen during upgrades).
3409        if (isUpgrade) {
3410            FileUtils.deleteContents(cacheBaseDir);
3411        }
3412
3413
3414        // Return the versioned package cache directory. This is something like
3415        // "/data/system/package_cache/1"
3416        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3417
3418        if (cacheDir == null) {
3419            // Something went wrong. Attempt to delete everything and return.
3420            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3421            FileUtils.deleteContentsAndDir(cacheBaseDir);
3422            return null;
3423        }
3424
3425        // The following is a workaround to aid development on non-numbered userdebug
3426        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3427        // the system partition is newer.
3428        //
3429        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3430        // that starts with "eng." to signify that this is an engineering build and not
3431        // destined for release.
3432        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3433            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3434
3435            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3436            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3437            // in general and should not be used for production changes. In this specific case,
3438            // we know that they will work.
3439            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3440            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3441                FileUtils.deleteContents(cacheBaseDir);
3442                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3443            }
3444        }
3445
3446        return cacheDir;
3447    }
3448
3449    @Override
3450    public boolean isFirstBoot() {
3451        // allow instant applications
3452        return mFirstBoot;
3453    }
3454
3455    @Override
3456    public boolean isOnlyCoreApps() {
3457        // allow instant applications
3458        return mOnlyCore;
3459    }
3460
3461    @Override
3462    public boolean isUpgrade() {
3463        // allow instant applications
3464        // The system property allows testing ota flow when upgraded to the same image.
3465        return mIsUpgrade || SystemProperties.getBoolean(
3466                "persist.pm.mock-upgrade", false /* default */);
3467    }
3468
3469    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3470        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3471
3472        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3473                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3474                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3475        if (matches.size() == 1) {
3476            return matches.get(0).getComponentInfo().packageName;
3477        } else if (matches.size() == 0) {
3478            Log.e(TAG, "There should probably be a verifier, but, none were found");
3479            return null;
3480        }
3481        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3482    }
3483
3484    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3485        synchronized (mPackages) {
3486            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3487            if (libraryEntry == null) {
3488                throw new IllegalStateException("Missing required shared library:" + name);
3489            }
3490            return libraryEntry.apk;
3491        }
3492    }
3493
3494    private @NonNull String getRequiredInstallerLPr() {
3495        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3496        intent.addCategory(Intent.CATEGORY_DEFAULT);
3497        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3498
3499        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3500                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3501                UserHandle.USER_SYSTEM);
3502        if (matches.size() == 1) {
3503            ResolveInfo resolveInfo = matches.get(0);
3504            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3505                throw new RuntimeException("The installer must be a privileged app");
3506            }
3507            return matches.get(0).getComponentInfo().packageName;
3508        } else {
3509            throw new RuntimeException("There must be exactly one installer; found " + matches);
3510        }
3511    }
3512
3513    private @NonNull String getRequiredUninstallerLPr() {
3514        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3515        intent.addCategory(Intent.CATEGORY_DEFAULT);
3516        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3517
3518        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3519                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3520                UserHandle.USER_SYSTEM);
3521        if (resolveInfo == null ||
3522                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3523            throw new RuntimeException("There must be exactly one uninstaller; found "
3524                    + resolveInfo);
3525        }
3526        return resolveInfo.getComponentInfo().packageName;
3527    }
3528
3529    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3530        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3531
3532        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3533                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3534                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3535        ResolveInfo best = null;
3536        final int N = matches.size();
3537        for (int i = 0; i < N; i++) {
3538            final ResolveInfo cur = matches.get(i);
3539            final String packageName = cur.getComponentInfo().packageName;
3540            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3541                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3542                continue;
3543            }
3544
3545            if (best == null || cur.priority > best.priority) {
3546                best = cur;
3547            }
3548        }
3549
3550        if (best != null) {
3551            return best.getComponentInfo().getComponentName();
3552        }
3553        Slog.w(TAG, "Intent filter verifier not found");
3554        return null;
3555    }
3556
3557    @Override
3558    public @Nullable ComponentName getInstantAppResolverComponent() {
3559        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3560            return null;
3561        }
3562        synchronized (mPackages) {
3563            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3564            if (instantAppResolver == null) {
3565                return null;
3566            }
3567            return instantAppResolver.first;
3568        }
3569    }
3570
3571    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3572        final String[] packageArray =
3573                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3574        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3575            if (DEBUG_INSTANT) {
3576                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3577            }
3578            return null;
3579        }
3580
3581        final int callingUid = Binder.getCallingUid();
3582        final int resolveFlags =
3583                MATCH_DIRECT_BOOT_AWARE
3584                | MATCH_DIRECT_BOOT_UNAWARE
3585                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3586        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3587        final Intent resolverIntent = new Intent(actionName);
3588        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3589                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3590        final int N = resolvers.size();
3591        if (N == 0) {
3592            if (DEBUG_INSTANT) {
3593                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3594            }
3595            return null;
3596        }
3597
3598        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3599        for (int i = 0; i < N; i++) {
3600            final ResolveInfo info = resolvers.get(i);
3601
3602            if (info.serviceInfo == null) {
3603                continue;
3604            }
3605
3606            final String packageName = info.serviceInfo.packageName;
3607            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3608                if (DEBUG_INSTANT) {
3609                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3610                            + " pkg: " + packageName + ", info:" + info);
3611                }
3612                continue;
3613            }
3614
3615            if (DEBUG_INSTANT) {
3616                Slog.v(TAG, "Ephemeral resolver found;"
3617                        + " pkg: " + packageName + ", info:" + info);
3618            }
3619            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3620        }
3621        if (DEBUG_INSTANT) {
3622            Slog.v(TAG, "Ephemeral resolver NOT found");
3623        }
3624        return null;
3625    }
3626
3627    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3628        String[] orderedActions = Build.IS_ENG
3629                ? new String[]{
3630                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3631                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3632                : new String[]{
3633                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3634
3635        final int resolveFlags =
3636                MATCH_DIRECT_BOOT_AWARE
3637                        | MATCH_DIRECT_BOOT_UNAWARE
3638                        | Intent.FLAG_IGNORE_EPHEMERAL
3639                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3640        final Intent intent = new Intent();
3641        intent.addCategory(Intent.CATEGORY_DEFAULT);
3642        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3643        List<ResolveInfo> matches = null;
3644        for (String action : orderedActions) {
3645            intent.setAction(action);
3646            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3647                    resolveFlags, UserHandle.USER_SYSTEM);
3648            if (matches.isEmpty()) {
3649                if (DEBUG_INSTANT) {
3650                    Slog.d(TAG, "Instant App installer not found with " + action);
3651                }
3652            } else {
3653                break;
3654            }
3655        }
3656        Iterator<ResolveInfo> iter = matches.iterator();
3657        while (iter.hasNext()) {
3658            final ResolveInfo rInfo = iter.next();
3659            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3660            if (ps != null) {
3661                final PermissionsState permissionsState = ps.getPermissionsState();
3662                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3663                        || Build.IS_ENG) {
3664                    continue;
3665                }
3666            }
3667            iter.remove();
3668        }
3669        if (matches.size() == 0) {
3670            return null;
3671        } else if (matches.size() == 1) {
3672            return (ActivityInfo) matches.get(0).getComponentInfo();
3673        } else {
3674            throw new RuntimeException(
3675                    "There must be at most one ephemeral installer; found " + matches);
3676        }
3677    }
3678
3679    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3680            @NonNull ComponentName resolver) {
3681        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3682                .addCategory(Intent.CATEGORY_DEFAULT)
3683                .setPackage(resolver.getPackageName());
3684        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3685        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3686                UserHandle.USER_SYSTEM);
3687        if (matches.isEmpty()) {
3688            return null;
3689        }
3690        return matches.get(0).getComponentInfo().getComponentName();
3691    }
3692
3693    private void primeDomainVerificationsLPw(int userId) {
3694        if (DEBUG_DOMAIN_VERIFICATION) {
3695            Slog.d(TAG, "Priming domain verifications in user " + userId);
3696        }
3697
3698        SystemConfig systemConfig = SystemConfig.getInstance();
3699        ArraySet<String> packages = systemConfig.getLinkedApps();
3700
3701        for (String packageName : packages) {
3702            PackageParser.Package pkg = mPackages.get(packageName);
3703            if (pkg != null) {
3704                if (!pkg.isSystem()) {
3705                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3706                    continue;
3707                }
3708
3709                ArraySet<String> domains = null;
3710                for (PackageParser.Activity a : pkg.activities) {
3711                    for (ActivityIntentInfo filter : a.intents) {
3712                        if (hasValidDomains(filter)) {
3713                            if (domains == null) {
3714                                domains = new ArraySet<String>();
3715                            }
3716                            domains.addAll(filter.getHostsList());
3717                        }
3718                    }
3719                }
3720
3721                if (domains != null && domains.size() > 0) {
3722                    if (DEBUG_DOMAIN_VERIFICATION) {
3723                        Slog.v(TAG, "      + " + packageName);
3724                    }
3725                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3726                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3727                    // and then 'always' in the per-user state actually used for intent resolution.
3728                    final IntentFilterVerificationInfo ivi;
3729                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3730                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3731                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3732                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3733                } else {
3734                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3735                            + "' does not handle web links");
3736                }
3737            } else {
3738                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3739            }
3740        }
3741
3742        scheduleWritePackageRestrictionsLocked(userId);
3743        scheduleWriteSettingsLocked();
3744    }
3745
3746    private void applyFactoryDefaultBrowserLPw(int userId) {
3747        // The default browser app's package name is stored in a string resource,
3748        // with a product-specific overlay used for vendor customization.
3749        String browserPkg = mContext.getResources().getString(
3750                com.android.internal.R.string.default_browser);
3751        if (!TextUtils.isEmpty(browserPkg)) {
3752            // non-empty string => required to be a known package
3753            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3754            if (ps == null) {
3755                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3756                browserPkg = null;
3757            } else {
3758                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3759            }
3760        }
3761
3762        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3763        // default.  If there's more than one, just leave everything alone.
3764        if (browserPkg == null) {
3765            calculateDefaultBrowserLPw(userId);
3766        }
3767    }
3768
3769    private void calculateDefaultBrowserLPw(int userId) {
3770        List<String> allBrowsers = resolveAllBrowserApps(userId);
3771        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3772        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3773    }
3774
3775    private List<String> resolveAllBrowserApps(int userId) {
3776        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3777        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3778                PackageManager.MATCH_ALL, userId);
3779
3780        final int count = list.size();
3781        List<String> result = new ArrayList<String>(count);
3782        for (int i=0; i<count; i++) {
3783            ResolveInfo info = list.get(i);
3784            if (info.activityInfo == null
3785                    || !info.handleAllWebDataURI
3786                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3787                    || result.contains(info.activityInfo.packageName)) {
3788                continue;
3789            }
3790            result.add(info.activityInfo.packageName);
3791        }
3792
3793        return result;
3794    }
3795
3796    private boolean packageIsBrowser(String packageName, int userId) {
3797        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3798                PackageManager.MATCH_ALL, userId);
3799        final int N = list.size();
3800        for (int i = 0; i < N; i++) {
3801            ResolveInfo info = list.get(i);
3802            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3803                return true;
3804            }
3805        }
3806        return false;
3807    }
3808
3809    private void checkDefaultBrowser() {
3810        final int myUserId = UserHandle.myUserId();
3811        final String packageName = getDefaultBrowserPackageName(myUserId);
3812        if (packageName != null) {
3813            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3814            if (info == null) {
3815                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3816                synchronized (mPackages) {
3817                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3818                }
3819            }
3820        }
3821    }
3822
3823    @Override
3824    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3825            throws RemoteException {
3826        try {
3827            return super.onTransact(code, data, reply, flags);
3828        } catch (RuntimeException e) {
3829            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3830                Slog.wtf(TAG, "Package Manager Crash", e);
3831            }
3832            throw e;
3833        }
3834    }
3835
3836    static int[] appendInts(int[] cur, int[] add) {
3837        if (add == null) return cur;
3838        if (cur == null) return add;
3839        final int N = add.length;
3840        for (int i=0; i<N; i++) {
3841            cur = appendInt(cur, add[i]);
3842        }
3843        return cur;
3844    }
3845
3846    /**
3847     * Returns whether or not a full application can see an instant application.
3848     * <p>
3849     * Currently, there are three cases in which this can occur:
3850     * <ol>
3851     * <li>The calling application is a "special" process. Special processes
3852     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3853     * <li>The calling application has the permission
3854     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3855     * <li>The calling application is the default launcher on the
3856     *     system partition.</li>
3857     * </ol>
3858     */
3859    private boolean canViewInstantApps(int callingUid, int userId) {
3860        if (callingUid < Process.FIRST_APPLICATION_UID) {
3861            return true;
3862        }
3863        if (mContext.checkCallingOrSelfPermission(
3864                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3865            return true;
3866        }
3867        if (mContext.checkCallingOrSelfPermission(
3868                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3869            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3870            if (homeComponent != null
3871                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3872                return true;
3873            }
3874        }
3875        return false;
3876    }
3877
3878    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3879        if (!sUserManager.exists(userId)) return null;
3880        if (ps == null) {
3881            return null;
3882        }
3883        final int callingUid = Binder.getCallingUid();
3884        // Filter out ephemeral app metadata:
3885        //   * The system/shell/root can see metadata for any app
3886        //   * An installed app can see metadata for 1) other installed apps
3887        //     and 2) ephemeral apps that have explicitly interacted with it
3888        //   * Ephemeral apps can only see their own data and exposed installed apps
3889        //   * Holding a signature permission allows seeing instant apps
3890        if (filterAppAccessLPr(ps, callingUid, userId)) {
3891            return null;
3892        }
3893
3894        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3895                && ps.isSystem()) {
3896            flags |= MATCH_ANY_USER;
3897        }
3898
3899        final PackageUserState state = ps.readUserState(userId);
3900        PackageParser.Package p = ps.pkg;
3901        if (p != null) {
3902            final PermissionsState permissionsState = ps.getPermissionsState();
3903
3904            // Compute GIDs only if requested
3905            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3906                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3907            // Compute granted permissions only if package has requested permissions
3908            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3909                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3910
3911            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3912                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3913
3914            if (packageInfo == null) {
3915                return null;
3916            }
3917
3918            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3919                    resolveExternalPackageNameLPr(p);
3920
3921            return packageInfo;
3922        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3923            PackageInfo pi = new PackageInfo();
3924            pi.packageName = ps.name;
3925            pi.setLongVersionCode(ps.versionCode);
3926            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3927            pi.firstInstallTime = ps.firstInstallTime;
3928            pi.lastUpdateTime = ps.lastUpdateTime;
3929
3930            ApplicationInfo ai = new ApplicationInfo();
3931            ai.packageName = ps.name;
3932            ai.uid = UserHandle.getUid(userId, ps.appId);
3933            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3934            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3935            ai.versionCode = ps.versionCode;
3936            ai.flags = ps.pkgFlags;
3937            ai.privateFlags = ps.pkgPrivateFlags;
3938            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3939
3940            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3941                    + ps.name + "]. Provides a minimum info.");
3942            return pi;
3943        } else {
3944            return null;
3945        }
3946    }
3947
3948    @Override
3949    public void checkPackageStartable(String packageName, int userId) {
3950        final int callingUid = Binder.getCallingUid();
3951        if (getInstantAppPackageName(callingUid) != null) {
3952            throw new SecurityException("Instant applications don't have access to this method");
3953        }
3954        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3955        synchronized (mPackages) {
3956            final PackageSetting ps = mSettings.mPackages.get(packageName);
3957            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3958                throw new SecurityException("Package " + packageName + " was not found!");
3959            }
3960
3961            if (!ps.getInstalled(userId)) {
3962                throw new SecurityException(
3963                        "Package " + packageName + " was not installed for user " + userId + "!");
3964            }
3965
3966            if (mSafeMode && !ps.isSystem()) {
3967                throw new SecurityException("Package " + packageName + " not a system app!");
3968            }
3969
3970            if (mFrozenPackages.contains(packageName)) {
3971                throw new SecurityException("Package " + packageName + " is currently frozen!");
3972            }
3973
3974            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3975                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3976            }
3977        }
3978    }
3979
3980    @Override
3981    public boolean isPackageAvailable(String packageName, int userId) {
3982        if (!sUserManager.exists(userId)) return false;
3983        final int callingUid = Binder.getCallingUid();
3984        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3985                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3986        synchronized (mPackages) {
3987            PackageParser.Package p = mPackages.get(packageName);
3988            if (p != null) {
3989                final PackageSetting ps = (PackageSetting) p.mExtras;
3990                if (filterAppAccessLPr(ps, callingUid, userId)) {
3991                    return false;
3992                }
3993                if (ps != null) {
3994                    final PackageUserState state = ps.readUserState(userId);
3995                    if (state != null) {
3996                        return PackageParser.isAvailable(state);
3997                    }
3998                }
3999            }
4000        }
4001        return false;
4002    }
4003
4004    @Override
4005    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4006        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4007                flags, Binder.getCallingUid(), userId);
4008    }
4009
4010    @Override
4011    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4012            int flags, int userId) {
4013        return getPackageInfoInternal(versionedPackage.getPackageName(),
4014                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4015    }
4016
4017    /**
4018     * Important: The provided filterCallingUid is used exclusively to filter out packages
4019     * that can be seen based on user state. It's typically the original caller uid prior
4020     * to clearing. Because it can only be provided by trusted code, it's value can be
4021     * trusted and will be used as-is; unlike userId which will be validated by this method.
4022     */
4023    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4024            int flags, int filterCallingUid, int userId) {
4025        if (!sUserManager.exists(userId)) return null;
4026        flags = updateFlagsForPackage(flags, userId, packageName);
4027        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4028                false /* requireFullPermission */, false /* checkShell */, "get package info");
4029
4030        // reader
4031        synchronized (mPackages) {
4032            // Normalize package name to handle renamed packages and static libs
4033            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4034
4035            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4036            if (matchFactoryOnly) {
4037                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4038                if (ps != null) {
4039                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4040                        return null;
4041                    }
4042                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4043                        return null;
4044                    }
4045                    return generatePackageInfo(ps, flags, userId);
4046                }
4047            }
4048
4049            PackageParser.Package p = mPackages.get(packageName);
4050            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4051                return null;
4052            }
4053            if (DEBUG_PACKAGE_INFO)
4054                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4055            if (p != null) {
4056                final PackageSetting ps = (PackageSetting) p.mExtras;
4057                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4058                    return null;
4059                }
4060                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4061                    return null;
4062                }
4063                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4064            }
4065            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4066                final PackageSetting ps = mSettings.mPackages.get(packageName);
4067                if (ps == null) return null;
4068                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4069                    return null;
4070                }
4071                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4072                    return null;
4073                }
4074                return generatePackageInfo(ps, flags, userId);
4075            }
4076        }
4077        return null;
4078    }
4079
4080    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4081        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4082            return true;
4083        }
4084        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4085            return true;
4086        }
4087        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4088            return true;
4089        }
4090        return false;
4091    }
4092
4093    private boolean isComponentVisibleToInstantApp(
4094            @Nullable ComponentName component, @ComponentType int type) {
4095        if (type == TYPE_ACTIVITY) {
4096            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4097            if (activity == null) {
4098                return false;
4099            }
4100            final boolean visibleToInstantApp =
4101                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4102            final boolean explicitlyVisibleToInstantApp =
4103                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4104            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4105        } else if (type == TYPE_RECEIVER) {
4106            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4107            if (activity == null) {
4108                return false;
4109            }
4110            final boolean visibleToInstantApp =
4111                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4112            final boolean explicitlyVisibleToInstantApp =
4113                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4114            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4115        } else if (type == TYPE_SERVICE) {
4116            final PackageParser.Service service = mServices.mServices.get(component);
4117            return service != null
4118                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4119                    : false;
4120        } else if (type == TYPE_PROVIDER) {
4121            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4122            return provider != null
4123                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4124                    : false;
4125        } else if (type == TYPE_UNKNOWN) {
4126            return isComponentVisibleToInstantApp(component);
4127        }
4128        return false;
4129    }
4130
4131    /**
4132     * Returns whether or not access to the application should be filtered.
4133     * <p>
4134     * Access may be limited based upon whether the calling or target applications
4135     * are instant applications.
4136     *
4137     * @see #canAccessInstantApps(int)
4138     */
4139    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4140            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4141        // if we're in an isolated process, get the real calling UID
4142        if (Process.isIsolated(callingUid)) {
4143            callingUid = mIsolatedOwners.get(callingUid);
4144        }
4145        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4146        final boolean callerIsInstantApp = instantAppPkgName != null;
4147        if (ps == null) {
4148            if (callerIsInstantApp) {
4149                // pretend the application exists, but, needs to be filtered
4150                return true;
4151            }
4152            return false;
4153        }
4154        // if the target and caller are the same application, don't filter
4155        if (isCallerSameApp(ps.name, callingUid)) {
4156            return false;
4157        }
4158        if (callerIsInstantApp) {
4159            // both caller and target are both instant, but, different applications, filter
4160            if (ps.getInstantApp(userId)) {
4161                return true;
4162            }
4163            // request for a specific component; if it hasn't been explicitly exposed through
4164            // property or instrumentation target, filter
4165            if (component != null) {
4166                final PackageParser.Instrumentation instrumentation =
4167                        mInstrumentation.get(component);
4168                if (instrumentation != null
4169                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4170                    return false;
4171                }
4172                return !isComponentVisibleToInstantApp(component, componentType);
4173            }
4174            // request for application; if no components have been explicitly exposed, filter
4175            return !ps.pkg.visibleToInstantApps;
4176        }
4177        if (ps.getInstantApp(userId)) {
4178            // caller can see all components of all instant applications, don't filter
4179            if (canViewInstantApps(callingUid, userId)) {
4180                return false;
4181            }
4182            // request for a specific instant application component, filter
4183            if (component != null) {
4184                return true;
4185            }
4186            // request for an instant application; if the caller hasn't been granted access, filter
4187            return !mInstantAppRegistry.isInstantAccessGranted(
4188                    userId, UserHandle.getAppId(callingUid), ps.appId);
4189        }
4190        return false;
4191    }
4192
4193    /**
4194     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4195     */
4196    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4197        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4198    }
4199
4200    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4201            int flags) {
4202        // Callers can access only the libs they depend on, otherwise they need to explicitly
4203        // ask for the shared libraries given the caller is allowed to access all static libs.
4204        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4205            // System/shell/root get to see all static libs
4206            final int appId = UserHandle.getAppId(uid);
4207            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4208                    || appId == Process.ROOT_UID) {
4209                return false;
4210            }
4211        }
4212
4213        // No package means no static lib as it is always on internal storage
4214        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4215            return false;
4216        }
4217
4218        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4219                ps.pkg.staticSharedLibVersion);
4220        if (libEntry == null) {
4221            return false;
4222        }
4223
4224        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4225        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4226        if (uidPackageNames == null) {
4227            return true;
4228        }
4229
4230        for (String uidPackageName : uidPackageNames) {
4231            if (ps.name.equals(uidPackageName)) {
4232                return false;
4233            }
4234            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4235            if (uidPs != null) {
4236                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4237                        libEntry.info.getName());
4238                if (index < 0) {
4239                    continue;
4240                }
4241                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4242                    return false;
4243                }
4244            }
4245        }
4246        return true;
4247    }
4248
4249    @Override
4250    public String[] currentToCanonicalPackageNames(String[] names) {
4251        final int callingUid = Binder.getCallingUid();
4252        if (getInstantAppPackageName(callingUid) != null) {
4253            return names;
4254        }
4255        final String[] out = new String[names.length];
4256        // reader
4257        synchronized (mPackages) {
4258            final int callingUserId = UserHandle.getUserId(callingUid);
4259            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4260            for (int i=names.length-1; i>=0; i--) {
4261                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4262                boolean translateName = false;
4263                if (ps != null && ps.realName != null) {
4264                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4265                    translateName = !targetIsInstantApp
4266                            || canViewInstantApps
4267                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4268                                    UserHandle.getAppId(callingUid), ps.appId);
4269                }
4270                out[i] = translateName ? ps.realName : names[i];
4271            }
4272        }
4273        return out;
4274    }
4275
4276    @Override
4277    public String[] canonicalToCurrentPackageNames(String[] names) {
4278        final int callingUid = Binder.getCallingUid();
4279        if (getInstantAppPackageName(callingUid) != null) {
4280            return names;
4281        }
4282        final String[] out = new String[names.length];
4283        // reader
4284        synchronized (mPackages) {
4285            final int callingUserId = UserHandle.getUserId(callingUid);
4286            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4287            for (int i=names.length-1; i>=0; i--) {
4288                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4289                boolean translateName = false;
4290                if (cur != null) {
4291                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4292                    final boolean targetIsInstantApp =
4293                            ps != null && ps.getInstantApp(callingUserId);
4294                    translateName = !targetIsInstantApp
4295                            || canViewInstantApps
4296                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4297                                    UserHandle.getAppId(callingUid), ps.appId);
4298                }
4299                out[i] = translateName ? cur : names[i];
4300            }
4301        }
4302        return out;
4303    }
4304
4305    @Override
4306    public int getPackageUid(String packageName, int flags, int userId) {
4307        if (!sUserManager.exists(userId)) return -1;
4308        final int callingUid = Binder.getCallingUid();
4309        flags = updateFlagsForPackage(flags, userId, packageName);
4310        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4311                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4312
4313        // reader
4314        synchronized (mPackages) {
4315            final PackageParser.Package p = mPackages.get(packageName);
4316            if (p != null && p.isMatch(flags)) {
4317                PackageSetting ps = (PackageSetting) p.mExtras;
4318                if (filterAppAccessLPr(ps, callingUid, userId)) {
4319                    return -1;
4320                }
4321                return UserHandle.getUid(userId, p.applicationInfo.uid);
4322            }
4323            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4324                final PackageSetting ps = mSettings.mPackages.get(packageName);
4325                if (ps != null && ps.isMatch(flags)
4326                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4327                    return UserHandle.getUid(userId, ps.appId);
4328                }
4329            }
4330        }
4331
4332        return -1;
4333    }
4334
4335    @Override
4336    public int[] getPackageGids(String packageName, int flags, int userId) {
4337        if (!sUserManager.exists(userId)) return null;
4338        final int callingUid = Binder.getCallingUid();
4339        flags = updateFlagsForPackage(flags, userId, packageName);
4340        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4341                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4342
4343        // reader
4344        synchronized (mPackages) {
4345            final PackageParser.Package p = mPackages.get(packageName);
4346            if (p != null && p.isMatch(flags)) {
4347                PackageSetting ps = (PackageSetting) p.mExtras;
4348                if (filterAppAccessLPr(ps, callingUid, userId)) {
4349                    return null;
4350                }
4351                // TODO: Shouldn't this be checking for package installed state for userId and
4352                // return null?
4353                return ps.getPermissionsState().computeGids(userId);
4354            }
4355            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4356                final PackageSetting ps = mSettings.mPackages.get(packageName);
4357                if (ps != null && ps.isMatch(flags)
4358                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4359                    return ps.getPermissionsState().computeGids(userId);
4360                }
4361            }
4362        }
4363
4364        return null;
4365    }
4366
4367    @Override
4368    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4369        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4370    }
4371
4372    @Override
4373    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4374            int flags) {
4375        final List<PermissionInfo> permissionList =
4376                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4377        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4378    }
4379
4380    @Override
4381    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4382        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4383    }
4384
4385    @Override
4386    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4387        final List<PermissionGroupInfo> permissionList =
4388                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4389        return (permissionList == null)
4390                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4391    }
4392
4393    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4394            int filterCallingUid, int userId) {
4395        if (!sUserManager.exists(userId)) return null;
4396        PackageSetting ps = mSettings.mPackages.get(packageName);
4397        if (ps != null) {
4398            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4399                return null;
4400            }
4401            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4402                return null;
4403            }
4404            if (ps.pkg == null) {
4405                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4406                if (pInfo != null) {
4407                    return pInfo.applicationInfo;
4408                }
4409                return null;
4410            }
4411            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4412                    ps.readUserState(userId), userId);
4413            if (ai != null) {
4414                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4415            }
4416            return ai;
4417        }
4418        return null;
4419    }
4420
4421    @Override
4422    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4423        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4424    }
4425
4426    /**
4427     * Important: The provided filterCallingUid is used exclusively to filter out applications
4428     * that can be seen based on user state. It's typically the original caller uid prior
4429     * to clearing. Because it can only be provided by trusted code, it's value can be
4430     * trusted and will be used as-is; unlike userId which will be validated by this method.
4431     */
4432    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4433            int filterCallingUid, int userId) {
4434        if (!sUserManager.exists(userId)) return null;
4435        flags = updateFlagsForApplication(flags, userId, packageName);
4436        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4437                false /* requireFullPermission */, false /* checkShell */, "get application info");
4438
4439        // writer
4440        synchronized (mPackages) {
4441            // Normalize package name to handle renamed packages and static libs
4442            packageName = resolveInternalPackageNameLPr(packageName,
4443                    PackageManager.VERSION_CODE_HIGHEST);
4444
4445            PackageParser.Package p = mPackages.get(packageName);
4446            if (DEBUG_PACKAGE_INFO) Log.v(
4447                    TAG, "getApplicationInfo " + packageName
4448                    + ": " + p);
4449            if (p != null) {
4450                PackageSetting ps = mSettings.mPackages.get(packageName);
4451                if (ps == null) return null;
4452                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4453                    return null;
4454                }
4455                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4456                    return null;
4457                }
4458                // Note: isEnabledLP() does not apply here - always return info
4459                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4460                        p, flags, ps.readUserState(userId), userId);
4461                if (ai != null) {
4462                    ai.packageName = resolveExternalPackageNameLPr(p);
4463                }
4464                return ai;
4465            }
4466            if ("android".equals(packageName)||"system".equals(packageName)) {
4467                return mAndroidApplication;
4468            }
4469            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4470                // Already generates the external package name
4471                return generateApplicationInfoFromSettingsLPw(packageName,
4472                        flags, filterCallingUid, userId);
4473            }
4474        }
4475        return null;
4476    }
4477
4478    private String normalizePackageNameLPr(String packageName) {
4479        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4480        return normalizedPackageName != null ? normalizedPackageName : packageName;
4481    }
4482
4483    @Override
4484    public void deletePreloadsFileCache() {
4485        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4486            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4487        }
4488        File dir = Environment.getDataPreloadsFileCacheDirectory();
4489        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4490        FileUtils.deleteContents(dir);
4491    }
4492
4493    @Override
4494    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4495            final int storageFlags, final IPackageDataObserver observer) {
4496        mContext.enforceCallingOrSelfPermission(
4497                android.Manifest.permission.CLEAR_APP_CACHE, null);
4498        mHandler.post(() -> {
4499            boolean success = false;
4500            try {
4501                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4502                success = true;
4503            } catch (IOException e) {
4504                Slog.w(TAG, e);
4505            }
4506            if (observer != null) {
4507                try {
4508                    observer.onRemoveCompleted(null, success);
4509                } catch (RemoteException e) {
4510                    Slog.w(TAG, e);
4511                }
4512            }
4513        });
4514    }
4515
4516    @Override
4517    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4518            final int storageFlags, final IntentSender pi) {
4519        mContext.enforceCallingOrSelfPermission(
4520                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4521        mHandler.post(() -> {
4522            boolean success = false;
4523            try {
4524                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4525                success = true;
4526            } catch (IOException e) {
4527                Slog.w(TAG, e);
4528            }
4529            if (pi != null) {
4530                try {
4531                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4532                } catch (SendIntentException e) {
4533                    Slog.w(TAG, e);
4534                }
4535            }
4536        });
4537    }
4538
4539    /**
4540     * Blocking call to clear various types of cached data across the system
4541     * until the requested bytes are available.
4542     */
4543    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4544        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4545        final File file = storage.findPathForUuid(volumeUuid);
4546        if (file.getUsableSpace() >= bytes) return;
4547
4548        if (ENABLE_FREE_CACHE_V2) {
4549            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4550                    volumeUuid);
4551            final boolean aggressive = (storageFlags
4552                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4553            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4554
4555            // 1. Pre-flight to determine if we have any chance to succeed
4556            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4557            if (internalVolume && (aggressive || SystemProperties
4558                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4559                deletePreloadsFileCache();
4560                if (file.getUsableSpace() >= bytes) return;
4561            }
4562
4563            // 3. Consider parsed APK data (aggressive only)
4564            if (internalVolume && aggressive) {
4565                FileUtils.deleteContents(mCacheDir);
4566                if (file.getUsableSpace() >= bytes) return;
4567            }
4568
4569            // 4. Consider cached app data (above quotas)
4570            try {
4571                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4572                        Installer.FLAG_FREE_CACHE_V2);
4573            } catch (InstallerException ignored) {
4574            }
4575            if (file.getUsableSpace() >= bytes) return;
4576
4577            // 5. Consider shared libraries with refcount=0 and age>min cache period
4578            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4579                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4580                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4581                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4582                return;
4583            }
4584
4585            // 6. Consider dexopt output (aggressive only)
4586            // TODO: Implement
4587
4588            // 7. Consider installed instant apps unused longer than min cache period
4589            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4590                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4591                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4592                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4593                return;
4594            }
4595
4596            // 8. Consider cached app data (below quotas)
4597            try {
4598                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4599                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4600            } catch (InstallerException ignored) {
4601            }
4602            if (file.getUsableSpace() >= bytes) return;
4603
4604            // 9. Consider DropBox entries
4605            // TODO: Implement
4606
4607            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4608            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4609                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4610                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4611                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4612                return;
4613            }
4614        } else {
4615            try {
4616                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4617            } catch (InstallerException ignored) {
4618            }
4619            if (file.getUsableSpace() >= bytes) return;
4620        }
4621
4622        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4623    }
4624
4625    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4626            throws IOException {
4627        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4628        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4629
4630        List<VersionedPackage> packagesToDelete = null;
4631        final long now = System.currentTimeMillis();
4632
4633        synchronized (mPackages) {
4634            final int[] allUsers = sUserManager.getUserIds();
4635            final int libCount = mSharedLibraries.size();
4636            for (int i = 0; i < libCount; i++) {
4637                final LongSparseArray<SharedLibraryEntry> versionedLib
4638                        = mSharedLibraries.valueAt(i);
4639                if (versionedLib == null) {
4640                    continue;
4641                }
4642                final int versionCount = versionedLib.size();
4643                for (int j = 0; j < versionCount; j++) {
4644                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4645                    // Skip packages that are not static shared libs.
4646                    if (!libInfo.isStatic()) {
4647                        break;
4648                    }
4649                    // Important: We skip static shared libs used for some user since
4650                    // in such a case we need to keep the APK on the device. The check for
4651                    // a lib being used for any user is performed by the uninstall call.
4652                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4653                    // Resolve the package name - we use synthetic package names internally
4654                    final String internalPackageName = resolveInternalPackageNameLPr(
4655                            declaringPackage.getPackageName(),
4656                            declaringPackage.getLongVersionCode());
4657                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4658                    // Skip unused static shared libs cached less than the min period
4659                    // to prevent pruning a lib needed by a subsequently installed package.
4660                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4661                        continue;
4662                    }
4663                    if (packagesToDelete == null) {
4664                        packagesToDelete = new ArrayList<>();
4665                    }
4666                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4667                            declaringPackage.getLongVersionCode()));
4668                }
4669            }
4670        }
4671
4672        if (packagesToDelete != null) {
4673            final int packageCount = packagesToDelete.size();
4674            for (int i = 0; i < packageCount; i++) {
4675                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4676                // Delete the package synchronously (will fail of the lib used for any user).
4677                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4678                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4679                                == PackageManager.DELETE_SUCCEEDED) {
4680                    if (volume.getUsableSpace() >= neededSpace) {
4681                        return true;
4682                    }
4683                }
4684            }
4685        }
4686
4687        return false;
4688    }
4689
4690    /**
4691     * Update given flags based on encryption status of current user.
4692     */
4693    private int updateFlags(int flags, int userId) {
4694        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4695                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4696            // Caller expressed an explicit opinion about what encryption
4697            // aware/unaware components they want to see, so fall through and
4698            // give them what they want
4699        } else {
4700            // Caller expressed no opinion, so match based on user state
4701            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4702                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4703            } else {
4704                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4705            }
4706        }
4707        return flags;
4708    }
4709
4710    private UserManagerInternal getUserManagerInternal() {
4711        if (mUserManagerInternal == null) {
4712            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4713        }
4714        return mUserManagerInternal;
4715    }
4716
4717    private ActivityManagerInternal getActivityManagerInternal() {
4718        if (mActivityManagerInternal == null) {
4719            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4720        }
4721        return mActivityManagerInternal;
4722    }
4723
4724
4725    private DeviceIdleController.LocalService getDeviceIdleController() {
4726        if (mDeviceIdleController == null) {
4727            mDeviceIdleController =
4728                    LocalServices.getService(DeviceIdleController.LocalService.class);
4729        }
4730        return mDeviceIdleController;
4731    }
4732
4733    /**
4734     * Update given flags when being used to request {@link PackageInfo}.
4735     */
4736    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4737        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4738        boolean triaged = true;
4739        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4740                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4741            // Caller is asking for component details, so they'd better be
4742            // asking for specific encryption matching behavior, or be triaged
4743            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4744                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4745                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4746                triaged = false;
4747            }
4748        }
4749        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4750                | PackageManager.MATCH_SYSTEM_ONLY
4751                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4752            triaged = false;
4753        }
4754        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4755            mPermissionManager.enforceCrossUserPermission(
4756                    Binder.getCallingUid(), userId, false, false,
4757                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4758                    + Debug.getCallers(5));
4759        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4760                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4761            // If the caller wants all packages and has a restricted profile associated with it,
4762            // then match all users. This is to make sure that launchers that need to access work
4763            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4764            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4765            flags |= PackageManager.MATCH_ANY_USER;
4766        }
4767        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4768            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4769                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4770        }
4771        return updateFlags(flags, userId);
4772    }
4773
4774    /**
4775     * Update given flags when being used to request {@link ApplicationInfo}.
4776     */
4777    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4778        return updateFlagsForPackage(flags, userId, cookie);
4779    }
4780
4781    /**
4782     * Update given flags when being used to request {@link ComponentInfo}.
4783     */
4784    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4785        if (cookie instanceof Intent) {
4786            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4787                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4788            }
4789        }
4790
4791        boolean triaged = true;
4792        // Caller is asking for component details, so they'd better be
4793        // asking for specific encryption matching behavior, or be triaged
4794        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4795                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4796                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4797            triaged = false;
4798        }
4799        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4800            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4801                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4802        }
4803
4804        return updateFlags(flags, userId);
4805    }
4806
4807    /**
4808     * Update given intent when being used to request {@link ResolveInfo}.
4809     */
4810    private Intent updateIntentForResolve(Intent intent) {
4811        if (intent.getSelector() != null) {
4812            intent = intent.getSelector();
4813        }
4814        if (DEBUG_PREFERRED) {
4815            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4816        }
4817        return intent;
4818    }
4819
4820    /**
4821     * Update given flags when being used to request {@link ResolveInfo}.
4822     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4823     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4824     * flag set. However, this flag is only honoured in three circumstances:
4825     * <ul>
4826     * <li>when called from a system process</li>
4827     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4828     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4829     * action and a {@code android.intent.category.BROWSABLE} category</li>
4830     * </ul>
4831     */
4832    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4833        return updateFlagsForResolve(flags, userId, intent, callingUid,
4834                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4835    }
4836    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4837            boolean wantInstantApps) {
4838        return updateFlagsForResolve(flags, userId, intent, callingUid,
4839                wantInstantApps, false /*onlyExposedExplicitly*/);
4840    }
4841    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4842            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4843        // Safe mode means we shouldn't match any third-party components
4844        if (mSafeMode) {
4845            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4846        }
4847        if (getInstantAppPackageName(callingUid) != null) {
4848            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4849            if (onlyExposedExplicitly) {
4850                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4851            }
4852            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4853            flags |= PackageManager.MATCH_INSTANT;
4854        } else {
4855            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4856            final boolean allowMatchInstant = wantInstantApps
4857                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4858            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4859                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4860            if (!allowMatchInstant) {
4861                flags &= ~PackageManager.MATCH_INSTANT;
4862            }
4863        }
4864        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4865    }
4866
4867    @Override
4868    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4869        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4870    }
4871
4872    /**
4873     * Important: The provided filterCallingUid is used exclusively to filter out activities
4874     * that can be seen based on user state. It's typically the original caller uid prior
4875     * to clearing. Because it can only be provided by trusted code, it's value can be
4876     * trusted and will be used as-is; unlike userId which will be validated by this method.
4877     */
4878    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4879            int filterCallingUid, int userId) {
4880        if (!sUserManager.exists(userId)) return null;
4881        flags = updateFlagsForComponent(flags, userId, component);
4882
4883        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4884            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4885                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4886        }
4887
4888        synchronized (mPackages) {
4889            PackageParser.Activity a = mActivities.mActivities.get(component);
4890
4891            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4892            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4893                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4894                if (ps == null) return null;
4895                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4896                    return null;
4897                }
4898                return PackageParser.generateActivityInfo(
4899                        a, flags, ps.readUserState(userId), userId);
4900            }
4901            if (mResolveComponentName.equals(component)) {
4902                return PackageParser.generateActivityInfo(
4903                        mResolveActivity, flags, new PackageUserState(), userId);
4904            }
4905        }
4906        return null;
4907    }
4908
4909    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4910        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4911            return false;
4912        }
4913        final long token = Binder.clearCallingIdentity();
4914        try {
4915            final int callingUserId = UserHandle.getUserId(callingUid);
4916            if (ActivityManager.getCurrentUser() != callingUserId) {
4917                return false;
4918            }
4919            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4920        } finally {
4921            Binder.restoreCallingIdentity(token);
4922        }
4923    }
4924
4925    @Override
4926    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4927            String resolvedType) {
4928        synchronized (mPackages) {
4929            if (component.equals(mResolveComponentName)) {
4930                // The resolver supports EVERYTHING!
4931                return true;
4932            }
4933            final int callingUid = Binder.getCallingUid();
4934            final int callingUserId = UserHandle.getUserId(callingUid);
4935            PackageParser.Activity a = mActivities.mActivities.get(component);
4936            if (a == null) {
4937                return false;
4938            }
4939            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4940            if (ps == null) {
4941                return false;
4942            }
4943            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4944                return false;
4945            }
4946            for (int i=0; i<a.intents.size(); i++) {
4947                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4948                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4949                    return true;
4950                }
4951            }
4952            return false;
4953        }
4954    }
4955
4956    @Override
4957    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4958        if (!sUserManager.exists(userId)) return null;
4959        final int callingUid = Binder.getCallingUid();
4960        flags = updateFlagsForComponent(flags, userId, component);
4961        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4962                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4963        synchronized (mPackages) {
4964            PackageParser.Activity a = mReceivers.mActivities.get(component);
4965            if (DEBUG_PACKAGE_INFO) Log.v(
4966                TAG, "getReceiverInfo " + component + ": " + a);
4967            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4968                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4969                if (ps == null) return null;
4970                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4971                    return null;
4972                }
4973                return PackageParser.generateActivityInfo(
4974                        a, flags, ps.readUserState(userId), userId);
4975            }
4976        }
4977        return null;
4978    }
4979
4980    @Override
4981    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4982            int flags, int userId) {
4983        if (!sUserManager.exists(userId)) return null;
4984        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4985        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4986            return null;
4987        }
4988
4989        flags = updateFlagsForPackage(flags, userId, null);
4990
4991        final boolean canSeeStaticLibraries =
4992                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4993                        == PERMISSION_GRANTED
4994                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4995                        == PERMISSION_GRANTED
4996                || canRequestPackageInstallsInternal(packageName,
4997                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4998                        false  /* throwIfPermNotDeclared*/)
4999                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5000                        == PERMISSION_GRANTED;
5001
5002        synchronized (mPackages) {
5003            List<SharedLibraryInfo> result = null;
5004
5005            final int libCount = mSharedLibraries.size();
5006            for (int i = 0; i < libCount; i++) {
5007                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5008                if (versionedLib == null) {
5009                    continue;
5010                }
5011
5012                final int versionCount = versionedLib.size();
5013                for (int j = 0; j < versionCount; j++) {
5014                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5015                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5016                        break;
5017                    }
5018                    final long identity = Binder.clearCallingIdentity();
5019                    try {
5020                        PackageInfo packageInfo = getPackageInfoVersioned(
5021                                libInfo.getDeclaringPackage(), flags
5022                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5023                        if (packageInfo == null) {
5024                            continue;
5025                        }
5026                    } finally {
5027                        Binder.restoreCallingIdentity(identity);
5028                    }
5029
5030                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5031                            libInfo.getLongVersion(), libInfo.getType(),
5032                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5033                            flags, userId));
5034
5035                    if (result == null) {
5036                        result = new ArrayList<>();
5037                    }
5038                    result.add(resLibInfo);
5039                }
5040            }
5041
5042            return result != null ? new ParceledListSlice<>(result) : null;
5043        }
5044    }
5045
5046    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5047            SharedLibraryInfo libInfo, int flags, int userId) {
5048        List<VersionedPackage> versionedPackages = null;
5049        final int packageCount = mSettings.mPackages.size();
5050        for (int i = 0; i < packageCount; i++) {
5051            PackageSetting ps = mSettings.mPackages.valueAt(i);
5052
5053            if (ps == null) {
5054                continue;
5055            }
5056
5057            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5058                continue;
5059            }
5060
5061            final String libName = libInfo.getName();
5062            if (libInfo.isStatic()) {
5063                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5064                if (libIdx < 0) {
5065                    continue;
5066                }
5067                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5068                    continue;
5069                }
5070                if (versionedPackages == null) {
5071                    versionedPackages = new ArrayList<>();
5072                }
5073                // If the dependent is a static shared lib, use the public package name
5074                String dependentPackageName = ps.name;
5075                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5076                    dependentPackageName = ps.pkg.manifestPackageName;
5077                }
5078                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5079            } else if (ps.pkg != null) {
5080                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5081                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5082                    if (versionedPackages == null) {
5083                        versionedPackages = new ArrayList<>();
5084                    }
5085                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5086                }
5087            }
5088        }
5089
5090        return versionedPackages;
5091    }
5092
5093    @Override
5094    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5095        if (!sUserManager.exists(userId)) return null;
5096        final int callingUid = Binder.getCallingUid();
5097        flags = updateFlagsForComponent(flags, userId, component);
5098        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5099                false /* requireFullPermission */, false /* checkShell */, "get service info");
5100        synchronized (mPackages) {
5101            PackageParser.Service s = mServices.mServices.get(component);
5102            if (DEBUG_PACKAGE_INFO) Log.v(
5103                TAG, "getServiceInfo " + component + ": " + s);
5104            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5105                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5106                if (ps == null) return null;
5107                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5108                    return null;
5109                }
5110                return PackageParser.generateServiceInfo(
5111                        s, flags, ps.readUserState(userId), userId);
5112            }
5113        }
5114        return null;
5115    }
5116
5117    @Override
5118    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5119        if (!sUserManager.exists(userId)) return null;
5120        final int callingUid = Binder.getCallingUid();
5121        flags = updateFlagsForComponent(flags, userId, component);
5122        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5123                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5124        synchronized (mPackages) {
5125            PackageParser.Provider p = mProviders.mProviders.get(component);
5126            if (DEBUG_PACKAGE_INFO) Log.v(
5127                TAG, "getProviderInfo " + component + ": " + p);
5128            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5129                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5130                if (ps == null) return null;
5131                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5132                    return null;
5133                }
5134                return PackageParser.generateProviderInfo(
5135                        p, flags, ps.readUserState(userId), userId);
5136            }
5137        }
5138        return null;
5139    }
5140
5141    @Override
5142    public String[] getSystemSharedLibraryNames() {
5143        // allow instant applications
5144        synchronized (mPackages) {
5145            Set<String> libs = null;
5146            final int libCount = mSharedLibraries.size();
5147            for (int i = 0; i < libCount; i++) {
5148                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5149                if (versionedLib == null) {
5150                    continue;
5151                }
5152                final int versionCount = versionedLib.size();
5153                for (int j = 0; j < versionCount; j++) {
5154                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5155                    if (!libEntry.info.isStatic()) {
5156                        if (libs == null) {
5157                            libs = new ArraySet<>();
5158                        }
5159                        libs.add(libEntry.info.getName());
5160                        break;
5161                    }
5162                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5163                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5164                            UserHandle.getUserId(Binder.getCallingUid()),
5165                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5166                        if (libs == null) {
5167                            libs = new ArraySet<>();
5168                        }
5169                        libs.add(libEntry.info.getName());
5170                        break;
5171                    }
5172                }
5173            }
5174
5175            if (libs != null) {
5176                String[] libsArray = new String[libs.size()];
5177                libs.toArray(libsArray);
5178                return libsArray;
5179            }
5180
5181            return null;
5182        }
5183    }
5184
5185    @Override
5186    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5187        // allow instant applications
5188        synchronized (mPackages) {
5189            return mServicesSystemSharedLibraryPackageName;
5190        }
5191    }
5192
5193    @Override
5194    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5195        // allow instant applications
5196        synchronized (mPackages) {
5197            return mSharedSystemSharedLibraryPackageName;
5198        }
5199    }
5200
5201    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5202        for (int i = userList.length - 1; i >= 0; --i) {
5203            final int userId = userList[i];
5204            // don't add instant app to the list of updates
5205            if (pkgSetting.getInstantApp(userId)) {
5206                continue;
5207            }
5208            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5209            if (changedPackages == null) {
5210                changedPackages = new SparseArray<>();
5211                mChangedPackages.put(userId, changedPackages);
5212            }
5213            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5214            if (sequenceNumbers == null) {
5215                sequenceNumbers = new HashMap<>();
5216                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5217            }
5218            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5219            if (sequenceNumber != null) {
5220                changedPackages.remove(sequenceNumber);
5221            }
5222            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5223            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5224        }
5225        mChangedPackagesSequenceNumber++;
5226    }
5227
5228    @Override
5229    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5230        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5231            return null;
5232        }
5233        synchronized (mPackages) {
5234            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5235                return null;
5236            }
5237            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5238            if (changedPackages == null) {
5239                return null;
5240            }
5241            final List<String> packageNames =
5242                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5243            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5244                final String packageName = changedPackages.get(i);
5245                if (packageName != null) {
5246                    packageNames.add(packageName);
5247                }
5248            }
5249            return packageNames.isEmpty()
5250                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5251        }
5252    }
5253
5254    @Override
5255    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5256        // allow instant applications
5257        ArrayList<FeatureInfo> res;
5258        synchronized (mAvailableFeatures) {
5259            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5260            res.addAll(mAvailableFeatures.values());
5261        }
5262        final FeatureInfo fi = new FeatureInfo();
5263        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5264                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5265        res.add(fi);
5266
5267        return new ParceledListSlice<>(res);
5268    }
5269
5270    @Override
5271    public boolean hasSystemFeature(String name, int version) {
5272        // allow instant applications
5273        synchronized (mAvailableFeatures) {
5274            final FeatureInfo feat = mAvailableFeatures.get(name);
5275            if (feat == null) {
5276                return false;
5277            } else {
5278                return feat.version >= version;
5279            }
5280        }
5281    }
5282
5283    @Override
5284    public int checkPermission(String permName, String pkgName, int userId) {
5285        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5286    }
5287
5288    @Override
5289    public int checkUidPermission(String permName, int uid) {
5290        synchronized (mPackages) {
5291            final String[] packageNames = getPackagesForUid(uid);
5292            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5293                    ? mPackages.get(packageNames[0])
5294                    : null;
5295            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5296        }
5297    }
5298
5299    @Override
5300    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5301        if (UserHandle.getCallingUserId() != userId) {
5302            mContext.enforceCallingPermission(
5303                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5304                    "isPermissionRevokedByPolicy for user " + userId);
5305        }
5306
5307        if (checkPermission(permission, packageName, userId)
5308                == PackageManager.PERMISSION_GRANTED) {
5309            return false;
5310        }
5311
5312        final int callingUid = Binder.getCallingUid();
5313        if (getInstantAppPackageName(callingUid) != null) {
5314            if (!isCallerSameApp(packageName, callingUid)) {
5315                return false;
5316            }
5317        } else {
5318            if (isInstantApp(packageName, userId)) {
5319                return false;
5320            }
5321        }
5322
5323        final long identity = Binder.clearCallingIdentity();
5324        try {
5325            final int flags = getPermissionFlags(permission, packageName, userId);
5326            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5327        } finally {
5328            Binder.restoreCallingIdentity(identity);
5329        }
5330    }
5331
5332    @Override
5333    public String getPermissionControllerPackageName() {
5334        synchronized (mPackages) {
5335            return mRequiredInstallerPackage;
5336        }
5337    }
5338
5339    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5340        return mPermissionManager.addDynamicPermission(
5341                info, async, getCallingUid(), new PermissionCallback() {
5342                    @Override
5343                    public void onPermissionChanged() {
5344                        if (!async) {
5345                            mSettings.writeLPr();
5346                        } else {
5347                            scheduleWriteSettingsLocked();
5348                        }
5349                    }
5350                });
5351    }
5352
5353    @Override
5354    public boolean addPermission(PermissionInfo info) {
5355        synchronized (mPackages) {
5356            return addDynamicPermission(info, false);
5357        }
5358    }
5359
5360    @Override
5361    public boolean addPermissionAsync(PermissionInfo info) {
5362        synchronized (mPackages) {
5363            return addDynamicPermission(info, true);
5364        }
5365    }
5366
5367    @Override
5368    public void removePermission(String permName) {
5369        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5370    }
5371
5372    @Override
5373    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5374        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5375                getCallingUid(), userId, mPermissionCallback);
5376    }
5377
5378    @Override
5379    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5380        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5381                getCallingUid(), userId, mPermissionCallback);
5382    }
5383
5384    @Override
5385    public void resetRuntimePermissions() {
5386        mContext.enforceCallingOrSelfPermission(
5387                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5388                "revokeRuntimePermission");
5389
5390        int callingUid = Binder.getCallingUid();
5391        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5392            mContext.enforceCallingOrSelfPermission(
5393                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5394                    "resetRuntimePermissions");
5395        }
5396
5397        synchronized (mPackages) {
5398            mPermissionManager.updateAllPermissions(
5399                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5400                    mPermissionCallback);
5401            for (int userId : UserManagerService.getInstance().getUserIds()) {
5402                final int packageCount = mPackages.size();
5403                for (int i = 0; i < packageCount; i++) {
5404                    PackageParser.Package pkg = mPackages.valueAt(i);
5405                    if (!(pkg.mExtras instanceof PackageSetting)) {
5406                        continue;
5407                    }
5408                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5409                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5410                }
5411            }
5412        }
5413    }
5414
5415    @Override
5416    public int getPermissionFlags(String permName, String packageName, int userId) {
5417        return mPermissionManager.getPermissionFlags(
5418                permName, packageName, getCallingUid(), userId);
5419    }
5420
5421    @Override
5422    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5423            int flagValues, int userId) {
5424        mPermissionManager.updatePermissionFlags(
5425                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5426                mPermissionCallback);
5427    }
5428
5429    /**
5430     * Update the permission flags for all packages and runtime permissions of a user in order
5431     * to allow device or profile owner to remove POLICY_FIXED.
5432     */
5433    @Override
5434    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5435        synchronized (mPackages) {
5436            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5437                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5438                    mPermissionCallback);
5439            if (changed) {
5440                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5441            }
5442        }
5443    }
5444
5445    @Override
5446    public boolean shouldShowRequestPermissionRationale(String permissionName,
5447            String packageName, int userId) {
5448        if (UserHandle.getCallingUserId() != userId) {
5449            mContext.enforceCallingPermission(
5450                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5451                    "canShowRequestPermissionRationale for user " + userId);
5452        }
5453
5454        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5455        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5456            return false;
5457        }
5458
5459        if (checkPermission(permissionName, packageName, userId)
5460                == PackageManager.PERMISSION_GRANTED) {
5461            return false;
5462        }
5463
5464        final int flags;
5465
5466        final long identity = Binder.clearCallingIdentity();
5467        try {
5468            flags = getPermissionFlags(permissionName,
5469                    packageName, userId);
5470        } finally {
5471            Binder.restoreCallingIdentity(identity);
5472        }
5473
5474        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5475                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5476                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5477
5478        if ((flags & fixedFlags) != 0) {
5479            return false;
5480        }
5481
5482        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5483    }
5484
5485    @Override
5486    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5487        mContext.enforceCallingOrSelfPermission(
5488                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5489                "addOnPermissionsChangeListener");
5490
5491        synchronized (mPackages) {
5492            mOnPermissionChangeListeners.addListenerLocked(listener);
5493        }
5494    }
5495
5496    @Override
5497    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5498        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5499            throw new SecurityException("Instant applications don't have access to this method");
5500        }
5501        synchronized (mPackages) {
5502            mOnPermissionChangeListeners.removeListenerLocked(listener);
5503        }
5504    }
5505
5506    @Override
5507    public boolean isProtectedBroadcast(String actionName) {
5508        // allow instant applications
5509        synchronized (mProtectedBroadcasts) {
5510            if (mProtectedBroadcasts.contains(actionName)) {
5511                return true;
5512            } else if (actionName != null) {
5513                // TODO: remove these terrible hacks
5514                if (actionName.startsWith("android.net.netmon.lingerExpired")
5515                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5516                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5517                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5518                    return true;
5519                }
5520            }
5521        }
5522        return false;
5523    }
5524
5525    @Override
5526    public int checkSignatures(String pkg1, String pkg2) {
5527        synchronized (mPackages) {
5528            final PackageParser.Package p1 = mPackages.get(pkg1);
5529            final PackageParser.Package p2 = mPackages.get(pkg2);
5530            if (p1 == null || p1.mExtras == null
5531                    || p2 == null || p2.mExtras == null) {
5532                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5533            }
5534            final int callingUid = Binder.getCallingUid();
5535            final int callingUserId = UserHandle.getUserId(callingUid);
5536            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5537            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5538            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5539                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5540                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5541            }
5542            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5543        }
5544    }
5545
5546    @Override
5547    public int checkUidSignatures(int uid1, int uid2) {
5548        final int callingUid = Binder.getCallingUid();
5549        final int callingUserId = UserHandle.getUserId(callingUid);
5550        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5551        // Map to base uids.
5552        uid1 = UserHandle.getAppId(uid1);
5553        uid2 = UserHandle.getAppId(uid2);
5554        // reader
5555        synchronized (mPackages) {
5556            Signature[] s1;
5557            Signature[] s2;
5558            Object obj = mSettings.getUserIdLPr(uid1);
5559            if (obj != null) {
5560                if (obj instanceof SharedUserSetting) {
5561                    if (isCallerInstantApp) {
5562                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5563                    }
5564                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5565                } else if (obj instanceof PackageSetting) {
5566                    final PackageSetting ps = (PackageSetting) obj;
5567                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5568                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5569                    }
5570                    s1 = ps.signatures.mSigningDetails.signatures;
5571                } else {
5572                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5573                }
5574            } else {
5575                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5576            }
5577            obj = mSettings.getUserIdLPr(uid2);
5578            if (obj != null) {
5579                if (obj instanceof SharedUserSetting) {
5580                    if (isCallerInstantApp) {
5581                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5582                    }
5583                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5584                } else if (obj instanceof PackageSetting) {
5585                    final PackageSetting ps = (PackageSetting) obj;
5586                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5587                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5588                    }
5589                    s2 = ps.signatures.mSigningDetails.signatures;
5590                } else {
5591                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5592                }
5593            } else {
5594                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5595            }
5596            return compareSignatures(s1, s2);
5597        }
5598    }
5599
5600    @Override
5601    public boolean hasSigningCertificate(
5602            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5603
5604        synchronized (mPackages) {
5605            final PackageParser.Package p = mPackages.get(packageName);
5606            if (p == null || p.mExtras == null) {
5607                return false;
5608            }
5609            final int callingUid = Binder.getCallingUid();
5610            final int callingUserId = UserHandle.getUserId(callingUid);
5611            final PackageSetting ps = (PackageSetting) p.mExtras;
5612            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5613                return false;
5614            }
5615            switch (type) {
5616                case CERT_INPUT_RAW_X509:
5617                    return p.mSigningDetails.hasCertificate(certificate);
5618                case CERT_INPUT_SHA256:
5619                    return p.mSigningDetails.hasSha256Certificate(certificate);
5620                default:
5621                    return false;
5622            }
5623        }
5624    }
5625
5626    @Override
5627    public boolean hasUidSigningCertificate(
5628            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5629        final int callingUid = Binder.getCallingUid();
5630        final int callingUserId = UserHandle.getUserId(callingUid);
5631        // Map to base uids.
5632        uid = UserHandle.getAppId(uid);
5633        // reader
5634        synchronized (mPackages) {
5635            final PackageParser.SigningDetails signingDetails;
5636            final Object obj = mSettings.getUserIdLPr(uid);
5637            if (obj != null) {
5638                if (obj instanceof SharedUserSetting) {
5639                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5640                    if (isCallerInstantApp) {
5641                        return false;
5642                    }
5643                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5644                } else if (obj instanceof PackageSetting) {
5645                    final PackageSetting ps = (PackageSetting) obj;
5646                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5647                        return false;
5648                    }
5649                    signingDetails = ps.signatures.mSigningDetails;
5650                } else {
5651                    return false;
5652                }
5653            } else {
5654                return false;
5655            }
5656            switch (type) {
5657                case CERT_INPUT_RAW_X509:
5658                    return signingDetails.hasCertificate(certificate);
5659                case CERT_INPUT_SHA256:
5660                    return signingDetails.hasSha256Certificate(certificate);
5661                default:
5662                    return false;
5663            }
5664        }
5665    }
5666
5667    /**
5668     * This method should typically only be used when granting or revoking
5669     * permissions, since the app may immediately restart after this call.
5670     * <p>
5671     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5672     * guard your work against the app being relaunched.
5673     */
5674    private void killUid(int appId, int userId, String reason) {
5675        final long identity = Binder.clearCallingIdentity();
5676        try {
5677            IActivityManager am = ActivityManager.getService();
5678            if (am != null) {
5679                try {
5680                    am.killUid(appId, userId, reason);
5681                } catch (RemoteException e) {
5682                    /* ignore - same process */
5683                }
5684            }
5685        } finally {
5686            Binder.restoreCallingIdentity(identity);
5687        }
5688    }
5689
5690    /**
5691     * If the database version for this type of package (internal storage or
5692     * external storage) is less than the version where package signatures
5693     * were updated, return true.
5694     */
5695    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5696        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5697        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5698    }
5699
5700    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5701        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5702        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5703    }
5704
5705    @Override
5706    public List<String> getAllPackages() {
5707        final int callingUid = Binder.getCallingUid();
5708        final int callingUserId = UserHandle.getUserId(callingUid);
5709        synchronized (mPackages) {
5710            if (canViewInstantApps(callingUid, callingUserId)) {
5711                return new ArrayList<String>(mPackages.keySet());
5712            }
5713            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5714            final List<String> result = new ArrayList<>();
5715            if (instantAppPkgName != null) {
5716                // caller is an instant application; filter unexposed applications
5717                for (PackageParser.Package pkg : mPackages.values()) {
5718                    if (!pkg.visibleToInstantApps) {
5719                        continue;
5720                    }
5721                    result.add(pkg.packageName);
5722                }
5723            } else {
5724                // caller is a normal application; filter instant applications
5725                for (PackageParser.Package pkg : mPackages.values()) {
5726                    final PackageSetting ps =
5727                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5728                    if (ps != null
5729                            && ps.getInstantApp(callingUserId)
5730                            && !mInstantAppRegistry.isInstantAccessGranted(
5731                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5732                        continue;
5733                    }
5734                    result.add(pkg.packageName);
5735                }
5736            }
5737            return result;
5738        }
5739    }
5740
5741    @Override
5742    public String[] getPackagesForUid(int uid) {
5743        final int callingUid = Binder.getCallingUid();
5744        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5745        final int userId = UserHandle.getUserId(uid);
5746        uid = UserHandle.getAppId(uid);
5747        // reader
5748        synchronized (mPackages) {
5749            Object obj = mSettings.getUserIdLPr(uid);
5750            if (obj instanceof SharedUserSetting) {
5751                if (isCallerInstantApp) {
5752                    return null;
5753                }
5754                final SharedUserSetting sus = (SharedUserSetting) obj;
5755                final int N = sus.packages.size();
5756                String[] res = new String[N];
5757                final Iterator<PackageSetting> it = sus.packages.iterator();
5758                int i = 0;
5759                while (it.hasNext()) {
5760                    PackageSetting ps = it.next();
5761                    if (ps.getInstalled(userId)) {
5762                        res[i++] = ps.name;
5763                    } else {
5764                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5765                    }
5766                }
5767                return res;
5768            } else if (obj instanceof PackageSetting) {
5769                final PackageSetting ps = (PackageSetting) obj;
5770                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5771                    return new String[]{ps.name};
5772                }
5773            }
5774        }
5775        return null;
5776    }
5777
5778    @Override
5779    public String getNameForUid(int uid) {
5780        final int callingUid = Binder.getCallingUid();
5781        if (getInstantAppPackageName(callingUid) != null) {
5782            return null;
5783        }
5784        synchronized (mPackages) {
5785            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5786            if (obj instanceof SharedUserSetting) {
5787                final SharedUserSetting sus = (SharedUserSetting) obj;
5788                return sus.name + ":" + sus.userId;
5789            } else if (obj instanceof PackageSetting) {
5790                final PackageSetting ps = (PackageSetting) obj;
5791                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5792                    return null;
5793                }
5794                return ps.name;
5795            }
5796            return null;
5797        }
5798    }
5799
5800    @Override
5801    public String[] getNamesForUids(int[] uids) {
5802        if (uids == null || uids.length == 0) {
5803            return null;
5804        }
5805        final int callingUid = Binder.getCallingUid();
5806        if (getInstantAppPackageName(callingUid) != null) {
5807            return null;
5808        }
5809        final String[] names = new String[uids.length];
5810        synchronized (mPackages) {
5811            for (int i = uids.length - 1; i >= 0; i--) {
5812                final int uid = uids[i];
5813                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5814                if (obj instanceof SharedUserSetting) {
5815                    final SharedUserSetting sus = (SharedUserSetting) obj;
5816                    names[i] = "shared:" + sus.name;
5817                } else if (obj instanceof PackageSetting) {
5818                    final PackageSetting ps = (PackageSetting) obj;
5819                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5820                        names[i] = null;
5821                    } else {
5822                        names[i] = ps.name;
5823                    }
5824                } else {
5825                    names[i] = null;
5826                }
5827            }
5828        }
5829        return names;
5830    }
5831
5832    @Override
5833    public int getUidForSharedUser(String sharedUserName) {
5834        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5835            return -1;
5836        }
5837        if (sharedUserName == null) {
5838            return -1;
5839        }
5840        // reader
5841        synchronized (mPackages) {
5842            SharedUserSetting suid;
5843            try {
5844                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5845                if (suid != null) {
5846                    return suid.userId;
5847                }
5848            } catch (PackageManagerException ignore) {
5849                // can't happen, but, still need to catch it
5850            }
5851            return -1;
5852        }
5853    }
5854
5855    @Override
5856    public int getFlagsForUid(int uid) {
5857        final int callingUid = Binder.getCallingUid();
5858        if (getInstantAppPackageName(callingUid) != null) {
5859            return 0;
5860        }
5861        synchronized (mPackages) {
5862            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5863            if (obj instanceof SharedUserSetting) {
5864                final SharedUserSetting sus = (SharedUserSetting) obj;
5865                return sus.pkgFlags;
5866            } else if (obj instanceof PackageSetting) {
5867                final PackageSetting ps = (PackageSetting) obj;
5868                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5869                    return 0;
5870                }
5871                return ps.pkgFlags;
5872            }
5873        }
5874        return 0;
5875    }
5876
5877    @Override
5878    public int getPrivateFlagsForUid(int uid) {
5879        final int callingUid = Binder.getCallingUid();
5880        if (getInstantAppPackageName(callingUid) != null) {
5881            return 0;
5882        }
5883        synchronized (mPackages) {
5884            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5885            if (obj instanceof SharedUserSetting) {
5886                final SharedUserSetting sus = (SharedUserSetting) obj;
5887                return sus.pkgPrivateFlags;
5888            } else if (obj instanceof PackageSetting) {
5889                final PackageSetting ps = (PackageSetting) obj;
5890                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5891                    return 0;
5892                }
5893                return ps.pkgPrivateFlags;
5894            }
5895        }
5896        return 0;
5897    }
5898
5899    @Override
5900    public boolean isUidPrivileged(int uid) {
5901        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5902            return false;
5903        }
5904        uid = UserHandle.getAppId(uid);
5905        // reader
5906        synchronized (mPackages) {
5907            Object obj = mSettings.getUserIdLPr(uid);
5908            if (obj instanceof SharedUserSetting) {
5909                final SharedUserSetting sus = (SharedUserSetting) obj;
5910                final Iterator<PackageSetting> it = sus.packages.iterator();
5911                while (it.hasNext()) {
5912                    if (it.next().isPrivileged()) {
5913                        return true;
5914                    }
5915                }
5916            } else if (obj instanceof PackageSetting) {
5917                final PackageSetting ps = (PackageSetting) obj;
5918                return ps.isPrivileged();
5919            }
5920        }
5921        return false;
5922    }
5923
5924    @Override
5925    public String[] getAppOpPermissionPackages(String permName) {
5926        return mPermissionManager.getAppOpPermissionPackages(permName);
5927    }
5928
5929    @Override
5930    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5931            int flags, int userId) {
5932        return resolveIntentInternal(
5933                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5934    }
5935
5936    /**
5937     * Normally instant apps can only be resolved when they're visible to the caller.
5938     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5939     * since we need to allow the system to start any installed application.
5940     */
5941    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5942            int flags, int userId, boolean resolveForStart) {
5943        try {
5944            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5945
5946            if (!sUserManager.exists(userId)) return null;
5947            final int callingUid = Binder.getCallingUid();
5948            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5949            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5950                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5951
5952            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5953            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5954                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5955            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5956
5957            final ResolveInfo bestChoice =
5958                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5959            return bestChoice;
5960        } finally {
5961            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5962        }
5963    }
5964
5965    @Override
5966    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5967        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5968            throw new SecurityException(
5969                    "findPersistentPreferredActivity can only be run by the system");
5970        }
5971        if (!sUserManager.exists(userId)) {
5972            return null;
5973        }
5974        final int callingUid = Binder.getCallingUid();
5975        intent = updateIntentForResolve(intent);
5976        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5977        final int flags = updateFlagsForResolve(
5978                0, userId, intent, callingUid, false /*includeInstantApps*/);
5979        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5980                userId);
5981        synchronized (mPackages) {
5982            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5983                    userId);
5984        }
5985    }
5986
5987    @Override
5988    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5989            IntentFilter filter, int match, ComponentName activity) {
5990        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5991            return;
5992        }
5993        final int userId = UserHandle.getCallingUserId();
5994        if (DEBUG_PREFERRED) {
5995            Log.v(TAG, "setLastChosenActivity intent=" + intent
5996                + " resolvedType=" + resolvedType
5997                + " flags=" + flags
5998                + " filter=" + filter
5999                + " match=" + match
6000                + " activity=" + activity);
6001            filter.dump(new PrintStreamPrinter(System.out), "    ");
6002        }
6003        intent.setComponent(null);
6004        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6005                userId);
6006        // Find any earlier preferred or last chosen entries and nuke them
6007        findPreferredActivity(intent, resolvedType,
6008                flags, query, 0, false, true, false, userId);
6009        // Add the new activity as the last chosen for this filter
6010        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6011                "Setting last chosen");
6012    }
6013
6014    @Override
6015    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6016        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6017            return null;
6018        }
6019        final int userId = UserHandle.getCallingUserId();
6020        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6021        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6022                userId);
6023        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6024                false, false, false, userId);
6025    }
6026
6027    /**
6028     * Returns whether or not instant apps have been disabled remotely.
6029     */
6030    private boolean areWebInstantAppsDisabled() {
6031        return mWebInstantAppsDisabled;
6032    }
6033
6034    private boolean isInstantAppResolutionAllowed(
6035            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6036            boolean skipPackageCheck) {
6037        if (mInstantAppResolverConnection == null) {
6038            return false;
6039        }
6040        if (mInstantAppInstallerActivity == null) {
6041            return false;
6042        }
6043        if (intent.getComponent() != null) {
6044            return false;
6045        }
6046        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6047            return false;
6048        }
6049        if (!skipPackageCheck && intent.getPackage() != null) {
6050            return false;
6051        }
6052        if (!intent.isWebIntent()) {
6053            // for non web intents, we should not resolve externally if an app already exists to
6054            // handle it or if the caller didn't explicitly request it.
6055            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6056                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6057                return false;
6058            }
6059        } else {
6060            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6061                return false;
6062            } else if (areWebInstantAppsDisabled()) {
6063                return false;
6064            }
6065        }
6066        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6067        // Or if there's already an ephemeral app installed that handles the action
6068        synchronized (mPackages) {
6069            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6070            for (int n = 0; n < count; n++) {
6071                final ResolveInfo info = resolvedActivities.get(n);
6072                final String packageName = info.activityInfo.packageName;
6073                final PackageSetting ps = mSettings.mPackages.get(packageName);
6074                if (ps != null) {
6075                    // only check domain verification status if the app is not a browser
6076                    if (!info.handleAllWebDataURI) {
6077                        // Try to get the status from User settings first
6078                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6079                        final int status = (int) (packedStatus >> 32);
6080                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6081                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6082                            if (DEBUG_INSTANT) {
6083                                Slog.v(TAG, "DENY instant app;"
6084                                    + " pkg: " + packageName + ", status: " + status);
6085                            }
6086                            return false;
6087                        }
6088                    }
6089                    if (ps.getInstantApp(userId)) {
6090                        if (DEBUG_INSTANT) {
6091                            Slog.v(TAG, "DENY instant app installed;"
6092                                    + " pkg: " + packageName);
6093                        }
6094                        return false;
6095                    }
6096                }
6097            }
6098        }
6099        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6100        return true;
6101    }
6102
6103    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6104            Intent origIntent, String resolvedType, String callingPackage,
6105            Bundle verificationBundle, int userId) {
6106        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6107                new InstantAppRequest(responseObj, origIntent, resolvedType,
6108                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6109        mHandler.sendMessage(msg);
6110    }
6111
6112    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6113            int flags, List<ResolveInfo> query, int userId) {
6114        if (query != null) {
6115            final int N = query.size();
6116            if (N == 1) {
6117                return query.get(0);
6118            } else if (N > 1) {
6119                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6120                // If there is more than one activity with the same priority,
6121                // then let the user decide between them.
6122                ResolveInfo r0 = query.get(0);
6123                ResolveInfo r1 = query.get(1);
6124                if (DEBUG_INTENT_MATCHING || debug) {
6125                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6126                            + r1.activityInfo.name + "=" + r1.priority);
6127                }
6128                // If the first activity has a higher priority, or a different
6129                // default, then it is always desirable to pick it.
6130                if (r0.priority != r1.priority
6131                        || r0.preferredOrder != r1.preferredOrder
6132                        || r0.isDefault != r1.isDefault) {
6133                    return query.get(0);
6134                }
6135                // If we have saved a preference for a preferred activity for
6136                // this Intent, use that.
6137                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6138                        flags, query, r0.priority, true, false, debug, userId);
6139                if (ri != null) {
6140                    return ri;
6141                }
6142                // If we have an ephemeral app, use it
6143                for (int i = 0; i < N; i++) {
6144                    ri = query.get(i);
6145                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6146                        final String packageName = ri.activityInfo.packageName;
6147                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6148                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6149                        final int status = (int)(packedStatus >> 32);
6150                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6151                            return ri;
6152                        }
6153                    }
6154                }
6155                ri = new ResolveInfo(mResolveInfo);
6156                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6157                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6158                // If all of the options come from the same package, show the application's
6159                // label and icon instead of the generic resolver's.
6160                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6161                // and then throw away the ResolveInfo itself, meaning that the caller loses
6162                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6163                // a fallback for this case; we only set the target package's resources on
6164                // the ResolveInfo, not the ActivityInfo.
6165                final String intentPackage = intent.getPackage();
6166                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6167                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6168                    ri.resolvePackageName = intentPackage;
6169                    if (userNeedsBadging(userId)) {
6170                        ri.noResourceId = true;
6171                    } else {
6172                        ri.icon = appi.icon;
6173                    }
6174                    ri.iconResourceId = appi.icon;
6175                    ri.labelRes = appi.labelRes;
6176                }
6177                ri.activityInfo.applicationInfo = new ApplicationInfo(
6178                        ri.activityInfo.applicationInfo);
6179                if (userId != 0) {
6180                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6181                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6182                }
6183                // Make sure that the resolver is displayable in car mode
6184                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6185                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6186                return ri;
6187            }
6188        }
6189        return null;
6190    }
6191
6192    /**
6193     * Return true if the given list is not empty and all of its contents have
6194     * an activityInfo with the given package name.
6195     */
6196    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6197        if (ArrayUtils.isEmpty(list)) {
6198            return false;
6199        }
6200        for (int i = 0, N = list.size(); i < N; i++) {
6201            final ResolveInfo ri = list.get(i);
6202            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6203            if (ai == null || !packageName.equals(ai.packageName)) {
6204                return false;
6205            }
6206        }
6207        return true;
6208    }
6209
6210    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6211            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6212        final int N = query.size();
6213        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6214                .get(userId);
6215        // Get the list of persistent preferred activities that handle the intent
6216        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6217        List<PersistentPreferredActivity> pprefs = ppir != null
6218                ? ppir.queryIntent(intent, resolvedType,
6219                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6220                        userId)
6221                : null;
6222        if (pprefs != null && pprefs.size() > 0) {
6223            final int M = pprefs.size();
6224            for (int i=0; i<M; i++) {
6225                final PersistentPreferredActivity ppa = pprefs.get(i);
6226                if (DEBUG_PREFERRED || debug) {
6227                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6228                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6229                            + "\n  component=" + ppa.mComponent);
6230                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6231                }
6232                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6233                        flags | MATCH_DISABLED_COMPONENTS, userId);
6234                if (DEBUG_PREFERRED || debug) {
6235                    Slog.v(TAG, "Found persistent preferred activity:");
6236                    if (ai != null) {
6237                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6238                    } else {
6239                        Slog.v(TAG, "  null");
6240                    }
6241                }
6242                if (ai == null) {
6243                    // This previously registered persistent preferred activity
6244                    // component is no longer known. Ignore it and do NOT remove it.
6245                    continue;
6246                }
6247                for (int j=0; j<N; j++) {
6248                    final ResolveInfo ri = query.get(j);
6249                    if (!ri.activityInfo.applicationInfo.packageName
6250                            .equals(ai.applicationInfo.packageName)) {
6251                        continue;
6252                    }
6253                    if (!ri.activityInfo.name.equals(ai.name)) {
6254                        continue;
6255                    }
6256                    //  Found a persistent preference that can handle the intent.
6257                    if (DEBUG_PREFERRED || debug) {
6258                        Slog.v(TAG, "Returning persistent preferred activity: " +
6259                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6260                    }
6261                    return ri;
6262                }
6263            }
6264        }
6265        return null;
6266    }
6267
6268    // TODO: handle preferred activities missing while user has amnesia
6269    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6270            List<ResolveInfo> query, int priority, boolean always,
6271            boolean removeMatches, boolean debug, int userId) {
6272        if (!sUserManager.exists(userId)) return null;
6273        final int callingUid = Binder.getCallingUid();
6274        flags = updateFlagsForResolve(
6275                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6276        intent = updateIntentForResolve(intent);
6277        // writer
6278        synchronized (mPackages) {
6279            // Try to find a matching persistent preferred activity.
6280            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6281                    debug, userId);
6282
6283            // If a persistent preferred activity matched, use it.
6284            if (pri != null) {
6285                return pri;
6286            }
6287
6288            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6289            // Get the list of preferred activities that handle the intent
6290            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6291            List<PreferredActivity> prefs = pir != null
6292                    ? pir.queryIntent(intent, resolvedType,
6293                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6294                            userId)
6295                    : null;
6296            if (prefs != null && prefs.size() > 0) {
6297                boolean changed = false;
6298                try {
6299                    // First figure out how good the original match set is.
6300                    // We will only allow preferred activities that came
6301                    // from the same match quality.
6302                    int match = 0;
6303
6304                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6305
6306                    final int N = query.size();
6307                    for (int j=0; j<N; j++) {
6308                        final ResolveInfo ri = query.get(j);
6309                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6310                                + ": 0x" + Integer.toHexString(match));
6311                        if (ri.match > match) {
6312                            match = ri.match;
6313                        }
6314                    }
6315
6316                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6317                            + Integer.toHexString(match));
6318
6319                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6320                    final int M = prefs.size();
6321                    for (int i=0; i<M; i++) {
6322                        final PreferredActivity pa = prefs.get(i);
6323                        if (DEBUG_PREFERRED || debug) {
6324                            Slog.v(TAG, "Checking PreferredActivity ds="
6325                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6326                                    + "\n  component=" + pa.mPref.mComponent);
6327                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6328                        }
6329                        if (pa.mPref.mMatch != match) {
6330                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6331                                    + Integer.toHexString(pa.mPref.mMatch));
6332                            continue;
6333                        }
6334                        // If it's not an "always" type preferred activity and that's what we're
6335                        // looking for, skip it.
6336                        if (always && !pa.mPref.mAlways) {
6337                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6338                            continue;
6339                        }
6340                        final ActivityInfo ai = getActivityInfo(
6341                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6342                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6343                                userId);
6344                        if (DEBUG_PREFERRED || debug) {
6345                            Slog.v(TAG, "Found preferred activity:");
6346                            if (ai != null) {
6347                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6348                            } else {
6349                                Slog.v(TAG, "  null");
6350                            }
6351                        }
6352                        if (ai == null) {
6353                            // This previously registered preferred activity
6354                            // component is no longer known.  Most likely an update
6355                            // to the app was installed and in the new version this
6356                            // component no longer exists.  Clean it up by removing
6357                            // it from the preferred activities list, and skip it.
6358                            Slog.w(TAG, "Removing dangling preferred activity: "
6359                                    + pa.mPref.mComponent);
6360                            pir.removeFilter(pa);
6361                            changed = true;
6362                            continue;
6363                        }
6364                        for (int j=0; j<N; j++) {
6365                            final ResolveInfo ri = query.get(j);
6366                            if (!ri.activityInfo.applicationInfo.packageName
6367                                    .equals(ai.applicationInfo.packageName)) {
6368                                continue;
6369                            }
6370                            if (!ri.activityInfo.name.equals(ai.name)) {
6371                                continue;
6372                            }
6373
6374                            if (removeMatches) {
6375                                pir.removeFilter(pa);
6376                                changed = true;
6377                                if (DEBUG_PREFERRED) {
6378                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6379                                }
6380                                break;
6381                            }
6382
6383                            // Okay we found a previously set preferred or last chosen app.
6384                            // If the result set is different from when this
6385                            // was created, and is not a subset of the preferred set, we need to
6386                            // clear it and re-ask the user their preference, if we're looking for
6387                            // an "always" type entry.
6388                            if (always && !pa.mPref.sameSet(query)) {
6389                                if (pa.mPref.isSuperset(query)) {
6390                                    // some components of the set are no longer present in
6391                                    // the query, but the preferred activity can still be reused
6392                                    if (DEBUG_PREFERRED) {
6393                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6394                                                + " still valid as only non-preferred components"
6395                                                + " were removed for " + intent + " type "
6396                                                + resolvedType);
6397                                    }
6398                                    // remove obsolete components and re-add the up-to-date filter
6399                                    PreferredActivity freshPa = new PreferredActivity(pa,
6400                                            pa.mPref.mMatch,
6401                                            pa.mPref.discardObsoleteComponents(query),
6402                                            pa.mPref.mComponent,
6403                                            pa.mPref.mAlways);
6404                                    pir.removeFilter(pa);
6405                                    pir.addFilter(freshPa);
6406                                    changed = true;
6407                                } else {
6408                                    Slog.i(TAG,
6409                                            "Result set changed, dropping preferred activity for "
6410                                                    + intent + " type " + resolvedType);
6411                                    if (DEBUG_PREFERRED) {
6412                                        Slog.v(TAG, "Removing preferred activity since set changed "
6413                                                + pa.mPref.mComponent);
6414                                    }
6415                                    pir.removeFilter(pa);
6416                                    // Re-add the filter as a "last chosen" entry (!always)
6417                                    PreferredActivity lastChosen = new PreferredActivity(
6418                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6419                                    pir.addFilter(lastChosen);
6420                                    changed = true;
6421                                    return null;
6422                                }
6423                            }
6424
6425                            // Yay! Either the set matched or we're looking for the last chosen
6426                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6427                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6428                            return ri;
6429                        }
6430                    }
6431                } finally {
6432                    if (changed) {
6433                        if (DEBUG_PREFERRED) {
6434                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6435                        }
6436                        scheduleWritePackageRestrictionsLocked(userId);
6437                    }
6438                }
6439            }
6440        }
6441        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6442        return null;
6443    }
6444
6445    /*
6446     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6447     */
6448    @Override
6449    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6450            int targetUserId) {
6451        mContext.enforceCallingOrSelfPermission(
6452                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6453        List<CrossProfileIntentFilter> matches =
6454                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6455        if (matches != null) {
6456            int size = matches.size();
6457            for (int i = 0; i < size; i++) {
6458                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6459            }
6460        }
6461        if (intent.hasWebURI()) {
6462            // cross-profile app linking works only towards the parent.
6463            final int callingUid = Binder.getCallingUid();
6464            final UserInfo parent = getProfileParent(sourceUserId);
6465            synchronized(mPackages) {
6466                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6467                        false /*includeInstantApps*/);
6468                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6469                        intent, resolvedType, flags, sourceUserId, parent.id);
6470                return xpDomainInfo != null;
6471            }
6472        }
6473        return false;
6474    }
6475
6476    private UserInfo getProfileParent(int userId) {
6477        final long identity = Binder.clearCallingIdentity();
6478        try {
6479            return sUserManager.getProfileParent(userId);
6480        } finally {
6481            Binder.restoreCallingIdentity(identity);
6482        }
6483    }
6484
6485    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6486            String resolvedType, int userId) {
6487        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6488        if (resolver != null) {
6489            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6490        }
6491        return null;
6492    }
6493
6494    @Override
6495    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6496            String resolvedType, int flags, int userId) {
6497        try {
6498            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6499
6500            return new ParceledListSlice<>(
6501                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6502        } finally {
6503            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6504        }
6505    }
6506
6507    /**
6508     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6509     * instant, returns {@code null}.
6510     */
6511    private String getInstantAppPackageName(int callingUid) {
6512        synchronized (mPackages) {
6513            // If the caller is an isolated app use the owner's uid for the lookup.
6514            if (Process.isIsolated(callingUid)) {
6515                callingUid = mIsolatedOwners.get(callingUid);
6516            }
6517            final int appId = UserHandle.getAppId(callingUid);
6518            final Object obj = mSettings.getUserIdLPr(appId);
6519            if (obj instanceof PackageSetting) {
6520                final PackageSetting ps = (PackageSetting) obj;
6521                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6522                return isInstantApp ? ps.pkg.packageName : null;
6523            }
6524        }
6525        return null;
6526    }
6527
6528    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6529            String resolvedType, int flags, int userId) {
6530        return queryIntentActivitiesInternal(
6531                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6532                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6533    }
6534
6535    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6536            String resolvedType, int flags, int filterCallingUid, int userId,
6537            boolean resolveForStart, boolean allowDynamicSplits) {
6538        if (!sUserManager.exists(userId)) return Collections.emptyList();
6539        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6540        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6541                false /* requireFullPermission */, false /* checkShell */,
6542                "query intent activities");
6543        final String pkgName = intent.getPackage();
6544        ComponentName comp = intent.getComponent();
6545        if (comp == null) {
6546            if (intent.getSelector() != null) {
6547                intent = intent.getSelector();
6548                comp = intent.getComponent();
6549            }
6550        }
6551
6552        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6553                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6554        if (comp != null) {
6555            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6556            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6557            if (ai != null) {
6558                // When specifying an explicit component, we prevent the activity from being
6559                // used when either 1) the calling package is normal and the activity is within
6560                // an ephemeral application or 2) the calling package is ephemeral and the
6561                // activity is not visible to ephemeral applications.
6562                final boolean matchInstantApp =
6563                        (flags & PackageManager.MATCH_INSTANT) != 0;
6564                final boolean matchVisibleToInstantAppOnly =
6565                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6566                final boolean matchExplicitlyVisibleOnly =
6567                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6568                final boolean isCallerInstantApp =
6569                        instantAppPkgName != null;
6570                final boolean isTargetSameInstantApp =
6571                        comp.getPackageName().equals(instantAppPkgName);
6572                final boolean isTargetInstantApp =
6573                        (ai.applicationInfo.privateFlags
6574                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6575                final boolean isTargetVisibleToInstantApp =
6576                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6577                final boolean isTargetExplicitlyVisibleToInstantApp =
6578                        isTargetVisibleToInstantApp
6579                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6580                final boolean isTargetHiddenFromInstantApp =
6581                        !isTargetVisibleToInstantApp
6582                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6583                final boolean blockResolution =
6584                        !isTargetSameInstantApp
6585                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6586                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6587                                        && isTargetHiddenFromInstantApp));
6588                if (!blockResolution) {
6589                    final ResolveInfo ri = new ResolveInfo();
6590                    ri.activityInfo = ai;
6591                    list.add(ri);
6592                }
6593            }
6594            return applyPostResolutionFilter(
6595                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6596        }
6597
6598        // reader
6599        boolean sortResult = false;
6600        boolean addInstant = false;
6601        List<ResolveInfo> result;
6602        synchronized (mPackages) {
6603            if (pkgName == null) {
6604                List<CrossProfileIntentFilter> matchingFilters =
6605                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6606                // Check for results that need to skip the current profile.
6607                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6608                        resolvedType, flags, userId);
6609                if (xpResolveInfo != null) {
6610                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6611                    xpResult.add(xpResolveInfo);
6612                    return applyPostResolutionFilter(
6613                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6614                            allowDynamicSplits, filterCallingUid, userId, intent);
6615                }
6616
6617                // Check for results in the current profile.
6618                result = filterIfNotSystemUser(mActivities.queryIntent(
6619                        intent, resolvedType, flags, userId), userId);
6620                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6621                        false /*skipPackageCheck*/);
6622                // Check for cross profile results.
6623                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6624                xpResolveInfo = queryCrossProfileIntents(
6625                        matchingFilters, intent, resolvedType, flags, userId,
6626                        hasNonNegativePriorityResult);
6627                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6628                    boolean isVisibleToUser = filterIfNotSystemUser(
6629                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6630                    if (isVisibleToUser) {
6631                        result.add(xpResolveInfo);
6632                        sortResult = true;
6633                    }
6634                }
6635                if (intent.hasWebURI()) {
6636                    CrossProfileDomainInfo xpDomainInfo = null;
6637                    final UserInfo parent = getProfileParent(userId);
6638                    if (parent != null) {
6639                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6640                                flags, userId, parent.id);
6641                    }
6642                    if (xpDomainInfo != null) {
6643                        if (xpResolveInfo != null) {
6644                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6645                            // in the result.
6646                            result.remove(xpResolveInfo);
6647                        }
6648                        if (result.size() == 0 && !addInstant) {
6649                            // No result in current profile, but found candidate in parent user.
6650                            // And we are not going to add emphemeral app, so we can return the
6651                            // result straight away.
6652                            result.add(xpDomainInfo.resolveInfo);
6653                            return applyPostResolutionFilter(result, instantAppPkgName,
6654                                    allowDynamicSplits, filterCallingUid, userId, intent);
6655                        }
6656                    } else if (result.size() <= 1 && !addInstant) {
6657                        // No result in parent user and <= 1 result in current profile, and we
6658                        // are not going to add emphemeral app, so we can return the result without
6659                        // further processing.
6660                        return applyPostResolutionFilter(result, instantAppPkgName,
6661                                allowDynamicSplits, filterCallingUid, userId, intent);
6662                    }
6663                    // We have more than one candidate (combining results from current and parent
6664                    // profile), so we need filtering and sorting.
6665                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6666                            intent, flags, result, xpDomainInfo, userId);
6667                    sortResult = true;
6668                }
6669            } else {
6670                final PackageParser.Package pkg = mPackages.get(pkgName);
6671                result = null;
6672                if (pkg != null) {
6673                    result = filterIfNotSystemUser(
6674                            mActivities.queryIntentForPackage(
6675                                    intent, resolvedType, flags, pkg.activities, userId),
6676                            userId);
6677                }
6678                if (result == null || result.size() == 0) {
6679                    // the caller wants to resolve for a particular package; however, there
6680                    // were no installed results, so, try to find an ephemeral result
6681                    addInstant = isInstantAppResolutionAllowed(
6682                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6683                    if (result == null) {
6684                        result = new ArrayList<>();
6685                    }
6686                }
6687            }
6688        }
6689        if (addInstant) {
6690            result = maybeAddInstantAppInstaller(
6691                    result, intent, resolvedType, flags, userId, resolveForStart);
6692        }
6693        if (sortResult) {
6694            Collections.sort(result, mResolvePrioritySorter);
6695        }
6696        return applyPostResolutionFilter(
6697                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6698    }
6699
6700    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6701            String resolvedType, int flags, int userId, boolean resolveForStart) {
6702        // first, check to see if we've got an instant app already installed
6703        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6704        ResolveInfo localInstantApp = null;
6705        boolean blockResolution = false;
6706        if (!alreadyResolvedLocally) {
6707            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6708                    flags
6709                        | PackageManager.GET_RESOLVED_FILTER
6710                        | PackageManager.MATCH_INSTANT
6711                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6712                    userId);
6713            for (int i = instantApps.size() - 1; i >= 0; --i) {
6714                final ResolveInfo info = instantApps.get(i);
6715                final String packageName = info.activityInfo.packageName;
6716                final PackageSetting ps = mSettings.mPackages.get(packageName);
6717                if (ps.getInstantApp(userId)) {
6718                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6719                    final int status = (int)(packedStatus >> 32);
6720                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6721                        // there's a local instant application installed, but, the user has
6722                        // chosen to never use it; skip resolution and don't acknowledge
6723                        // an instant application is even available
6724                        if (DEBUG_INSTANT) {
6725                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6726                        }
6727                        blockResolution = true;
6728                        break;
6729                    } else {
6730                        // we have a locally installed instant application; skip resolution
6731                        // but acknowledge there's an instant application available
6732                        if (DEBUG_INSTANT) {
6733                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6734                        }
6735                        localInstantApp = info;
6736                        break;
6737                    }
6738                }
6739            }
6740        }
6741        // no app installed, let's see if one's available
6742        AuxiliaryResolveInfo auxiliaryResponse = null;
6743        if (!blockResolution) {
6744            if (localInstantApp == null) {
6745                // we don't have an instant app locally, resolve externally
6746                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6747                final InstantAppRequest requestObject = new InstantAppRequest(
6748                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6749                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6750                        resolveForStart);
6751                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6752                        mInstantAppResolverConnection, requestObject);
6753                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6754            } else {
6755                // we have an instant application locally, but, we can't admit that since
6756                // callers shouldn't be able to determine prior browsing. create a dummy
6757                // auxiliary response so the downstream code behaves as if there's an
6758                // instant application available externally. when it comes time to start
6759                // the instant application, we'll do the right thing.
6760                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6761                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6762                                        ai.packageName, ai.versionCode, null /* splitName */);
6763            }
6764        }
6765        if (intent.isWebIntent() && auxiliaryResponse == null) {
6766            return result;
6767        }
6768        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6769        if (ps == null
6770                || ps.getUserState().get(userId) == null
6771                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6772            return result;
6773        }
6774        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6775        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6776                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6777        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6778                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6779        // add a non-generic filter
6780        ephemeralInstaller.filter = new IntentFilter();
6781        if (intent.getAction() != null) {
6782            ephemeralInstaller.filter.addAction(intent.getAction());
6783        }
6784        if (intent.getData() != null && intent.getData().getPath() != null) {
6785            ephemeralInstaller.filter.addDataPath(
6786                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6787        }
6788        ephemeralInstaller.isInstantAppAvailable = true;
6789        // make sure this resolver is the default
6790        ephemeralInstaller.isDefault = true;
6791        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6792        if (DEBUG_INSTANT) {
6793            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6794        }
6795
6796        result.add(ephemeralInstaller);
6797        return result;
6798    }
6799
6800    private static class CrossProfileDomainInfo {
6801        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6802        ResolveInfo resolveInfo;
6803        /* Best domain verification status of the activities found in the other profile */
6804        int bestDomainVerificationStatus;
6805    }
6806
6807    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6808            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6809        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6810                sourceUserId)) {
6811            return null;
6812        }
6813        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6814                resolvedType, flags, parentUserId);
6815
6816        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6817            return null;
6818        }
6819        CrossProfileDomainInfo result = null;
6820        int size = resultTargetUser.size();
6821        for (int i = 0; i < size; i++) {
6822            ResolveInfo riTargetUser = resultTargetUser.get(i);
6823            // Intent filter verification is only for filters that specify a host. So don't return
6824            // those that handle all web uris.
6825            if (riTargetUser.handleAllWebDataURI) {
6826                continue;
6827            }
6828            String packageName = riTargetUser.activityInfo.packageName;
6829            PackageSetting ps = mSettings.mPackages.get(packageName);
6830            if (ps == null) {
6831                continue;
6832            }
6833            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6834            int status = (int)(verificationState >> 32);
6835            if (result == null) {
6836                result = new CrossProfileDomainInfo();
6837                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6838                        sourceUserId, parentUserId);
6839                result.bestDomainVerificationStatus = status;
6840            } else {
6841                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6842                        result.bestDomainVerificationStatus);
6843            }
6844        }
6845        // Don't consider matches with status NEVER across profiles.
6846        if (result != null && result.bestDomainVerificationStatus
6847                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6848            return null;
6849        }
6850        return result;
6851    }
6852
6853    /**
6854     * Verification statuses are ordered from the worse to the best, except for
6855     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6856     */
6857    private int bestDomainVerificationStatus(int status1, int status2) {
6858        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6859            return status2;
6860        }
6861        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6862            return status1;
6863        }
6864        return (int) MathUtils.max(status1, status2);
6865    }
6866
6867    private boolean isUserEnabled(int userId) {
6868        long callingId = Binder.clearCallingIdentity();
6869        try {
6870            UserInfo userInfo = sUserManager.getUserInfo(userId);
6871            return userInfo != null && userInfo.isEnabled();
6872        } finally {
6873            Binder.restoreCallingIdentity(callingId);
6874        }
6875    }
6876
6877    /**
6878     * Filter out activities with systemUserOnly flag set, when current user is not System.
6879     *
6880     * @return filtered list
6881     */
6882    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6883        if (userId == UserHandle.USER_SYSTEM) {
6884            return resolveInfos;
6885        }
6886        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6887            ResolveInfo info = resolveInfos.get(i);
6888            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6889                resolveInfos.remove(i);
6890            }
6891        }
6892        return resolveInfos;
6893    }
6894
6895    /**
6896     * Filters out ephemeral activities.
6897     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6898     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6899     *
6900     * @param resolveInfos The pre-filtered list of resolved activities
6901     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6902     *          is performed.
6903     * @param intent
6904     * @return A filtered list of resolved activities.
6905     */
6906    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6907            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6908            Intent intent) {
6909        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6910        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6911            final ResolveInfo info = resolveInfos.get(i);
6912            // remove locally resolved instant app web results when disabled
6913            if (info.isInstantAppAvailable && blockInstant) {
6914                resolveInfos.remove(i);
6915                continue;
6916            }
6917            // allow activities that are defined in the provided package
6918            if (allowDynamicSplits
6919                    && info.activityInfo != null
6920                    && info.activityInfo.splitName != null
6921                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6922                            info.activityInfo.splitName)) {
6923                if (mInstantAppInstallerActivity == null) {
6924                    if (DEBUG_INSTALL) {
6925                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6926                    }
6927                    resolveInfos.remove(i);
6928                    continue;
6929                }
6930                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6931                    resolveInfos.remove(i);
6932                    continue;
6933                }
6934                // requested activity is defined in a split that hasn't been installed yet.
6935                // add the installer to the resolve list
6936                if (DEBUG_INSTALL) {
6937                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6938                }
6939                final ResolveInfo installerInfo = new ResolveInfo(
6940                        mInstantAppInstallerInfo);
6941                final ComponentName installFailureActivity = findInstallFailureActivity(
6942                        info.activityInfo.packageName,  filterCallingUid, userId);
6943                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6944                        installFailureActivity,
6945                        info.activityInfo.packageName,
6946                        info.activityInfo.applicationInfo.versionCode,
6947                        info.activityInfo.splitName);
6948                // add a non-generic filter
6949                installerInfo.filter = new IntentFilter();
6950
6951                // This resolve info may appear in the chooser UI, so let us make it
6952                // look as the one it replaces as far as the user is concerned which
6953                // requires loading the correct label and icon for the resolve info.
6954                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6955                installerInfo.labelRes = info.resolveLabelResId();
6956                installerInfo.icon = info.resolveIconResId();
6957                installerInfo.isInstantAppAvailable = true;
6958                resolveInfos.set(i, installerInfo);
6959                continue;
6960            }
6961            // caller is a full app, don't need to apply any other filtering
6962            if (ephemeralPkgName == null) {
6963                continue;
6964            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6965                // caller is same app; don't need to apply any other filtering
6966                continue;
6967            }
6968            // allow activities that have been explicitly exposed to ephemeral apps
6969            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6970            if (!isEphemeralApp
6971                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6972                continue;
6973            }
6974            resolveInfos.remove(i);
6975        }
6976        return resolveInfos;
6977    }
6978
6979    /**
6980     * Returns the activity component that can handle install failures.
6981     * <p>By default, the instant application installer handles failures. However, an
6982     * application may want to handle failures on its own. Applications do this by
6983     * creating an activity with an intent filter that handles the action
6984     * {@link Intent#ACTION_INSTALL_FAILURE}.
6985     */
6986    private @Nullable ComponentName findInstallFailureActivity(
6987            String packageName, int filterCallingUid, int userId) {
6988        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6989        failureActivityIntent.setPackage(packageName);
6990        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6991        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6992                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6993                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6994        final int NR = result.size();
6995        if (NR > 0) {
6996            for (int i = 0; i < NR; i++) {
6997                final ResolveInfo info = result.get(i);
6998                if (info.activityInfo.splitName != null) {
6999                    continue;
7000                }
7001                return new ComponentName(packageName, info.activityInfo.name);
7002            }
7003        }
7004        return null;
7005    }
7006
7007    /**
7008     * @param resolveInfos list of resolve infos in descending priority order
7009     * @return if the list contains a resolve info with non-negative priority
7010     */
7011    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7012        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7013    }
7014
7015    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7016            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7017            int userId) {
7018        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7019
7020        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7021            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7022                    candidates.size());
7023        }
7024
7025        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7026        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7027        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7028        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7029        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7030        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7031
7032        synchronized (mPackages) {
7033            final int count = candidates.size();
7034            // First, try to use linked apps. Partition the candidates into four lists:
7035            // one for the final results, one for the "do not use ever", one for "undefined status"
7036            // and finally one for "browser app type".
7037            for (int n=0; n<count; n++) {
7038                ResolveInfo info = candidates.get(n);
7039                String packageName = info.activityInfo.packageName;
7040                PackageSetting ps = mSettings.mPackages.get(packageName);
7041                if (ps != null) {
7042                    // Add to the special match all list (Browser use case)
7043                    if (info.handleAllWebDataURI) {
7044                        matchAllList.add(info);
7045                        continue;
7046                    }
7047                    // Try to get the status from User settings first
7048                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7049                    int status = (int)(packedStatus >> 32);
7050                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7051                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7052                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7053                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7054                                    + " : linkgen=" + linkGeneration);
7055                        }
7056                        // Use link-enabled generation as preferredOrder, i.e.
7057                        // prefer newly-enabled over earlier-enabled.
7058                        info.preferredOrder = linkGeneration;
7059                        alwaysList.add(info);
7060                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7061                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7062                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7063                        }
7064                        neverList.add(info);
7065                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7066                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7067                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7068                        }
7069                        alwaysAskList.add(info);
7070                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7071                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7072                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7073                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7074                        }
7075                        undefinedList.add(info);
7076                    }
7077                }
7078            }
7079
7080            // We'll want to include browser possibilities in a few cases
7081            boolean includeBrowser = false;
7082
7083            // First try to add the "always" resolution(s) for the current user, if any
7084            if (alwaysList.size() > 0) {
7085                result.addAll(alwaysList);
7086            } else {
7087                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7088                result.addAll(undefinedList);
7089                // Maybe add one for the other profile.
7090                if (xpDomainInfo != null && (
7091                        xpDomainInfo.bestDomainVerificationStatus
7092                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7093                    result.add(xpDomainInfo.resolveInfo);
7094                }
7095                includeBrowser = true;
7096            }
7097
7098            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7099            // If there were 'always' entries their preferred order has been set, so we also
7100            // back that off to make the alternatives equivalent
7101            if (alwaysAskList.size() > 0) {
7102                for (ResolveInfo i : result) {
7103                    i.preferredOrder = 0;
7104                }
7105                result.addAll(alwaysAskList);
7106                includeBrowser = true;
7107            }
7108
7109            if (includeBrowser) {
7110                // Also add browsers (all of them or only the default one)
7111                if (DEBUG_DOMAIN_VERIFICATION) {
7112                    Slog.v(TAG, "   ...including browsers in candidate set");
7113                }
7114                if ((matchFlags & MATCH_ALL) != 0) {
7115                    result.addAll(matchAllList);
7116                } else {
7117                    // Browser/generic handling case.  If there's a default browser, go straight
7118                    // to that (but only if there is no other higher-priority match).
7119                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7120                    int maxMatchPrio = 0;
7121                    ResolveInfo defaultBrowserMatch = null;
7122                    final int numCandidates = matchAllList.size();
7123                    for (int n = 0; n < numCandidates; n++) {
7124                        ResolveInfo info = matchAllList.get(n);
7125                        // track the highest overall match priority...
7126                        if (info.priority > maxMatchPrio) {
7127                            maxMatchPrio = info.priority;
7128                        }
7129                        // ...and the highest-priority default browser match
7130                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7131                            if (defaultBrowserMatch == null
7132                                    || (defaultBrowserMatch.priority < info.priority)) {
7133                                if (debug) {
7134                                    Slog.v(TAG, "Considering default browser match " + info);
7135                                }
7136                                defaultBrowserMatch = info;
7137                            }
7138                        }
7139                    }
7140                    if (defaultBrowserMatch != null
7141                            && defaultBrowserMatch.priority >= maxMatchPrio
7142                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7143                    {
7144                        if (debug) {
7145                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7146                        }
7147                        result.add(defaultBrowserMatch);
7148                    } else {
7149                        result.addAll(matchAllList);
7150                    }
7151                }
7152
7153                // If there is nothing selected, add all candidates and remove the ones that the user
7154                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7155                if (result.size() == 0) {
7156                    result.addAll(candidates);
7157                    result.removeAll(neverList);
7158                }
7159            }
7160        }
7161        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7162            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7163                    result.size());
7164            for (ResolveInfo info : result) {
7165                Slog.v(TAG, "  + " + info.activityInfo);
7166            }
7167        }
7168        return result;
7169    }
7170
7171    // Returns a packed value as a long:
7172    //
7173    // high 'int'-sized word: link status: undefined/ask/never/always.
7174    // low 'int'-sized word: relative priority among 'always' results.
7175    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7176        long result = ps.getDomainVerificationStatusForUser(userId);
7177        // if none available, get the master status
7178        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7179            if (ps.getIntentFilterVerificationInfo() != null) {
7180                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7181            }
7182        }
7183        return result;
7184    }
7185
7186    private ResolveInfo querySkipCurrentProfileIntents(
7187            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7188            int flags, int sourceUserId) {
7189        if (matchingFilters != null) {
7190            int size = matchingFilters.size();
7191            for (int i = 0; i < size; i ++) {
7192                CrossProfileIntentFilter filter = matchingFilters.get(i);
7193                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7194                    // Checking if there are activities in the target user that can handle the
7195                    // intent.
7196                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7197                            resolvedType, flags, sourceUserId);
7198                    if (resolveInfo != null) {
7199                        return resolveInfo;
7200                    }
7201                }
7202            }
7203        }
7204        return null;
7205    }
7206
7207    // Return matching ResolveInfo in target user if any.
7208    private ResolveInfo queryCrossProfileIntents(
7209            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7210            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7211        if (matchingFilters != null) {
7212            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7213            // match the same intent. For performance reasons, it is better not to
7214            // run queryIntent twice for the same userId
7215            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7216            int size = matchingFilters.size();
7217            for (int i = 0; i < size; i++) {
7218                CrossProfileIntentFilter filter = matchingFilters.get(i);
7219                int targetUserId = filter.getTargetUserId();
7220                boolean skipCurrentProfile =
7221                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7222                boolean skipCurrentProfileIfNoMatchFound =
7223                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7224                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7225                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7226                    // Checking if there are activities in the target user that can handle the
7227                    // intent.
7228                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7229                            resolvedType, flags, sourceUserId);
7230                    if (resolveInfo != null) return resolveInfo;
7231                    alreadyTriedUserIds.put(targetUserId, true);
7232                }
7233            }
7234        }
7235        return null;
7236    }
7237
7238    /**
7239     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7240     * will forward the intent to the filter's target user.
7241     * Otherwise, returns null.
7242     */
7243    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7244            String resolvedType, int flags, int sourceUserId) {
7245        int targetUserId = filter.getTargetUserId();
7246        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7247                resolvedType, flags, targetUserId);
7248        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7249            // If all the matches in the target profile are suspended, return null.
7250            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7251                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7252                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7253                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7254                            targetUserId);
7255                }
7256            }
7257        }
7258        return null;
7259    }
7260
7261    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7262            int sourceUserId, int targetUserId) {
7263        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7264        long ident = Binder.clearCallingIdentity();
7265        boolean targetIsProfile;
7266        try {
7267            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7268        } finally {
7269            Binder.restoreCallingIdentity(ident);
7270        }
7271        String className;
7272        if (targetIsProfile) {
7273            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7274        } else {
7275            className = FORWARD_INTENT_TO_PARENT;
7276        }
7277        ComponentName forwardingActivityComponentName = new ComponentName(
7278                mAndroidApplication.packageName, className);
7279        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7280                sourceUserId);
7281        if (!targetIsProfile) {
7282            forwardingActivityInfo.showUserIcon = targetUserId;
7283            forwardingResolveInfo.noResourceId = true;
7284        }
7285        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7286        forwardingResolveInfo.priority = 0;
7287        forwardingResolveInfo.preferredOrder = 0;
7288        forwardingResolveInfo.match = 0;
7289        forwardingResolveInfo.isDefault = true;
7290        forwardingResolveInfo.filter = filter;
7291        forwardingResolveInfo.targetUserId = targetUserId;
7292        return forwardingResolveInfo;
7293    }
7294
7295    @Override
7296    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7297            Intent[] specifics, String[] specificTypes, Intent intent,
7298            String resolvedType, int flags, int userId) {
7299        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7300                specificTypes, intent, resolvedType, flags, userId));
7301    }
7302
7303    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7304            Intent[] specifics, String[] specificTypes, Intent intent,
7305            String resolvedType, int flags, int userId) {
7306        if (!sUserManager.exists(userId)) return Collections.emptyList();
7307        final int callingUid = Binder.getCallingUid();
7308        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7309                false /*includeInstantApps*/);
7310        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7311                false /*requireFullPermission*/, false /*checkShell*/,
7312                "query intent activity options");
7313        final String resultsAction = intent.getAction();
7314
7315        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7316                | PackageManager.GET_RESOLVED_FILTER, userId);
7317
7318        if (DEBUG_INTENT_MATCHING) {
7319            Log.v(TAG, "Query " + intent + ": " + results);
7320        }
7321
7322        int specificsPos = 0;
7323        int N;
7324
7325        // todo: note that the algorithm used here is O(N^2).  This
7326        // isn't a problem in our current environment, but if we start running
7327        // into situations where we have more than 5 or 10 matches then this
7328        // should probably be changed to something smarter...
7329
7330        // First we go through and resolve each of the specific items
7331        // that were supplied, taking care of removing any corresponding
7332        // duplicate items in the generic resolve list.
7333        if (specifics != null) {
7334            for (int i=0; i<specifics.length; i++) {
7335                final Intent sintent = specifics[i];
7336                if (sintent == null) {
7337                    continue;
7338                }
7339
7340                if (DEBUG_INTENT_MATCHING) {
7341                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7342                }
7343
7344                String action = sintent.getAction();
7345                if (resultsAction != null && resultsAction.equals(action)) {
7346                    // If this action was explicitly requested, then don't
7347                    // remove things that have it.
7348                    action = null;
7349                }
7350
7351                ResolveInfo ri = null;
7352                ActivityInfo ai = null;
7353
7354                ComponentName comp = sintent.getComponent();
7355                if (comp == null) {
7356                    ri = resolveIntent(
7357                        sintent,
7358                        specificTypes != null ? specificTypes[i] : null,
7359                            flags, userId);
7360                    if (ri == null) {
7361                        continue;
7362                    }
7363                    if (ri == mResolveInfo) {
7364                        // ACK!  Must do something better with this.
7365                    }
7366                    ai = ri.activityInfo;
7367                    comp = new ComponentName(ai.applicationInfo.packageName,
7368                            ai.name);
7369                } else {
7370                    ai = getActivityInfo(comp, flags, userId);
7371                    if (ai == null) {
7372                        continue;
7373                    }
7374                }
7375
7376                // Look for any generic query activities that are duplicates
7377                // of this specific one, and remove them from the results.
7378                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7379                N = results.size();
7380                int j;
7381                for (j=specificsPos; j<N; j++) {
7382                    ResolveInfo sri = results.get(j);
7383                    if ((sri.activityInfo.name.equals(comp.getClassName())
7384                            && sri.activityInfo.applicationInfo.packageName.equals(
7385                                    comp.getPackageName()))
7386                        || (action != null && sri.filter.matchAction(action))) {
7387                        results.remove(j);
7388                        if (DEBUG_INTENT_MATCHING) Log.v(
7389                            TAG, "Removing duplicate item from " + j
7390                            + " due to specific " + specificsPos);
7391                        if (ri == null) {
7392                            ri = sri;
7393                        }
7394                        j--;
7395                        N--;
7396                    }
7397                }
7398
7399                // Add this specific item to its proper place.
7400                if (ri == null) {
7401                    ri = new ResolveInfo();
7402                    ri.activityInfo = ai;
7403                }
7404                results.add(specificsPos, ri);
7405                ri.specificIndex = i;
7406                specificsPos++;
7407            }
7408        }
7409
7410        // Now we go through the remaining generic results and remove any
7411        // duplicate actions that are found here.
7412        N = results.size();
7413        for (int i=specificsPos; i<N-1; i++) {
7414            final ResolveInfo rii = results.get(i);
7415            if (rii.filter == null) {
7416                continue;
7417            }
7418
7419            // Iterate over all of the actions of this result's intent
7420            // filter...  typically this should be just one.
7421            final Iterator<String> it = rii.filter.actionsIterator();
7422            if (it == null) {
7423                continue;
7424            }
7425            while (it.hasNext()) {
7426                final String action = it.next();
7427                if (resultsAction != null && resultsAction.equals(action)) {
7428                    // If this action was explicitly requested, then don't
7429                    // remove things that have it.
7430                    continue;
7431                }
7432                for (int j=i+1; j<N; j++) {
7433                    final ResolveInfo rij = results.get(j);
7434                    if (rij.filter != null && rij.filter.hasAction(action)) {
7435                        results.remove(j);
7436                        if (DEBUG_INTENT_MATCHING) Log.v(
7437                            TAG, "Removing duplicate item from " + j
7438                            + " due to action " + action + " at " + i);
7439                        j--;
7440                        N--;
7441                    }
7442                }
7443            }
7444
7445            // If the caller didn't request filter information, drop it now
7446            // so we don't have to marshall/unmarshall it.
7447            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7448                rii.filter = null;
7449            }
7450        }
7451
7452        // Filter out the caller activity if so requested.
7453        if (caller != null) {
7454            N = results.size();
7455            for (int i=0; i<N; i++) {
7456                ActivityInfo ainfo = results.get(i).activityInfo;
7457                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7458                        && caller.getClassName().equals(ainfo.name)) {
7459                    results.remove(i);
7460                    break;
7461                }
7462            }
7463        }
7464
7465        // If the caller didn't request filter information,
7466        // drop them now so we don't have to
7467        // marshall/unmarshall it.
7468        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7469            N = results.size();
7470            for (int i=0; i<N; i++) {
7471                results.get(i).filter = null;
7472            }
7473        }
7474
7475        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7476        return results;
7477    }
7478
7479    @Override
7480    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7481            String resolvedType, int flags, int userId) {
7482        return new ParceledListSlice<>(
7483                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7484                        false /*allowDynamicSplits*/));
7485    }
7486
7487    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7488            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7489        if (!sUserManager.exists(userId)) return Collections.emptyList();
7490        final int callingUid = Binder.getCallingUid();
7491        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7492                false /*requireFullPermission*/, false /*checkShell*/,
7493                "query intent receivers");
7494        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7495        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7496                false /*includeInstantApps*/);
7497        ComponentName comp = intent.getComponent();
7498        if (comp == null) {
7499            if (intent.getSelector() != null) {
7500                intent = intent.getSelector();
7501                comp = intent.getComponent();
7502            }
7503        }
7504        if (comp != null) {
7505            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7506            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7507            if (ai != null) {
7508                // When specifying an explicit component, we prevent the activity from being
7509                // used when either 1) the calling package is normal and the activity is within
7510                // an instant application or 2) the calling package is ephemeral and the
7511                // activity is not visible to instant applications.
7512                final boolean matchInstantApp =
7513                        (flags & PackageManager.MATCH_INSTANT) != 0;
7514                final boolean matchVisibleToInstantAppOnly =
7515                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7516                final boolean matchExplicitlyVisibleOnly =
7517                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7518                final boolean isCallerInstantApp =
7519                        instantAppPkgName != null;
7520                final boolean isTargetSameInstantApp =
7521                        comp.getPackageName().equals(instantAppPkgName);
7522                final boolean isTargetInstantApp =
7523                        (ai.applicationInfo.privateFlags
7524                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7525                final boolean isTargetVisibleToInstantApp =
7526                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7527                final boolean isTargetExplicitlyVisibleToInstantApp =
7528                        isTargetVisibleToInstantApp
7529                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7530                final boolean isTargetHiddenFromInstantApp =
7531                        !isTargetVisibleToInstantApp
7532                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7533                final boolean blockResolution =
7534                        !isTargetSameInstantApp
7535                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7536                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7537                                        && isTargetHiddenFromInstantApp));
7538                if (!blockResolution) {
7539                    ResolveInfo ri = new ResolveInfo();
7540                    ri.activityInfo = ai;
7541                    list.add(ri);
7542                }
7543            }
7544            return applyPostResolutionFilter(
7545                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7546        }
7547
7548        // reader
7549        synchronized (mPackages) {
7550            String pkgName = intent.getPackage();
7551            if (pkgName == null) {
7552                final List<ResolveInfo> result =
7553                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7554                return applyPostResolutionFilter(
7555                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7556            }
7557            final PackageParser.Package pkg = mPackages.get(pkgName);
7558            if (pkg != null) {
7559                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7560                        intent, resolvedType, flags, pkg.receivers, userId);
7561                return applyPostResolutionFilter(
7562                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7563            }
7564            return Collections.emptyList();
7565        }
7566    }
7567
7568    @Override
7569    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7570        final int callingUid = Binder.getCallingUid();
7571        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7572    }
7573
7574    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7575            int userId, int callingUid) {
7576        if (!sUserManager.exists(userId)) return null;
7577        flags = updateFlagsForResolve(
7578                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7579        List<ResolveInfo> query = queryIntentServicesInternal(
7580                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7581        if (query != null) {
7582            if (query.size() >= 1) {
7583                // If there is more than one service with the same priority,
7584                // just arbitrarily pick the first one.
7585                return query.get(0);
7586            }
7587        }
7588        return null;
7589    }
7590
7591    @Override
7592    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7593            String resolvedType, int flags, int userId) {
7594        final int callingUid = Binder.getCallingUid();
7595        return new ParceledListSlice<>(queryIntentServicesInternal(
7596                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7597    }
7598
7599    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7600            String resolvedType, int flags, int userId, int callingUid,
7601            boolean includeInstantApps) {
7602        if (!sUserManager.exists(userId)) return Collections.emptyList();
7603        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7604                false /*requireFullPermission*/, false /*checkShell*/,
7605                "query intent receivers");
7606        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7607        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7608        ComponentName comp = intent.getComponent();
7609        if (comp == null) {
7610            if (intent.getSelector() != null) {
7611                intent = intent.getSelector();
7612                comp = intent.getComponent();
7613            }
7614        }
7615        if (comp != null) {
7616            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7617            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7618            if (si != null) {
7619                // When specifying an explicit component, we prevent the service from being
7620                // used when either 1) the service is in an instant application and the
7621                // caller is not the same instant application or 2) the calling package is
7622                // ephemeral and the activity is not visible to ephemeral applications.
7623                final boolean matchInstantApp =
7624                        (flags & PackageManager.MATCH_INSTANT) != 0;
7625                final boolean matchVisibleToInstantAppOnly =
7626                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7627                final boolean isCallerInstantApp =
7628                        instantAppPkgName != null;
7629                final boolean isTargetSameInstantApp =
7630                        comp.getPackageName().equals(instantAppPkgName);
7631                final boolean isTargetInstantApp =
7632                        (si.applicationInfo.privateFlags
7633                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7634                final boolean isTargetHiddenFromInstantApp =
7635                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7636                final boolean blockResolution =
7637                        !isTargetSameInstantApp
7638                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7639                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7640                                        && isTargetHiddenFromInstantApp));
7641                if (!blockResolution) {
7642                    final ResolveInfo ri = new ResolveInfo();
7643                    ri.serviceInfo = si;
7644                    list.add(ri);
7645                }
7646            }
7647            return list;
7648        }
7649
7650        // reader
7651        synchronized (mPackages) {
7652            String pkgName = intent.getPackage();
7653            if (pkgName == null) {
7654                return applyPostServiceResolutionFilter(
7655                        mServices.queryIntent(intent, resolvedType, flags, userId),
7656                        instantAppPkgName);
7657            }
7658            final PackageParser.Package pkg = mPackages.get(pkgName);
7659            if (pkg != null) {
7660                return applyPostServiceResolutionFilter(
7661                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7662                                userId),
7663                        instantAppPkgName);
7664            }
7665            return Collections.emptyList();
7666        }
7667    }
7668
7669    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7670            String instantAppPkgName) {
7671        if (instantAppPkgName == null) {
7672            return resolveInfos;
7673        }
7674        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7675            final ResolveInfo info = resolveInfos.get(i);
7676            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7677            // allow services that are defined in the provided package
7678            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7679                if (info.serviceInfo.splitName != null
7680                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7681                                info.serviceInfo.splitName)) {
7682                    // requested service is defined in a split that hasn't been installed yet.
7683                    // add the installer to the resolve list
7684                    if (DEBUG_INSTANT) {
7685                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7686                    }
7687                    final ResolveInfo installerInfo = new ResolveInfo(
7688                            mInstantAppInstallerInfo);
7689                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7690                            null /* installFailureActivity */,
7691                            info.serviceInfo.packageName,
7692                            info.serviceInfo.applicationInfo.versionCode,
7693                            info.serviceInfo.splitName);
7694                    // add a non-generic filter
7695                    installerInfo.filter = new IntentFilter();
7696                    // load resources from the correct package
7697                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7698                    resolveInfos.set(i, installerInfo);
7699                }
7700                continue;
7701            }
7702            // allow services that have been explicitly exposed to ephemeral apps
7703            if (!isEphemeralApp
7704                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7705                continue;
7706            }
7707            resolveInfos.remove(i);
7708        }
7709        return resolveInfos;
7710    }
7711
7712    @Override
7713    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7714            String resolvedType, int flags, int userId) {
7715        return new ParceledListSlice<>(
7716                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7717    }
7718
7719    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7720            Intent intent, String resolvedType, int flags, int userId) {
7721        if (!sUserManager.exists(userId)) return Collections.emptyList();
7722        final int callingUid = Binder.getCallingUid();
7723        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7724        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7725                false /*includeInstantApps*/);
7726        ComponentName comp = intent.getComponent();
7727        if (comp == null) {
7728            if (intent.getSelector() != null) {
7729                intent = intent.getSelector();
7730                comp = intent.getComponent();
7731            }
7732        }
7733        if (comp != null) {
7734            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7735            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7736            if (pi != null) {
7737                // When specifying an explicit component, we prevent the provider from being
7738                // used when either 1) the provider is in an instant application and the
7739                // caller is not the same instant application or 2) the calling package is an
7740                // instant application and the provider is not visible to instant applications.
7741                final boolean matchInstantApp =
7742                        (flags & PackageManager.MATCH_INSTANT) != 0;
7743                final boolean matchVisibleToInstantAppOnly =
7744                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7745                final boolean isCallerInstantApp =
7746                        instantAppPkgName != null;
7747                final boolean isTargetSameInstantApp =
7748                        comp.getPackageName().equals(instantAppPkgName);
7749                final boolean isTargetInstantApp =
7750                        (pi.applicationInfo.privateFlags
7751                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7752                final boolean isTargetHiddenFromInstantApp =
7753                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7754                final boolean blockResolution =
7755                        !isTargetSameInstantApp
7756                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7757                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7758                                        && isTargetHiddenFromInstantApp));
7759                if (!blockResolution) {
7760                    final ResolveInfo ri = new ResolveInfo();
7761                    ri.providerInfo = pi;
7762                    list.add(ri);
7763                }
7764            }
7765            return list;
7766        }
7767
7768        // reader
7769        synchronized (mPackages) {
7770            String pkgName = intent.getPackage();
7771            if (pkgName == null) {
7772                return applyPostContentProviderResolutionFilter(
7773                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7774                        instantAppPkgName);
7775            }
7776            final PackageParser.Package pkg = mPackages.get(pkgName);
7777            if (pkg != null) {
7778                return applyPostContentProviderResolutionFilter(
7779                        mProviders.queryIntentForPackage(
7780                        intent, resolvedType, flags, pkg.providers, userId),
7781                        instantAppPkgName);
7782            }
7783            return Collections.emptyList();
7784        }
7785    }
7786
7787    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7788            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7789        if (instantAppPkgName == null) {
7790            return resolveInfos;
7791        }
7792        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7793            final ResolveInfo info = resolveInfos.get(i);
7794            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7795            // allow providers that are defined in the provided package
7796            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7797                if (info.providerInfo.splitName != null
7798                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7799                                info.providerInfo.splitName)) {
7800                    // requested provider is defined in a split that hasn't been installed yet.
7801                    // add the installer to the resolve list
7802                    if (DEBUG_INSTANT) {
7803                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7804                    }
7805                    final ResolveInfo installerInfo = new ResolveInfo(
7806                            mInstantAppInstallerInfo);
7807                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7808                            null /*failureActivity*/,
7809                            info.providerInfo.packageName,
7810                            info.providerInfo.applicationInfo.versionCode,
7811                            info.providerInfo.splitName);
7812                    // add a non-generic filter
7813                    installerInfo.filter = new IntentFilter();
7814                    // load resources from the correct package
7815                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7816                    resolveInfos.set(i, installerInfo);
7817                }
7818                continue;
7819            }
7820            // allow providers that have been explicitly exposed to instant applications
7821            if (!isEphemeralApp
7822                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7823                continue;
7824            }
7825            resolveInfos.remove(i);
7826        }
7827        return resolveInfos;
7828    }
7829
7830    @Override
7831    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7832        final int callingUid = Binder.getCallingUid();
7833        if (getInstantAppPackageName(callingUid) != null) {
7834            return ParceledListSlice.emptyList();
7835        }
7836        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7837        flags = updateFlagsForPackage(flags, userId, null);
7838        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7839        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7840                true /* requireFullPermission */, false /* checkShell */,
7841                "get installed packages");
7842
7843        // writer
7844        synchronized (mPackages) {
7845            ArrayList<PackageInfo> list;
7846            if (listUninstalled) {
7847                list = new ArrayList<>(mSettings.mPackages.size());
7848                for (PackageSetting ps : mSettings.mPackages.values()) {
7849                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7850                        continue;
7851                    }
7852                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7853                        continue;
7854                    }
7855                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7856                    if (pi != null) {
7857                        list.add(pi);
7858                    }
7859                }
7860            } else {
7861                list = new ArrayList<>(mPackages.size());
7862                for (PackageParser.Package p : mPackages.values()) {
7863                    final PackageSetting ps = (PackageSetting) p.mExtras;
7864                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7865                        continue;
7866                    }
7867                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7868                        continue;
7869                    }
7870                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7871                            p.mExtras, flags, userId);
7872                    if (pi != null) {
7873                        list.add(pi);
7874                    }
7875                }
7876            }
7877
7878            return new ParceledListSlice<>(list);
7879        }
7880    }
7881
7882    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7883            String[] permissions, boolean[] tmp, int flags, int userId) {
7884        int numMatch = 0;
7885        final PermissionsState permissionsState = ps.getPermissionsState();
7886        for (int i=0; i<permissions.length; i++) {
7887            final String permission = permissions[i];
7888            if (permissionsState.hasPermission(permission, userId)) {
7889                tmp[i] = true;
7890                numMatch++;
7891            } else {
7892                tmp[i] = false;
7893            }
7894        }
7895        if (numMatch == 0) {
7896            return;
7897        }
7898        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7899
7900        // The above might return null in cases of uninstalled apps or install-state
7901        // skew across users/profiles.
7902        if (pi != null) {
7903            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7904                if (numMatch == permissions.length) {
7905                    pi.requestedPermissions = permissions;
7906                } else {
7907                    pi.requestedPermissions = new String[numMatch];
7908                    numMatch = 0;
7909                    for (int i=0; i<permissions.length; i++) {
7910                        if (tmp[i]) {
7911                            pi.requestedPermissions[numMatch] = permissions[i];
7912                            numMatch++;
7913                        }
7914                    }
7915                }
7916            }
7917            list.add(pi);
7918        }
7919    }
7920
7921    @Override
7922    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7923            String[] permissions, int flags, int userId) {
7924        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7925        flags = updateFlagsForPackage(flags, userId, permissions);
7926        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7927                true /* requireFullPermission */, false /* checkShell */,
7928                "get packages holding permissions");
7929        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7930
7931        // writer
7932        synchronized (mPackages) {
7933            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7934            boolean[] tmpBools = new boolean[permissions.length];
7935            if (listUninstalled) {
7936                for (PackageSetting ps : mSettings.mPackages.values()) {
7937                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7938                            userId);
7939                }
7940            } else {
7941                for (PackageParser.Package pkg : mPackages.values()) {
7942                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7943                    if (ps != null) {
7944                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7945                                userId);
7946                    }
7947                }
7948            }
7949
7950            return new ParceledListSlice<PackageInfo>(list);
7951        }
7952    }
7953
7954    @Override
7955    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7956        final int callingUid = Binder.getCallingUid();
7957        if (getInstantAppPackageName(callingUid) != null) {
7958            return ParceledListSlice.emptyList();
7959        }
7960        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7961        flags = updateFlagsForApplication(flags, userId, null);
7962        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7963
7964        // writer
7965        synchronized (mPackages) {
7966            ArrayList<ApplicationInfo> list;
7967            if (listUninstalled) {
7968                list = new ArrayList<>(mSettings.mPackages.size());
7969                for (PackageSetting ps : mSettings.mPackages.values()) {
7970                    ApplicationInfo ai;
7971                    int effectiveFlags = flags;
7972                    if (ps.isSystem()) {
7973                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7974                    }
7975                    if (ps.pkg != null) {
7976                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7977                            continue;
7978                        }
7979                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7980                            continue;
7981                        }
7982                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7983                                ps.readUserState(userId), userId);
7984                        if (ai != null) {
7985                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7986                        }
7987                    } else {
7988                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7989                        // and already converts to externally visible package name
7990                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7991                                callingUid, effectiveFlags, userId);
7992                    }
7993                    if (ai != null) {
7994                        list.add(ai);
7995                    }
7996                }
7997            } else {
7998                list = new ArrayList<>(mPackages.size());
7999                for (PackageParser.Package p : mPackages.values()) {
8000                    if (p.mExtras != null) {
8001                        PackageSetting ps = (PackageSetting) p.mExtras;
8002                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8003                            continue;
8004                        }
8005                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8006                            continue;
8007                        }
8008                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8009                                ps.readUserState(userId), userId);
8010                        if (ai != null) {
8011                            ai.packageName = resolveExternalPackageNameLPr(p);
8012                            list.add(ai);
8013                        }
8014                    }
8015                }
8016            }
8017
8018            return new ParceledListSlice<>(list);
8019        }
8020    }
8021
8022    @Override
8023    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8024        if (HIDE_EPHEMERAL_APIS) {
8025            return null;
8026        }
8027        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8028            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8029                    "getEphemeralApplications");
8030        }
8031        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8032                true /* requireFullPermission */, false /* checkShell */,
8033                "getEphemeralApplications");
8034        synchronized (mPackages) {
8035            List<InstantAppInfo> instantApps = mInstantAppRegistry
8036                    .getInstantAppsLPr(userId);
8037            if (instantApps != null) {
8038                return new ParceledListSlice<>(instantApps);
8039            }
8040        }
8041        return null;
8042    }
8043
8044    @Override
8045    public boolean isInstantApp(String packageName, int userId) {
8046        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8047                true /* requireFullPermission */, false /* checkShell */,
8048                "isInstantApp");
8049        if (HIDE_EPHEMERAL_APIS) {
8050            return false;
8051        }
8052
8053        synchronized (mPackages) {
8054            int callingUid = Binder.getCallingUid();
8055            if (Process.isIsolated(callingUid)) {
8056                callingUid = mIsolatedOwners.get(callingUid);
8057            }
8058            final PackageSetting ps = mSettings.mPackages.get(packageName);
8059            PackageParser.Package pkg = mPackages.get(packageName);
8060            final boolean returnAllowed =
8061                    ps != null
8062                    && (isCallerSameApp(packageName, callingUid)
8063                            || canViewInstantApps(callingUid, userId)
8064                            || mInstantAppRegistry.isInstantAccessGranted(
8065                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8066            if (returnAllowed) {
8067                return ps.getInstantApp(userId);
8068            }
8069        }
8070        return false;
8071    }
8072
8073    @Override
8074    public byte[] getInstantAppCookie(String packageName, int userId) {
8075        if (HIDE_EPHEMERAL_APIS) {
8076            return null;
8077        }
8078
8079        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8080                true /* requireFullPermission */, false /* checkShell */,
8081                "getInstantAppCookie");
8082        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8083            return null;
8084        }
8085        synchronized (mPackages) {
8086            return mInstantAppRegistry.getInstantAppCookieLPw(
8087                    packageName, userId);
8088        }
8089    }
8090
8091    @Override
8092    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8093        if (HIDE_EPHEMERAL_APIS) {
8094            return true;
8095        }
8096
8097        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8098                true /* requireFullPermission */, true /* checkShell */,
8099                "setInstantAppCookie");
8100        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8101            return false;
8102        }
8103        synchronized (mPackages) {
8104            return mInstantAppRegistry.setInstantAppCookieLPw(
8105                    packageName, cookie, userId);
8106        }
8107    }
8108
8109    @Override
8110    public Bitmap getInstantAppIcon(String packageName, int userId) {
8111        if (HIDE_EPHEMERAL_APIS) {
8112            return null;
8113        }
8114
8115        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8116            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8117                    "getInstantAppIcon");
8118        }
8119        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8120                true /* requireFullPermission */, false /* checkShell */,
8121                "getInstantAppIcon");
8122
8123        synchronized (mPackages) {
8124            return mInstantAppRegistry.getInstantAppIconLPw(
8125                    packageName, userId);
8126        }
8127    }
8128
8129    private boolean isCallerSameApp(String packageName, int uid) {
8130        PackageParser.Package pkg = mPackages.get(packageName);
8131        return pkg != null
8132                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8133    }
8134
8135    @Override
8136    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8137        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8138            return ParceledListSlice.emptyList();
8139        }
8140        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8141    }
8142
8143    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8144        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8145
8146        // reader
8147        synchronized (mPackages) {
8148            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8149            final int userId = UserHandle.getCallingUserId();
8150            while (i.hasNext()) {
8151                final PackageParser.Package p = i.next();
8152                if (p.applicationInfo == null) continue;
8153
8154                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8155                        && !p.applicationInfo.isDirectBootAware();
8156                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8157                        && p.applicationInfo.isDirectBootAware();
8158
8159                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8160                        && (!mSafeMode || isSystemApp(p))
8161                        && (matchesUnaware || matchesAware)) {
8162                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8163                    if (ps != null) {
8164                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8165                                ps.readUserState(userId), userId);
8166                        if (ai != null) {
8167                            finalList.add(ai);
8168                        }
8169                    }
8170                }
8171            }
8172        }
8173
8174        return finalList;
8175    }
8176
8177    @Override
8178    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8179        return resolveContentProviderInternal(name, flags, userId);
8180    }
8181
8182    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8183        if (!sUserManager.exists(userId)) return null;
8184        flags = updateFlagsForComponent(flags, userId, name);
8185        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8186        // reader
8187        synchronized (mPackages) {
8188            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8189            PackageSetting ps = provider != null
8190                    ? mSettings.mPackages.get(provider.owner.packageName)
8191                    : null;
8192            if (ps != null) {
8193                final boolean isInstantApp = ps.getInstantApp(userId);
8194                // normal application; filter out instant application provider
8195                if (instantAppPkgName == null && isInstantApp) {
8196                    return null;
8197                }
8198                // instant application; filter out other instant applications
8199                if (instantAppPkgName != null
8200                        && isInstantApp
8201                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8202                    return null;
8203                }
8204                // instant application; filter out non-exposed provider
8205                if (instantAppPkgName != null
8206                        && !isInstantApp
8207                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8208                    return null;
8209                }
8210                // provider not enabled
8211                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8212                    return null;
8213                }
8214                return PackageParser.generateProviderInfo(
8215                        provider, flags, ps.readUserState(userId), userId);
8216            }
8217            return null;
8218        }
8219    }
8220
8221    /**
8222     * @deprecated
8223     */
8224    @Deprecated
8225    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8226        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8227            return;
8228        }
8229        // reader
8230        synchronized (mPackages) {
8231            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8232                    .entrySet().iterator();
8233            final int userId = UserHandle.getCallingUserId();
8234            while (i.hasNext()) {
8235                Map.Entry<String, PackageParser.Provider> entry = i.next();
8236                PackageParser.Provider p = entry.getValue();
8237                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8238
8239                if (ps != null && p.syncable
8240                        && (!mSafeMode || (p.info.applicationInfo.flags
8241                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8242                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8243                            ps.readUserState(userId), userId);
8244                    if (info != null) {
8245                        outNames.add(entry.getKey());
8246                        outInfo.add(info);
8247                    }
8248                }
8249            }
8250        }
8251    }
8252
8253    @Override
8254    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8255            int uid, int flags, String metaDataKey) {
8256        final int callingUid = Binder.getCallingUid();
8257        final int userId = processName != null ? UserHandle.getUserId(uid)
8258                : UserHandle.getCallingUserId();
8259        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8260        flags = updateFlagsForComponent(flags, userId, processName);
8261        ArrayList<ProviderInfo> finalList = null;
8262        // reader
8263        synchronized (mPackages) {
8264            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8265            while (i.hasNext()) {
8266                final PackageParser.Provider p = i.next();
8267                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8268                if (ps != null && p.info.authority != null
8269                        && (processName == null
8270                                || (p.info.processName.equals(processName)
8271                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8272                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8273
8274                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8275                    // parameter.
8276                    if (metaDataKey != null
8277                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8278                        continue;
8279                    }
8280                    final ComponentName component =
8281                            new ComponentName(p.info.packageName, p.info.name);
8282                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8283                        continue;
8284                    }
8285                    if (finalList == null) {
8286                        finalList = new ArrayList<ProviderInfo>(3);
8287                    }
8288                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8289                            ps.readUserState(userId), userId);
8290                    if (info != null) {
8291                        finalList.add(info);
8292                    }
8293                }
8294            }
8295        }
8296
8297        if (finalList != null) {
8298            Collections.sort(finalList, mProviderInitOrderSorter);
8299            return new ParceledListSlice<ProviderInfo>(finalList);
8300        }
8301
8302        return ParceledListSlice.emptyList();
8303    }
8304
8305    @Override
8306    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8307        // reader
8308        synchronized (mPackages) {
8309            final int callingUid = Binder.getCallingUid();
8310            final int callingUserId = UserHandle.getUserId(callingUid);
8311            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8312            if (ps == null) return null;
8313            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8314                return null;
8315            }
8316            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8317            return PackageParser.generateInstrumentationInfo(i, flags);
8318        }
8319    }
8320
8321    @Override
8322    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8323            String targetPackage, int flags) {
8324        final int callingUid = Binder.getCallingUid();
8325        final int callingUserId = UserHandle.getUserId(callingUid);
8326        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8327        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8328            return ParceledListSlice.emptyList();
8329        }
8330        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8331    }
8332
8333    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8334            int flags) {
8335        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8336
8337        // reader
8338        synchronized (mPackages) {
8339            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8340            while (i.hasNext()) {
8341                final PackageParser.Instrumentation p = i.next();
8342                if (targetPackage == null
8343                        || targetPackage.equals(p.info.targetPackage)) {
8344                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8345                            flags);
8346                    if (ii != null) {
8347                        finalList.add(ii);
8348                    }
8349                }
8350            }
8351        }
8352
8353        return finalList;
8354    }
8355
8356    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8357        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8358        try {
8359            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8360        } finally {
8361            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8362        }
8363    }
8364
8365    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8366        final File[] files = scanDir.listFiles();
8367        if (ArrayUtils.isEmpty(files)) {
8368            Log.d(TAG, "No files in app dir " + scanDir);
8369            return;
8370        }
8371
8372        if (DEBUG_PACKAGE_SCANNING) {
8373            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8374                    + " flags=0x" + Integer.toHexString(parseFlags));
8375        }
8376        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8377                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8378                mParallelPackageParserCallback)) {
8379            // Submit files for parsing in parallel
8380            int fileCount = 0;
8381            for (File file : files) {
8382                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8383                        && !PackageInstallerService.isStageName(file.getName());
8384                if (!isPackage) {
8385                    // Ignore entries which are not packages
8386                    continue;
8387                }
8388                parallelPackageParser.submit(file, parseFlags);
8389                fileCount++;
8390            }
8391
8392            // Process results one by one
8393            for (; fileCount > 0; fileCount--) {
8394                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8395                Throwable throwable = parseResult.throwable;
8396                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8397
8398                if (throwable == null) {
8399                    // TODO(toddke): move lower in the scan chain
8400                    // Static shared libraries have synthetic package names
8401                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8402                        renameStaticSharedLibraryPackage(parseResult.pkg);
8403                    }
8404                    try {
8405                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8406                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8407                                    currentTime, null);
8408                        }
8409                    } catch (PackageManagerException e) {
8410                        errorCode = e.error;
8411                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8412                    }
8413                } else if (throwable instanceof PackageParser.PackageParserException) {
8414                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8415                            throwable;
8416                    errorCode = e.error;
8417                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8418                } else {
8419                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8420                            + parseResult.scanFile, throwable);
8421                }
8422
8423                // Delete invalid userdata apps
8424                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8425                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8426                    logCriticalInfo(Log.WARN,
8427                            "Deleting invalid package at " + parseResult.scanFile);
8428                    removeCodePathLI(parseResult.scanFile);
8429                }
8430            }
8431        }
8432    }
8433
8434    public static void reportSettingsProblem(int priority, String msg) {
8435        logCriticalInfo(priority, msg);
8436    }
8437
8438    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8439            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8440        // When upgrading from pre-N MR1, verify the package time stamp using the package
8441        // directory and not the APK file.
8442        final long lastModifiedTime = mIsPreNMR1Upgrade
8443                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8444        if (ps != null && !forceCollect
8445                && ps.codePathString.equals(pkg.codePath)
8446                && ps.timeStamp == lastModifiedTime
8447                && !isCompatSignatureUpdateNeeded(pkg)
8448                && !isRecoverSignatureUpdateNeeded(pkg)) {
8449            if (ps.signatures.mSigningDetails.signatures != null
8450                    && ps.signatures.mSigningDetails.signatures.length != 0
8451                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8452                            != SignatureSchemeVersion.UNKNOWN) {
8453                // Optimization: reuse the existing cached signing data
8454                // if the package appears to be unchanged.
8455                pkg.mSigningDetails =
8456                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8457                return;
8458            }
8459
8460            Slog.w(TAG, "PackageSetting for " + ps.name
8461                    + " is missing signatures.  Collecting certs again to recover them.");
8462        } else {
8463            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8464                    (forceCollect ? " (forced)" : ""));
8465        }
8466
8467        try {
8468            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8469            PackageParser.collectCertificates(pkg, skipVerify);
8470        } catch (PackageParserException e) {
8471            throw PackageManagerException.from(e);
8472        } finally {
8473            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8474        }
8475    }
8476
8477    /**
8478     *  Traces a package scan.
8479     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8480     */
8481    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8482            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8483        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8484        try {
8485            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8486        } finally {
8487            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8488        }
8489    }
8490
8491    /**
8492     *  Scans a package and returns the newly parsed package.
8493     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8494     */
8495    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8496            long currentTime, UserHandle user) throws PackageManagerException {
8497        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8498        PackageParser pp = new PackageParser();
8499        pp.setSeparateProcesses(mSeparateProcesses);
8500        pp.setOnlyCoreApps(mOnlyCore);
8501        pp.setDisplayMetrics(mMetrics);
8502        pp.setCallback(mPackageParserCallback);
8503
8504        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8505        final PackageParser.Package pkg;
8506        try {
8507            pkg = pp.parsePackage(scanFile, parseFlags);
8508        } catch (PackageParserException e) {
8509            throw PackageManagerException.from(e);
8510        } finally {
8511            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8512        }
8513
8514        // Static shared libraries have synthetic package names
8515        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8516            renameStaticSharedLibraryPackage(pkg);
8517        }
8518
8519        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8520    }
8521
8522    /**
8523     *  Scans a package and returns the newly parsed package.
8524     *  @throws PackageManagerException on a parse error.
8525     */
8526    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8527            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8528            @Nullable UserHandle user)
8529                    throws PackageManagerException {
8530        // If the package has children and this is the first dive in the function
8531        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8532        // packages (parent and children) would be successfully scanned before the
8533        // actual scan since scanning mutates internal state and we want to atomically
8534        // install the package and its children.
8535        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8536            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8537                scanFlags |= SCAN_CHECK_ONLY;
8538            }
8539        } else {
8540            scanFlags &= ~SCAN_CHECK_ONLY;
8541        }
8542
8543        // Scan the parent
8544        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8545                scanFlags, currentTime, user);
8546
8547        // Scan the children
8548        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8549        for (int i = 0; i < childCount; i++) {
8550            PackageParser.Package childPackage = pkg.childPackages.get(i);
8551            addForInitLI(childPackage, parseFlags, scanFlags,
8552                    currentTime, user);
8553        }
8554
8555
8556        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8557            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8558        }
8559
8560        return scannedPkg;
8561    }
8562
8563    /**
8564     * Returns if full apk verification can be skipped for the whole package, including the splits.
8565     */
8566    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8567        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8568            return false;
8569        }
8570        // TODO: Allow base and splits to be verified individually.
8571        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8572            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8573                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8574                    return false;
8575                }
8576            }
8577        }
8578        return true;
8579    }
8580
8581    /**
8582     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8583     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8584     * match one in a trusted source, and should be done separately.
8585     */
8586    private boolean canSkipFullApkVerification(String apkPath) {
8587        byte[] rootHashObserved = null;
8588        try {
8589            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8590            if (rootHashObserved == null) {
8591                return false;  // APK does not contain Merkle tree root hash.
8592            }
8593            synchronized (mInstallLock) {
8594                // Returns whether the observed root hash matches what kernel has.
8595                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8596                return true;
8597            }
8598        } catch (InstallerException | IOException | DigestException |
8599                NoSuchAlgorithmException e) {
8600            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8601        }
8602        return false;
8603    }
8604
8605    /**
8606     * Adds a new package to the internal data structures during platform initialization.
8607     * <p>After adding, the package is known to the system and available for querying.
8608     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8609     * etc...], additional checks are performed. Basic verification [such as ensuring
8610     * matching signatures, checking version codes, etc...] occurs if the package is
8611     * identical to a previously known package. If the package fails a signature check,
8612     * the version installed on /data will be removed. If the version of the new package
8613     * is less than or equal than the version on /data, it will be ignored.
8614     * <p>Regardless of the package location, the results are applied to the internal
8615     * structures and the package is made available to the rest of the system.
8616     * <p>NOTE: The return value should be removed. It's the passed in package object.
8617     */
8618    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8619            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8620            @Nullable UserHandle user)
8621                    throws PackageManagerException {
8622        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8623        final String renamedPkgName;
8624        final PackageSetting disabledPkgSetting;
8625        final boolean isSystemPkgUpdated;
8626        final boolean pkgAlreadyExists;
8627        PackageSetting pkgSetting;
8628
8629        // NOTE: installPackageLI() has the same code to setup the package's
8630        // application info. This probably should be done lower in the call
8631        // stack [such as scanPackageOnly()]. However, we verify the application
8632        // info prior to that [in scanPackageNew()] and thus have to setup
8633        // the application info early.
8634        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8635        pkg.setApplicationInfoCodePath(pkg.codePath);
8636        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8637        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8638        pkg.setApplicationInfoResourcePath(pkg.codePath);
8639        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8640        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8641
8642        synchronized (mPackages) {
8643            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8644            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8645            if (realPkgName != null) {
8646                ensurePackageRenamed(pkg, renamedPkgName);
8647            }
8648            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8649            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8650            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8651            pkgAlreadyExists = pkgSetting != null;
8652            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8653            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8654            isSystemPkgUpdated = disabledPkgSetting != null;
8655
8656            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8657                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8658            }
8659
8660            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8661                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8662                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8663                    : null;
8664            if (DEBUG_PACKAGE_SCANNING
8665                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8666                    && sharedUserSetting != null) {
8667                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8668                        + " (uid=" + sharedUserSetting.userId + "):"
8669                        + " packages=" + sharedUserSetting.packages);
8670            }
8671
8672            if (scanSystemPartition) {
8673                // Potentially prune child packages. If the application on the /system
8674                // partition has been updated via OTA, but, is still disabled by a
8675                // version on /data, cycle through all of its children packages and
8676                // remove children that are no longer defined.
8677                if (isSystemPkgUpdated) {
8678                    final int scannedChildCount = (pkg.childPackages != null)
8679                            ? pkg.childPackages.size() : 0;
8680                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8681                            ? disabledPkgSetting.childPackageNames.size() : 0;
8682                    for (int i = 0; i < disabledChildCount; i++) {
8683                        String disabledChildPackageName =
8684                                disabledPkgSetting.childPackageNames.get(i);
8685                        boolean disabledPackageAvailable = false;
8686                        for (int j = 0; j < scannedChildCount; j++) {
8687                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8688                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8689                                disabledPackageAvailable = true;
8690                                break;
8691                            }
8692                        }
8693                        if (!disabledPackageAvailable) {
8694                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8695                        }
8696                    }
8697                    // we're updating the disabled package, so, scan it as the package setting
8698                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8699                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8700                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8701                            (pkg == mPlatformPackage), user);
8702                    applyPolicy(pkg, parseFlags, scanFlags);
8703                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8704                }
8705            }
8706        }
8707
8708        final boolean newPkgChangedPaths =
8709                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8710        final boolean newPkgVersionGreater =
8711                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8712        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8713                && newPkgChangedPaths && newPkgVersionGreater;
8714        if (isSystemPkgBetter) {
8715            // The version of the application on /system is greater than the version on
8716            // /data. Switch back to the application on /system.
8717            // It's safe to assume the application on /system will correctly scan. If not,
8718            // there won't be a working copy of the application.
8719            synchronized (mPackages) {
8720                // just remove the loaded entries from package lists
8721                mPackages.remove(pkgSetting.name);
8722            }
8723
8724            logCriticalInfo(Log.WARN,
8725                    "System package updated;"
8726                    + " name: " + pkgSetting.name
8727                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8728                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8729
8730            final InstallArgs args = createInstallArgsForExisting(
8731                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8732                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8733            args.cleanUpResourcesLI();
8734            synchronized (mPackages) {
8735                mSettings.enableSystemPackageLPw(pkgSetting.name);
8736            }
8737        }
8738
8739        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8740            // The version of the application on the /system partition is less than or
8741            // equal to the version on the /data partition. Throw an exception and use
8742            // the application already installed on the /data partition.
8743            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8744                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8745                    + " better than this " + pkg.getLongVersionCode());
8746        }
8747
8748        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8749        // force re-collecting certificate.
8750        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8751                disabledPkgSetting);
8752        // Full APK verification can be skipped during certificate collection, only if the file is
8753        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8754        // cases, only data in Signing Block is verified instead of the whole file.
8755        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8756                (forceCollect && canSkipFullPackageVerification(pkg));
8757        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8758
8759        boolean shouldHideSystemApp = false;
8760        // A new application appeared on /system, but, we already have a copy of
8761        // the application installed on /data.
8762        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8763                && !pkgSetting.isSystem()) {
8764
8765            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8766                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8767                logCriticalInfo(Log.WARN,
8768                        "System package signature mismatch;"
8769                        + " name: " + pkgSetting.name);
8770                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8771                        "scanPackageInternalLI")) {
8772                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8773                }
8774                pkgSetting = null;
8775            } else if (newPkgVersionGreater) {
8776                // The application on /system is newer than the application on /data.
8777                // Simply remove the application on /data [keeping application data]
8778                // and replace it with the version on /system.
8779                logCriticalInfo(Log.WARN,
8780                        "System package enabled;"
8781                        + " name: " + pkgSetting.name
8782                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8783                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8784                InstallArgs args = createInstallArgsForExisting(
8785                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8786                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8787                synchronized (mInstallLock) {
8788                    args.cleanUpResourcesLI();
8789                }
8790            } else {
8791                // The application on /system is older than the application on /data. Hide
8792                // the application on /system and the version on /data will be scanned later
8793                // and re-added like an update.
8794                shouldHideSystemApp = true;
8795                logCriticalInfo(Log.INFO,
8796                        "System package disabled;"
8797                        + " name: " + pkgSetting.name
8798                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8799                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8800            }
8801        }
8802
8803        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8804                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8805
8806        if (shouldHideSystemApp) {
8807            synchronized (mPackages) {
8808                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8809            }
8810        }
8811        return scannedPkg;
8812    }
8813
8814    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8815        // Derive the new package synthetic package name
8816        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8817                + pkg.staticSharedLibVersion);
8818    }
8819
8820    private static String fixProcessName(String defProcessName,
8821            String processName) {
8822        if (processName == null) {
8823            return defProcessName;
8824        }
8825        return processName;
8826    }
8827
8828    /**
8829     * Enforces that only the system UID or root's UID can call a method exposed
8830     * via Binder.
8831     *
8832     * @param message used as message if SecurityException is thrown
8833     * @throws SecurityException if the caller is not system or root
8834     */
8835    private static final void enforceSystemOrRoot(String message) {
8836        final int uid = Binder.getCallingUid();
8837        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8838            throw new SecurityException(message);
8839        }
8840    }
8841
8842    @Override
8843    public void performFstrimIfNeeded() {
8844        enforceSystemOrRoot("Only the system can request fstrim");
8845
8846        // Before everything else, see whether we need to fstrim.
8847        try {
8848            IStorageManager sm = PackageHelper.getStorageManager();
8849            if (sm != null) {
8850                boolean doTrim = false;
8851                final long interval = android.provider.Settings.Global.getLong(
8852                        mContext.getContentResolver(),
8853                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8854                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8855                if (interval > 0) {
8856                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8857                    if (timeSinceLast > interval) {
8858                        doTrim = true;
8859                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8860                                + "; running immediately");
8861                    }
8862                }
8863                if (doTrim) {
8864                    final boolean dexOptDialogShown;
8865                    synchronized (mPackages) {
8866                        dexOptDialogShown = mDexOptDialogShown;
8867                    }
8868                    if (!isFirstBoot() && dexOptDialogShown) {
8869                        try {
8870                            ActivityManager.getService().showBootMessage(
8871                                    mContext.getResources().getString(
8872                                            R.string.android_upgrading_fstrim), true);
8873                        } catch (RemoteException e) {
8874                        }
8875                    }
8876                    sm.runMaintenance();
8877                }
8878            } else {
8879                Slog.e(TAG, "storageManager service unavailable!");
8880            }
8881        } catch (RemoteException e) {
8882            // Can't happen; StorageManagerService is local
8883        }
8884    }
8885
8886    @Override
8887    public void updatePackagesIfNeeded() {
8888        enforceSystemOrRoot("Only the system can request package update");
8889
8890        // We need to re-extract after an OTA.
8891        boolean causeUpgrade = isUpgrade();
8892
8893        // First boot or factory reset.
8894        // Note: we also handle devices that are upgrading to N right now as if it is their
8895        //       first boot, as they do not have profile data.
8896        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8897
8898        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8899        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8900
8901        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8902            return;
8903        }
8904
8905        List<PackageParser.Package> pkgs;
8906        synchronized (mPackages) {
8907            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8908        }
8909
8910        final long startTime = System.nanoTime();
8911        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8912                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8913                    false /* bootComplete */);
8914
8915        final int elapsedTimeSeconds =
8916                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8917
8918        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8919        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8920        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8921        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8922        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8923    }
8924
8925    /*
8926     * Return the prebuilt profile path given a package base code path.
8927     */
8928    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8929        return pkg.baseCodePath + ".prof";
8930    }
8931
8932    /**
8933     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8934     * containing statistics about the invocation. The array consists of three elements,
8935     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8936     * and {@code numberOfPackagesFailed}.
8937     */
8938    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8939            final int compilationReason, boolean bootComplete) {
8940
8941        int numberOfPackagesVisited = 0;
8942        int numberOfPackagesOptimized = 0;
8943        int numberOfPackagesSkipped = 0;
8944        int numberOfPackagesFailed = 0;
8945        final int numberOfPackagesToDexopt = pkgs.size();
8946
8947        for (PackageParser.Package pkg : pkgs) {
8948            numberOfPackagesVisited++;
8949
8950            boolean useProfileForDexopt = false;
8951
8952            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8953                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8954                // that are already compiled.
8955                File profileFile = new File(getPrebuildProfilePath(pkg));
8956                // Copy profile if it exists.
8957                if (profileFile.exists()) {
8958                    try {
8959                        // We could also do this lazily before calling dexopt in
8960                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8961                        // is that we don't have a good way to say "do this only once".
8962                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8963                                pkg.applicationInfo.uid, pkg.packageName,
8964                                ArtManager.getProfileName(null))) {
8965                            Log.e(TAG, "Installer failed to copy system profile!");
8966                        } else {
8967                            // Disabled as this causes speed-profile compilation during first boot
8968                            // even if things are already compiled.
8969                            // useProfileForDexopt = true;
8970                        }
8971                    } catch (Exception e) {
8972                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8973                                e);
8974                    }
8975                } else {
8976                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8977                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8978                    // minimize the number off apps being speed-profile compiled during first boot.
8979                    // The other paths will not change the filter.
8980                    if (disabledPs != null && disabledPs.pkg.isStub) {
8981                        // The package is the stub one, remove the stub suffix to get the normal
8982                        // package and APK names.
8983                        String systemProfilePath =
8984                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8985                        profileFile = new File(systemProfilePath);
8986                        // If we have a profile for a compressed APK, copy it to the reference
8987                        // location.
8988                        // Note that copying the profile here will cause it to override the
8989                        // reference profile every OTA even though the existing reference profile
8990                        // may have more data. We can't copy during decompression since the
8991                        // directories are not set up at that point.
8992                        if (profileFile.exists()) {
8993                            try {
8994                                // We could also do this lazily before calling dexopt in
8995                                // PackageDexOptimizer to prevent this happening on first boot. The
8996                                // issue is that we don't have a good way to say "do this only
8997                                // once".
8998                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8999                                        pkg.applicationInfo.uid, pkg.packageName,
9000                                        ArtManager.getProfileName(null))) {
9001                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9002                                } else {
9003                                    useProfileForDexopt = true;
9004                                }
9005                            } catch (Exception e) {
9006                                Log.e(TAG, "Failed to copy profile " +
9007                                        profileFile.getAbsolutePath() + " ", e);
9008                            }
9009                        }
9010                    }
9011                }
9012            }
9013
9014            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9015                if (DEBUG_DEXOPT) {
9016                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9017                }
9018                numberOfPackagesSkipped++;
9019                continue;
9020            }
9021
9022            if (DEBUG_DEXOPT) {
9023                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9024                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9025            }
9026
9027            if (showDialog) {
9028                try {
9029                    ActivityManager.getService().showBootMessage(
9030                            mContext.getResources().getString(R.string.android_upgrading_apk,
9031                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9032                } catch (RemoteException e) {
9033                }
9034                synchronized (mPackages) {
9035                    mDexOptDialogShown = true;
9036                }
9037            }
9038
9039            int pkgCompilationReason = compilationReason;
9040            if (useProfileForDexopt) {
9041                // Use background dexopt mode to try and use the profile. Note that this does not
9042                // guarantee usage of the profile.
9043                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9044            }
9045
9046            // checkProfiles is false to avoid merging profiles during boot which
9047            // might interfere with background compilation (b/28612421).
9048            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9049            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9050            // trade-off worth doing to save boot time work.
9051            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9052            if (compilationReason == REASON_FIRST_BOOT) {
9053                // TODO: This doesn't cover the upgrade case, we should check for this too.
9054                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9055            }
9056            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9057                    pkg.packageName,
9058                    pkgCompilationReason,
9059                    dexoptFlags));
9060
9061            switch (primaryDexOptStaus) {
9062                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9063                    numberOfPackagesOptimized++;
9064                    break;
9065                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9066                    numberOfPackagesSkipped++;
9067                    break;
9068                case PackageDexOptimizer.DEX_OPT_FAILED:
9069                    numberOfPackagesFailed++;
9070                    break;
9071                default:
9072                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9073                    break;
9074            }
9075        }
9076
9077        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9078                numberOfPackagesFailed };
9079    }
9080
9081    @Override
9082    public void notifyPackageUse(String packageName, int reason) {
9083        synchronized (mPackages) {
9084            final int callingUid = Binder.getCallingUid();
9085            final int callingUserId = UserHandle.getUserId(callingUid);
9086            if (getInstantAppPackageName(callingUid) != null) {
9087                if (!isCallerSameApp(packageName, callingUid)) {
9088                    return;
9089                }
9090            } else {
9091                if (isInstantApp(packageName, callingUserId)) {
9092                    return;
9093                }
9094            }
9095            notifyPackageUseLocked(packageName, reason);
9096        }
9097    }
9098
9099    @GuardedBy("mPackages")
9100    private void notifyPackageUseLocked(String packageName, int reason) {
9101        final PackageParser.Package p = mPackages.get(packageName);
9102        if (p == null) {
9103            return;
9104        }
9105        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9106    }
9107
9108    @Override
9109    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9110            List<String> classPaths, String loaderIsa) {
9111        int userId = UserHandle.getCallingUserId();
9112        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9113        if (ai == null) {
9114            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9115                + loadingPackageName + ", user=" + userId);
9116            return;
9117        }
9118        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9119    }
9120
9121    @Override
9122    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9123            IDexModuleRegisterCallback callback) {
9124        int userId = UserHandle.getCallingUserId();
9125        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9126        DexManager.RegisterDexModuleResult result;
9127        if (ai == null) {
9128            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9129                     " calling user. package=" + packageName + ", user=" + userId);
9130            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9131        } else {
9132            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9133        }
9134
9135        if (callback != null) {
9136            mHandler.post(() -> {
9137                try {
9138                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9139                } catch (RemoteException e) {
9140                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9141                }
9142            });
9143        }
9144    }
9145
9146    /**
9147     * Ask the package manager to perform a dex-opt with the given compiler filter.
9148     *
9149     * Note: exposed only for the shell command to allow moving packages explicitly to a
9150     *       definite state.
9151     */
9152    @Override
9153    public boolean performDexOptMode(String packageName,
9154            boolean checkProfiles, String targetCompilerFilter, boolean force,
9155            boolean bootComplete, String splitName) {
9156        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9157                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9158                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9159        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9160                targetCompilerFilter, splitName, flags));
9161    }
9162
9163    /**
9164     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9165     * secondary dex files belonging to the given package.
9166     *
9167     * Note: exposed only for the shell command to allow moving packages explicitly to a
9168     *       definite state.
9169     */
9170    @Override
9171    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9172            boolean force) {
9173        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9174                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9175                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9176                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9177        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9178    }
9179
9180    /*package*/ boolean performDexOpt(DexoptOptions options) {
9181        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9182            return false;
9183        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9184            return false;
9185        }
9186
9187        if (options.isDexoptOnlySecondaryDex()) {
9188            return mDexManager.dexoptSecondaryDex(options);
9189        } else {
9190            int dexoptStatus = performDexOptWithStatus(options);
9191            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9192        }
9193    }
9194
9195    /**
9196     * Perform dexopt on the given package and return one of following result:
9197     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9198     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9199     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9200     */
9201    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9202        return performDexOptTraced(options);
9203    }
9204
9205    private int performDexOptTraced(DexoptOptions options) {
9206        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9207        try {
9208            return performDexOptInternal(options);
9209        } finally {
9210            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9211        }
9212    }
9213
9214    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9215    // if the package can now be considered up to date for the given filter.
9216    private int performDexOptInternal(DexoptOptions options) {
9217        PackageParser.Package p;
9218        synchronized (mPackages) {
9219            p = mPackages.get(options.getPackageName());
9220            if (p == null) {
9221                // Package could not be found. Report failure.
9222                return PackageDexOptimizer.DEX_OPT_FAILED;
9223            }
9224            mPackageUsage.maybeWriteAsync(mPackages);
9225            mCompilerStats.maybeWriteAsync();
9226        }
9227        long callingId = Binder.clearCallingIdentity();
9228        try {
9229            synchronized (mInstallLock) {
9230                return performDexOptInternalWithDependenciesLI(p, options);
9231            }
9232        } finally {
9233            Binder.restoreCallingIdentity(callingId);
9234        }
9235    }
9236
9237    public ArraySet<String> getOptimizablePackages() {
9238        ArraySet<String> pkgs = new ArraySet<String>();
9239        synchronized (mPackages) {
9240            for (PackageParser.Package p : mPackages.values()) {
9241                if (PackageDexOptimizer.canOptimizePackage(p)) {
9242                    pkgs.add(p.packageName);
9243                }
9244            }
9245        }
9246        return pkgs;
9247    }
9248
9249    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9250            DexoptOptions options) {
9251        // Select the dex optimizer based on the force parameter.
9252        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9253        //       allocate an object here.
9254        PackageDexOptimizer pdo = options.isForce()
9255                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9256                : mPackageDexOptimizer;
9257
9258        // Dexopt all dependencies first. Note: we ignore the return value and march on
9259        // on errors.
9260        // Note that we are going to call performDexOpt on those libraries as many times as
9261        // they are referenced in packages. When we do a batch of performDexOpt (for example
9262        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9263        // and the first package that uses the library will dexopt it. The
9264        // others will see that the compiled code for the library is up to date.
9265        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9266        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9267        if (!deps.isEmpty()) {
9268            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9269                    options.getCompilationReason(), options.getCompilerFilter(),
9270                    options.getSplitName(),
9271                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9272            for (PackageParser.Package depPackage : deps) {
9273                // TODO: Analyze and investigate if we (should) profile libraries.
9274                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9275                        getOrCreateCompilerPackageStats(depPackage),
9276                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9277            }
9278        }
9279        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9280                getOrCreateCompilerPackageStats(p),
9281                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9282    }
9283
9284    /**
9285     * Reconcile the information we have about the secondary dex files belonging to
9286     * {@code packagName} and the actual dex files. For all dex files that were
9287     * deleted, update the internal records and delete the generated oat files.
9288     */
9289    @Override
9290    public void reconcileSecondaryDexFiles(String packageName) {
9291        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9292            return;
9293        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9294            return;
9295        }
9296        mDexManager.reconcileSecondaryDexFiles(packageName);
9297    }
9298
9299    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9300    // a reference there.
9301    /*package*/ DexManager getDexManager() {
9302        return mDexManager;
9303    }
9304
9305    /**
9306     * Execute the background dexopt job immediately.
9307     */
9308    @Override
9309    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9310        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9311            return false;
9312        }
9313        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9314    }
9315
9316    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9317        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9318                || p.usesStaticLibraries != null) {
9319            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9320            Set<String> collectedNames = new HashSet<>();
9321            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9322
9323            retValue.remove(p);
9324
9325            return retValue;
9326        } else {
9327            return Collections.emptyList();
9328        }
9329    }
9330
9331    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9332            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9333        if (!collectedNames.contains(p.packageName)) {
9334            collectedNames.add(p.packageName);
9335            collected.add(p);
9336
9337            if (p.usesLibraries != null) {
9338                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9339                        null, collected, collectedNames);
9340            }
9341            if (p.usesOptionalLibraries != null) {
9342                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9343                        null, collected, collectedNames);
9344            }
9345            if (p.usesStaticLibraries != null) {
9346                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9347                        p.usesStaticLibrariesVersions, collected, collectedNames);
9348            }
9349        }
9350    }
9351
9352    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9353            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9354        final int libNameCount = libs.size();
9355        for (int i = 0; i < libNameCount; i++) {
9356            String libName = libs.get(i);
9357            long version = (versions != null && versions.length == libNameCount)
9358                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9359            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9360            if (libPkg != null) {
9361                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9362            }
9363        }
9364    }
9365
9366    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9367        synchronized (mPackages) {
9368            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9369            if (libEntry != null) {
9370                return mPackages.get(libEntry.apk);
9371            }
9372            return null;
9373        }
9374    }
9375
9376    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9377        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9378        if (versionedLib == null) {
9379            return null;
9380        }
9381        return versionedLib.get(version);
9382    }
9383
9384    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9385        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9386                pkg.staticSharedLibName);
9387        if (versionedLib == null) {
9388            return null;
9389        }
9390        long previousLibVersion = -1;
9391        final int versionCount = versionedLib.size();
9392        for (int i = 0; i < versionCount; i++) {
9393            final long libVersion = versionedLib.keyAt(i);
9394            if (libVersion < pkg.staticSharedLibVersion) {
9395                previousLibVersion = Math.max(previousLibVersion, libVersion);
9396            }
9397        }
9398        if (previousLibVersion >= 0) {
9399            return versionedLib.get(previousLibVersion);
9400        }
9401        return null;
9402    }
9403
9404    public void shutdown() {
9405        mPackageUsage.writeNow(mPackages);
9406        mCompilerStats.writeNow();
9407        mDexManager.writePackageDexUsageNow();
9408    }
9409
9410    @Override
9411    public void dumpProfiles(String packageName) {
9412        PackageParser.Package pkg;
9413        synchronized (mPackages) {
9414            pkg = mPackages.get(packageName);
9415            if (pkg == null) {
9416                throw new IllegalArgumentException("Unknown package: " + packageName);
9417            }
9418        }
9419        /* Only the shell, root, or the app user should be able to dump profiles. */
9420        int callingUid = Binder.getCallingUid();
9421        if (callingUid != Process.SHELL_UID &&
9422            callingUid != Process.ROOT_UID &&
9423            callingUid != pkg.applicationInfo.uid) {
9424            throw new SecurityException("dumpProfiles");
9425        }
9426
9427        synchronized (mInstallLock) {
9428            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9429            mArtManagerService.dumpProfiles(pkg);
9430            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9431        }
9432    }
9433
9434    @Override
9435    public void forceDexOpt(String packageName) {
9436        enforceSystemOrRoot("forceDexOpt");
9437
9438        PackageParser.Package pkg;
9439        synchronized (mPackages) {
9440            pkg = mPackages.get(packageName);
9441            if (pkg == null) {
9442                throw new IllegalArgumentException("Unknown package: " + packageName);
9443            }
9444        }
9445
9446        synchronized (mInstallLock) {
9447            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9448
9449            // Whoever is calling forceDexOpt wants a compiled package.
9450            // Don't use profiles since that may cause compilation to be skipped.
9451            final int res = performDexOptInternalWithDependenciesLI(
9452                    pkg,
9453                    new DexoptOptions(packageName,
9454                            getDefaultCompilerFilter(),
9455                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9456
9457            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9458            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9459                throw new IllegalStateException("Failed to dexopt: " + res);
9460            }
9461        }
9462    }
9463
9464    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9465        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9466            Slog.w(TAG, "Unable to update from " + oldPkg.name
9467                    + " to " + newPkg.packageName
9468                    + ": old package not in system partition");
9469            return false;
9470        } else if (mPackages.get(oldPkg.name) != null) {
9471            Slog.w(TAG, "Unable to update from " + oldPkg.name
9472                    + " to " + newPkg.packageName
9473                    + ": old package still exists");
9474            return false;
9475        }
9476        return true;
9477    }
9478
9479    void removeCodePathLI(File codePath) {
9480        if (codePath.isDirectory()) {
9481            try {
9482                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9483            } catch (InstallerException e) {
9484                Slog.w(TAG, "Failed to remove code path", e);
9485            }
9486        } else {
9487            codePath.delete();
9488        }
9489    }
9490
9491    private int[] resolveUserIds(int userId) {
9492        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9493    }
9494
9495    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9496        if (pkg == null) {
9497            Slog.wtf(TAG, "Package was null!", new Throwable());
9498            return;
9499        }
9500        clearAppDataLeafLIF(pkg, userId, flags);
9501        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9502        for (int i = 0; i < childCount; i++) {
9503            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9504        }
9505
9506        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9507    }
9508
9509    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9510        final PackageSetting ps;
9511        synchronized (mPackages) {
9512            ps = mSettings.mPackages.get(pkg.packageName);
9513        }
9514        for (int realUserId : resolveUserIds(userId)) {
9515            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9516            try {
9517                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9518                        ceDataInode);
9519            } catch (InstallerException e) {
9520                Slog.w(TAG, String.valueOf(e));
9521            }
9522        }
9523    }
9524
9525    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9526        if (pkg == null) {
9527            Slog.wtf(TAG, "Package was null!", new Throwable());
9528            return;
9529        }
9530        destroyAppDataLeafLIF(pkg, userId, flags);
9531        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9532        for (int i = 0; i < childCount; i++) {
9533            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9534        }
9535    }
9536
9537    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9538        final PackageSetting ps;
9539        synchronized (mPackages) {
9540            ps = mSettings.mPackages.get(pkg.packageName);
9541        }
9542        for (int realUserId : resolveUserIds(userId)) {
9543            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9544            try {
9545                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9546                        ceDataInode);
9547            } catch (InstallerException e) {
9548                Slog.w(TAG, String.valueOf(e));
9549            }
9550            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9551        }
9552    }
9553
9554    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9555        if (pkg == null) {
9556            Slog.wtf(TAG, "Package was null!", new Throwable());
9557            return;
9558        }
9559        destroyAppProfilesLeafLIF(pkg);
9560        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9561        for (int i = 0; i < childCount; i++) {
9562            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9563        }
9564    }
9565
9566    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9567        try {
9568            mInstaller.destroyAppProfiles(pkg.packageName);
9569        } catch (InstallerException e) {
9570            Slog.w(TAG, String.valueOf(e));
9571        }
9572    }
9573
9574    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9575        if (pkg == null) {
9576            Slog.wtf(TAG, "Package was null!", new Throwable());
9577            return;
9578        }
9579        mArtManagerService.clearAppProfiles(pkg);
9580        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9581        for (int i = 0; i < childCount; i++) {
9582            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9583        }
9584    }
9585
9586    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9587            long lastUpdateTime) {
9588        // Set parent install/update time
9589        PackageSetting ps = (PackageSetting) pkg.mExtras;
9590        if (ps != null) {
9591            ps.firstInstallTime = firstInstallTime;
9592            ps.lastUpdateTime = lastUpdateTime;
9593        }
9594        // Set children install/update time
9595        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9596        for (int i = 0; i < childCount; i++) {
9597            PackageParser.Package childPkg = pkg.childPackages.get(i);
9598            ps = (PackageSetting) childPkg.mExtras;
9599            if (ps != null) {
9600                ps.firstInstallTime = firstInstallTime;
9601                ps.lastUpdateTime = lastUpdateTime;
9602            }
9603        }
9604    }
9605
9606    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9607            SharedLibraryEntry file,
9608            PackageParser.Package changingLib) {
9609        if (file.path != null) {
9610            usesLibraryFiles.add(file.path);
9611            return;
9612        }
9613        PackageParser.Package p = mPackages.get(file.apk);
9614        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9615            // If we are doing this while in the middle of updating a library apk,
9616            // then we need to make sure to use that new apk for determining the
9617            // dependencies here.  (We haven't yet finished committing the new apk
9618            // to the package manager state.)
9619            if (p == null || p.packageName.equals(changingLib.packageName)) {
9620                p = changingLib;
9621            }
9622        }
9623        if (p != null) {
9624            usesLibraryFiles.addAll(p.getAllCodePaths());
9625            if (p.usesLibraryFiles != null) {
9626                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9627            }
9628        }
9629    }
9630
9631    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9632            PackageParser.Package changingLib) throws PackageManagerException {
9633        if (pkg == null) {
9634            return;
9635        }
9636        // The collection used here must maintain the order of addition (so
9637        // that libraries are searched in the correct order) and must have no
9638        // duplicates.
9639        Set<String> usesLibraryFiles = null;
9640        if (pkg.usesLibraries != null) {
9641            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9642                    null, null, pkg.packageName, changingLib, true,
9643                    pkg.applicationInfo.targetSdkVersion, null);
9644        }
9645        if (pkg.usesStaticLibraries != null) {
9646            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9647                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9648                    pkg.packageName, changingLib, true,
9649                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9650        }
9651        if (pkg.usesOptionalLibraries != null) {
9652            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9653                    null, null, pkg.packageName, changingLib, false,
9654                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9655        }
9656        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9657            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9658        } else {
9659            pkg.usesLibraryFiles = null;
9660        }
9661    }
9662
9663    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9664            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9665            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9666            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9667            throws PackageManagerException {
9668        final int libCount = requestedLibraries.size();
9669        for (int i = 0; i < libCount; i++) {
9670            final String libName = requestedLibraries.get(i);
9671            final long libVersion = requiredVersions != null ? requiredVersions[i]
9672                    : SharedLibraryInfo.VERSION_UNDEFINED;
9673            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9674            if (libEntry == null) {
9675                if (required) {
9676                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9677                            "Package " + packageName + " requires unavailable shared library "
9678                                    + libName + "; failing!");
9679                } else if (DEBUG_SHARED_LIBRARIES) {
9680                    Slog.i(TAG, "Package " + packageName
9681                            + " desires unavailable shared library "
9682                            + libName + "; ignoring!");
9683                }
9684            } else {
9685                if (requiredVersions != null && requiredCertDigests != null) {
9686                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9687                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9688                            "Package " + packageName + " requires unavailable static shared"
9689                                    + " library " + libName + " version "
9690                                    + libEntry.info.getLongVersion() + "; failing!");
9691                    }
9692
9693                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9694                    if (libPkg == null) {
9695                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9696                                "Package " + packageName + " requires unavailable static shared"
9697                                        + " library; failing!");
9698                    }
9699
9700                    final String[] expectedCertDigests = requiredCertDigests[i];
9701
9702
9703                    if (expectedCertDigests.length > 1) {
9704
9705                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9706                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9707                                ? PackageUtils.computeSignaturesSha256Digests(
9708                                libPkg.mSigningDetails.signatures)
9709                                : PackageUtils.computeSignaturesSha256Digests(
9710                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9711
9712                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9713                        // target O we don't parse the "additional-certificate" tags similarly
9714                        // how we only consider all certs only for apps targeting O (see above).
9715                        // Therefore, the size check is safe to make.
9716                        if (expectedCertDigests.length != libCertDigests.length) {
9717                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9718                                    "Package " + packageName + " requires differently signed" +
9719                                            " static shared library; failing!");
9720                        }
9721
9722                        // Use a predictable order as signature order may vary
9723                        Arrays.sort(libCertDigests);
9724                        Arrays.sort(expectedCertDigests);
9725
9726                        final int certCount = libCertDigests.length;
9727                        for (int j = 0; j < certCount; j++) {
9728                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9729                                throw new PackageManagerException(
9730                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9731                                        "Package " + packageName + " requires differently signed" +
9732                                                " static shared library; failing!");
9733                            }
9734                        }
9735                    } else {
9736
9737                        // lib signing cert could have rotated beyond the one expected, check to see
9738                        // if the new one has been blessed by the old
9739                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9740                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9741                            throw new PackageManagerException(
9742                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9743                                    "Package " + packageName + " requires differently signed" +
9744                                            " static shared library; failing!");
9745                        }
9746                    }
9747                }
9748
9749                if (outUsedLibraries == null) {
9750                    // Use LinkedHashSet to preserve the order of files added to
9751                    // usesLibraryFiles while eliminating duplicates.
9752                    outUsedLibraries = new LinkedHashSet<>();
9753                }
9754                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9755            }
9756        }
9757        return outUsedLibraries;
9758    }
9759
9760    private static boolean hasString(List<String> list, List<String> which) {
9761        if (list == null) {
9762            return false;
9763        }
9764        for (int i=list.size()-1; i>=0; i--) {
9765            for (int j=which.size()-1; j>=0; j--) {
9766                if (which.get(j).equals(list.get(i))) {
9767                    return true;
9768                }
9769            }
9770        }
9771        return false;
9772    }
9773
9774    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9775            PackageParser.Package changingPkg) {
9776        ArrayList<PackageParser.Package> res = null;
9777        for (PackageParser.Package pkg : mPackages.values()) {
9778            if (changingPkg != null
9779                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9780                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9781                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9782                            changingPkg.staticSharedLibName)) {
9783                return null;
9784            }
9785            if (res == null) {
9786                res = new ArrayList<>();
9787            }
9788            res.add(pkg);
9789            try {
9790                updateSharedLibrariesLPr(pkg, changingPkg);
9791            } catch (PackageManagerException e) {
9792                // If a system app update or an app and a required lib missing we
9793                // delete the package and for updated system apps keep the data as
9794                // it is better for the user to reinstall than to be in an limbo
9795                // state. Also libs disappearing under an app should never happen
9796                // - just in case.
9797                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9798                    final int flags = pkg.isUpdatedSystemApp()
9799                            ? PackageManager.DELETE_KEEP_DATA : 0;
9800                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9801                            flags , null, true, null);
9802                }
9803                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9804            }
9805        }
9806        return res;
9807    }
9808
9809    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9810            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9811            @Nullable UserHandle user) throws PackageManagerException {
9812        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9813        // If the package has children and this is the first dive in the function
9814        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9815        // whether all packages (parent and children) would be successfully scanned
9816        // before the actual scan since scanning mutates internal state and we want
9817        // to atomically install the package and its children.
9818        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9819            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9820                scanFlags |= SCAN_CHECK_ONLY;
9821            }
9822        } else {
9823            scanFlags &= ~SCAN_CHECK_ONLY;
9824        }
9825
9826        final PackageParser.Package scannedPkg;
9827        try {
9828            // Scan the parent
9829            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9830            // Scan the children
9831            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9832            for (int i = 0; i < childCount; i++) {
9833                PackageParser.Package childPkg = pkg.childPackages.get(i);
9834                scanPackageNewLI(childPkg, parseFlags,
9835                        scanFlags, currentTime, user);
9836            }
9837        } finally {
9838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9839        }
9840
9841        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9842            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9843        }
9844
9845        return scannedPkg;
9846    }
9847
9848    /** The result of a package scan. */
9849    private static class ScanResult {
9850        /** Whether or not the package scan was successful */
9851        public final boolean success;
9852        /**
9853         * The final package settings. This may be the same object passed in
9854         * the {@link ScanRequest}, but, with modified values.
9855         */
9856        @Nullable public final PackageSetting pkgSetting;
9857        /** ABI code paths that have changed in the package scan */
9858        @Nullable public final List<String> changedAbiCodePath;
9859        public ScanResult(
9860                boolean success,
9861                @Nullable PackageSetting pkgSetting,
9862                @Nullable List<String> changedAbiCodePath) {
9863            this.success = success;
9864            this.pkgSetting = pkgSetting;
9865            this.changedAbiCodePath = changedAbiCodePath;
9866        }
9867    }
9868
9869    /** A package to be scanned */
9870    private static class ScanRequest {
9871        /** The parsed package */
9872        @NonNull public final PackageParser.Package pkg;
9873        /** Shared user settings, if the package has a shared user */
9874        @Nullable public final SharedUserSetting sharedUserSetting;
9875        /**
9876         * Package settings of the currently installed version.
9877         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9878         * during scan.
9879         */
9880        @Nullable public final PackageSetting pkgSetting;
9881        /** A copy of the settings for the currently installed version */
9882        @Nullable public final PackageSetting oldPkgSetting;
9883        /** Package settings for the disabled version on the /system partition */
9884        @Nullable public final PackageSetting disabledPkgSetting;
9885        /** Package settings for the installed version under its original package name */
9886        @Nullable public final PackageSetting originalPkgSetting;
9887        /** The real package name of a renamed application */
9888        @Nullable public final String realPkgName;
9889        public final @ParseFlags int parseFlags;
9890        public final @ScanFlags int scanFlags;
9891        /** The user for which the package is being scanned */
9892        @Nullable public final UserHandle user;
9893        /** Whether or not the platform package is being scanned */
9894        public final boolean isPlatformPackage;
9895        public ScanRequest(
9896                @NonNull PackageParser.Package pkg,
9897                @Nullable SharedUserSetting sharedUserSetting,
9898                @Nullable PackageSetting pkgSetting,
9899                @Nullable PackageSetting disabledPkgSetting,
9900                @Nullable PackageSetting originalPkgSetting,
9901                @Nullable String realPkgName,
9902                @ParseFlags int parseFlags,
9903                @ScanFlags int scanFlags,
9904                boolean isPlatformPackage,
9905                @Nullable UserHandle user) {
9906            this.pkg = pkg;
9907            this.pkgSetting = pkgSetting;
9908            this.sharedUserSetting = sharedUserSetting;
9909            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9910            this.disabledPkgSetting = disabledPkgSetting;
9911            this.originalPkgSetting = originalPkgSetting;
9912            this.realPkgName = realPkgName;
9913            this.parseFlags = parseFlags;
9914            this.scanFlags = scanFlags;
9915            this.isPlatformPackage = isPlatformPackage;
9916            this.user = user;
9917        }
9918    }
9919
9920    /**
9921     * Returns the actual scan flags depending upon the state of the other settings.
9922     * <p>Updated system applications will not have the following flags set
9923     * by default and need to be adjusted after the fact:
9924     * <ul>
9925     * <li>{@link #SCAN_AS_SYSTEM}</li>
9926     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9927     * <li>{@link #SCAN_AS_OEM}</li>
9928     * <li>{@link #SCAN_AS_VENDOR}</li>
9929     * <li>{@link #SCAN_AS_PRODUCT}</li>
9930     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9931     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9932     * </ul>
9933     */
9934    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9935            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9936            PackageParser.Package pkg) {
9937        if (disabledPkgSetting != null) {
9938            // updated system application, must at least have SCAN_AS_SYSTEM
9939            scanFlags |= SCAN_AS_SYSTEM;
9940            if ((disabledPkgSetting.pkgPrivateFlags
9941                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9942                scanFlags |= SCAN_AS_PRIVILEGED;
9943            }
9944            if ((disabledPkgSetting.pkgPrivateFlags
9945                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9946                scanFlags |= SCAN_AS_OEM;
9947            }
9948            if ((disabledPkgSetting.pkgPrivateFlags
9949                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9950                scanFlags |= SCAN_AS_VENDOR;
9951            }
9952            if ((disabledPkgSetting.pkgPrivateFlags
9953                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9954                scanFlags |= SCAN_AS_PRODUCT;
9955            }
9956        }
9957        if (pkgSetting != null) {
9958            final int userId = ((user == null) ? 0 : user.getIdentifier());
9959            if (pkgSetting.getInstantApp(userId)) {
9960                scanFlags |= SCAN_AS_INSTANT_APP;
9961            }
9962            if (pkgSetting.getVirtulalPreload(userId)) {
9963                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9964            }
9965        }
9966
9967        // Scan as privileged apps that share a user with a priv-app.
9968        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9969                && (pkg.mSharedUserId != null)) {
9970            SharedUserSetting sharedUserSetting = null;
9971            try {
9972                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9973            } catch (PackageManagerException ignore) {}
9974            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9975                // Exempt SharedUsers signed with the platform key.
9976                // TODO(b/72378145) Fix this exemption. Force signature apps
9977                // to whitelist their privileged permissions just like other
9978                // priv-apps.
9979                synchronized (mPackages) {
9980                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9981                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9982                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9983                        scanFlags |= SCAN_AS_PRIVILEGED;
9984                    }
9985                }
9986            }
9987        }
9988
9989        return scanFlags;
9990    }
9991
9992    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
9993    // the results / removing app data needs to be moved up a level to the callers of this
9994    // method. Also, we need to solve the problem of potentially creating a new shared user
9995    // setting. That can probably be done later and patch things up after the fact.
9996    @GuardedBy("mInstallLock")
9997    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9998            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9999            @Nullable UserHandle user) throws PackageManagerException {
10000
10001        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10002        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10003        if (realPkgName != null) {
10004            ensurePackageRenamed(pkg, renamedPkgName);
10005        }
10006        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10007        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10008        final PackageSetting disabledPkgSetting =
10009                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10010
10011        if (mTransferedPackages.contains(pkg.packageName)) {
10012            Slog.w(TAG, "Package " + pkg.packageName
10013                    + " was transferred to another, but its .apk remains");
10014        }
10015
10016        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10017        synchronized (mPackages) {
10018            applyPolicy(pkg, parseFlags, scanFlags);
10019            assertPackageIsValid(pkg, parseFlags, scanFlags);
10020
10021            SharedUserSetting sharedUserSetting = null;
10022            if (pkg.mSharedUserId != null) {
10023                // SIDE EFFECTS; may potentially allocate a new shared user
10024                sharedUserSetting = mSettings.getSharedUserLPw(
10025                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10026                if (DEBUG_PACKAGE_SCANNING) {
10027                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10028                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10029                                + " (uid=" + sharedUserSetting.userId + "):"
10030                                + " packages=" + sharedUserSetting.packages);
10031                }
10032            }
10033
10034            boolean scanSucceeded = false;
10035            try {
10036                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10037                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10038                        (pkg == mPlatformPackage), user);
10039                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10040                if (result.success) {
10041                    commitScanResultsLocked(request, result);
10042                }
10043                scanSucceeded = true;
10044            } finally {
10045                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10046                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10047                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10048                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10049                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10050                  }
10051            }
10052        }
10053        return pkg;
10054    }
10055
10056    /**
10057     * Commits the package scan and modifies system state.
10058     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10059     * of committing the package, leaving the system in an inconsistent state.
10060     * This needs to be fixed so, once we get to this point, no errors are
10061     * possible and the system is not left in an inconsistent state.
10062     */
10063    @GuardedBy("mPackages")
10064    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10065            throws PackageManagerException {
10066        final PackageParser.Package pkg = request.pkg;
10067        final @ParseFlags int parseFlags = request.parseFlags;
10068        final @ScanFlags int scanFlags = request.scanFlags;
10069        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10070        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10071        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10072        final UserHandle user = request.user;
10073        final String realPkgName = request.realPkgName;
10074        final PackageSetting pkgSetting = result.pkgSetting;
10075        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10076        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10077
10078        if (newPkgSettingCreated) {
10079            if (originalPkgSetting != null) {
10080                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10081            }
10082            // THROWS: when we can't allocate a user id. add call to check if there's
10083            // enough space to ensure we won't throw; otherwise, don't modify state
10084            mSettings.addUserToSettingLPw(pkgSetting);
10085
10086            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10087                mTransferedPackages.add(originalPkgSetting.name);
10088            }
10089        }
10090        // TODO(toddke): Consider a method specifically for modifying the Package object
10091        // post scan; or, moving this stuff out of the Package object since it has nothing
10092        // to do with the package on disk.
10093        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10094        // for creating the application ID. If we did this earlier, we would be saving the
10095        // correct ID.
10096        pkg.applicationInfo.uid = pkgSetting.appId;
10097
10098        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10099
10100        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10101            mTransferedPackages.add(pkg.packageName);
10102        }
10103
10104        // THROWS: when requested libraries that can't be found. it only changes
10105        // the state of the passed in pkg object, so, move to the top of the method
10106        // and allow it to abort
10107        if ((scanFlags & SCAN_BOOTING) == 0
10108                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10109            // Check all shared libraries and map to their actual file path.
10110            // We only do this here for apps not on a system dir, because those
10111            // are the only ones that can fail an install due to this.  We
10112            // will take care of the system apps by updating all of their
10113            // library paths after the scan is done. Also during the initial
10114            // scan don't update any libs as we do this wholesale after all
10115            // apps are scanned to avoid dependency based scanning.
10116            updateSharedLibrariesLPr(pkg, null);
10117        }
10118
10119        // All versions of a static shared library are referenced with the same
10120        // package name. Internally, we use a synthetic package name to allow
10121        // multiple versions of the same shared library to be installed. So,
10122        // we need to generate the synthetic package name of the latest shared
10123        // library in order to compare signatures.
10124        PackageSetting signatureCheckPs = pkgSetting;
10125        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10126            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10127            if (libraryEntry != null) {
10128                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10129            }
10130        }
10131
10132        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10133        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10134            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10135                // We just determined the app is signed correctly, so bring
10136                // over the latest parsed certs.
10137                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10138            } else {
10139                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10140                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10141                            "Package " + pkg.packageName + " upgrade keys do not match the "
10142                                    + "previously installed version");
10143                } else {
10144                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10145                    String msg = "System package " + pkg.packageName
10146                            + " signature changed; retaining data.";
10147                    reportSettingsProblem(Log.WARN, msg);
10148                }
10149            }
10150        } else {
10151            try {
10152                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10153                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10154                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10155                        pkg.mSigningDetails, compareCompat, compareRecover);
10156                // The new KeySets will be re-added later in the scanning process.
10157                if (compatMatch) {
10158                    synchronized (mPackages) {
10159                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10160                    }
10161                }
10162                // We just determined the app is signed correctly, so bring
10163                // over the latest parsed certs.
10164                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10165
10166
10167                // if this is is a sharedUser, check to see if the new package is signed by a newer
10168                // signing certificate than the existing one, and if so, copy over the new details
10169                if (signatureCheckPs.sharedUser != null
10170                        && pkg.mSigningDetails.hasAncestor(
10171                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10172                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10173                }
10174            } catch (PackageManagerException e) {
10175                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10176                    throw e;
10177                }
10178                // The signature has changed, but this package is in the system
10179                // image...  let's recover!
10180                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10181                // However...  if this package is part of a shared user, but it
10182                // doesn't match the signature of the shared user, let's fail.
10183                // What this means is that you can't change the signatures
10184                // associated with an overall shared user, which doesn't seem all
10185                // that unreasonable.
10186                if (signatureCheckPs.sharedUser != null) {
10187                    if (compareSignatures(
10188                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10189                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10190                        throw new PackageManagerException(
10191                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10192                                "Signature mismatch for shared user: "
10193                                        + pkgSetting.sharedUser);
10194                    }
10195                }
10196                // File a report about this.
10197                String msg = "System package " + pkg.packageName
10198                        + " signature changed; retaining data.";
10199                reportSettingsProblem(Log.WARN, msg);
10200            } catch (IllegalArgumentException e) {
10201
10202                // should never happen: certs matched when checking, but not when comparing
10203                // old to new for sharedUser
10204                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10205                        "Signing certificates comparison made on incomparable signing details"
10206                        + " but somehow passed verifySignatures!");
10207            }
10208        }
10209
10210        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10211            // This package wants to adopt ownership of permissions from
10212            // another package.
10213            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10214                final String origName = pkg.mAdoptPermissions.get(i);
10215                final PackageSetting orig = mSettings.getPackageLPr(origName);
10216                if (orig != null) {
10217                    if (verifyPackageUpdateLPr(orig, pkg)) {
10218                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10219                                + pkg.packageName);
10220                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10221                    }
10222                }
10223            }
10224        }
10225
10226        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10227            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10228                final String codePathString = changedAbiCodePath.get(i);
10229                try {
10230                    mInstaller.rmdex(codePathString,
10231                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10232                } catch (InstallerException ignored) {
10233                }
10234            }
10235        }
10236
10237        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10238            if (oldPkgSetting != null) {
10239                synchronized (mPackages) {
10240                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10241                }
10242            }
10243        } else {
10244            final int userId = user == null ? 0 : user.getIdentifier();
10245            // Modify state for the given package setting
10246            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10247                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10248            if (pkgSetting.getInstantApp(userId)) {
10249                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10250            }
10251        }
10252    }
10253
10254    /**
10255     * Returns the "real" name of the package.
10256     * <p>This may differ from the package's actual name if the application has already
10257     * been installed under one of this package's original names.
10258     */
10259    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10260            @Nullable String renamedPkgName) {
10261        if (isPackageRenamed(pkg, renamedPkgName)) {
10262            return pkg.mRealPackage;
10263        }
10264        return null;
10265    }
10266
10267    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10268    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10269            @Nullable String renamedPkgName) {
10270        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10271    }
10272
10273    /**
10274     * Returns the original package setting.
10275     * <p>A package can migrate its name during an update. In this scenario, a package
10276     * designates a set of names that it considers as one of its original names.
10277     * <p>An original package must be signed identically and it must have the same
10278     * shared user [if any].
10279     */
10280    @GuardedBy("mPackages")
10281    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10282            @Nullable String renamedPkgName) {
10283        if (!isPackageRenamed(pkg, renamedPkgName)) {
10284            return null;
10285        }
10286        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10287            final PackageSetting originalPs =
10288                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10289            if (originalPs != null) {
10290                // the package is already installed under its original name...
10291                // but, should we use it?
10292                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10293                    // the new package is incompatible with the original
10294                    continue;
10295                } else if (originalPs.sharedUser != null) {
10296                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10297                        // the shared user id is incompatible with the original
10298                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10299                                + " to " + pkg.packageName + ": old uid "
10300                                + originalPs.sharedUser.name
10301                                + " differs from " + pkg.mSharedUserId);
10302                        continue;
10303                    }
10304                    // TODO: Add case when shared user id is added [b/28144775]
10305                } else {
10306                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10307                            + pkg.packageName + " to old name " + originalPs.name);
10308                }
10309                return originalPs;
10310            }
10311        }
10312        return null;
10313    }
10314
10315    /**
10316     * Renames the package if it was installed under a different name.
10317     * <p>When we've already installed the package under an original name, update
10318     * the new package so we can continue to have the old name.
10319     */
10320    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10321            @NonNull String renamedPackageName) {
10322        if (pkg.mOriginalPackages == null
10323                || !pkg.mOriginalPackages.contains(renamedPackageName)
10324                || pkg.packageName.equals(renamedPackageName)) {
10325            return;
10326        }
10327        pkg.setPackageName(renamedPackageName);
10328    }
10329
10330    /**
10331     * Just scans the package without any side effects.
10332     * <p>Not entirely true at the moment. There is still one side effect -- this
10333     * method potentially modifies a live {@link PackageSetting} object representing
10334     * the package being scanned. This will be resolved in the future.
10335     *
10336     * @param request Information about the package to be scanned
10337     * @param isUnderFactoryTest Whether or not the device is under factory test
10338     * @param currentTime The current time, in millis
10339     * @return The results of the scan
10340     */
10341    @GuardedBy("mInstallLock")
10342    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10343            boolean isUnderFactoryTest, long currentTime)
10344                    throws PackageManagerException {
10345        final PackageParser.Package pkg = request.pkg;
10346        PackageSetting pkgSetting = request.pkgSetting;
10347        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10348        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10349        final @ParseFlags int parseFlags = request.parseFlags;
10350        final @ScanFlags int scanFlags = request.scanFlags;
10351        final String realPkgName = request.realPkgName;
10352        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10353        final UserHandle user = request.user;
10354        final boolean isPlatformPackage = request.isPlatformPackage;
10355
10356        List<String> changedAbiCodePath = null;
10357
10358        if (DEBUG_PACKAGE_SCANNING) {
10359            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10360                Log.d(TAG, "Scanning package " + pkg.packageName);
10361        }
10362
10363        if (Build.IS_DEBUGGABLE &&
10364                pkg.isPrivileged() &&
10365                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10366            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10367        }
10368
10369        // Initialize package source and resource directories
10370        final File scanFile = new File(pkg.codePath);
10371        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10372        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10373
10374        // We keep references to the derived CPU Abis from settings in oder to reuse
10375        // them in the case where we're not upgrading or booting for the first time.
10376        String primaryCpuAbiFromSettings = null;
10377        String secondaryCpuAbiFromSettings = null;
10378        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10379
10380        if (!needToDeriveAbi) {
10381            if (pkgSetting != null) {
10382                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10383                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10384            } else {
10385                // Re-scanning a system package after uninstalling updates; need to derive ABI
10386                needToDeriveAbi = true;
10387            }
10388        }
10389
10390        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10391            PackageManagerService.reportSettingsProblem(Log.WARN,
10392                    "Package " + pkg.packageName + " shared user changed from "
10393                            + (pkgSetting.sharedUser != null
10394                            ? pkgSetting.sharedUser.name : "<nothing>")
10395                            + " to "
10396                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10397                            + "; replacing with new");
10398            pkgSetting = null;
10399        }
10400
10401        String[] usesStaticLibraries = null;
10402        if (pkg.usesStaticLibraries != null) {
10403            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10404            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10405        }
10406        final boolean createNewPackage = (pkgSetting == null);
10407        if (createNewPackage) {
10408            final String parentPackageName = (pkg.parentPackage != null)
10409                    ? pkg.parentPackage.packageName : null;
10410            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10411            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10412            // REMOVE SharedUserSetting from method; update in a separate call
10413            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10414                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10415                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10416                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10417                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10418                    user, true /*allowInstall*/, instantApp, virtualPreload,
10419                    parentPackageName, pkg.getChildPackageNames(),
10420                    UserManagerService.getInstance(), usesStaticLibraries,
10421                    pkg.usesStaticLibrariesVersions);
10422        } else {
10423            // REMOVE SharedUserSetting from method; update in a separate call.
10424            //
10425            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10426            // secondaryCpuAbi are not known at this point so we always update them
10427            // to null here, only to reset them at a later point.
10428            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10429                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10430                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10431                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10432                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10433                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10434        }
10435        if (createNewPackage && originalPkgSetting != null) {
10436            // This is the initial transition from the original package, so,
10437            // fix up the new package's name now. We must do this after looking
10438            // up the package under its new name, so getPackageLP takes care of
10439            // fiddling things correctly.
10440            pkg.setPackageName(originalPkgSetting.name);
10441
10442            // File a report about this.
10443            String msg = "New package " + pkgSetting.realName
10444                    + " renamed to replace old package " + pkgSetting.name;
10445            reportSettingsProblem(Log.WARN, msg);
10446        }
10447
10448        if (disabledPkgSetting != null) {
10449            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10450        }
10451
10452        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10453        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10454        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10455        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10456        // least restrictive selinux domain.
10457        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10458        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10459        // ensures that all packages continue to run in the same selinux domain.
10460        final int targetSdkVersion =
10461            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10462            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10463        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10464        // They currently can be if the sharedUser apps are signed with the platform key.
10465        final boolean isPrivileged = (sharedUserSetting != null) ?
10466            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10467
10468        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10469                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10470
10471        pkg.mExtras = pkgSetting;
10472        pkg.applicationInfo.processName = fixProcessName(
10473                pkg.applicationInfo.packageName,
10474                pkg.applicationInfo.processName);
10475
10476        if (!isPlatformPackage) {
10477            // Get all of our default paths setup
10478            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10479        }
10480
10481        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10482
10483        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10484            if (needToDeriveAbi) {
10485                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10486                final boolean extractNativeLibs = !pkg.isLibrary();
10487                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10488                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10489
10490                // Some system apps still use directory structure for native libraries
10491                // in which case we might end up not detecting abi solely based on apk
10492                // structure. Try to detect abi based on directory structure.
10493                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10494                        pkg.applicationInfo.primaryCpuAbi == null) {
10495                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10496                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10497                }
10498            } else {
10499                // This is not a first boot or an upgrade, don't bother deriving the
10500                // ABI during the scan. Instead, trust the value that was stored in the
10501                // package setting.
10502                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10503                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10504
10505                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10506
10507                if (DEBUG_ABI_SELECTION) {
10508                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10509                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10510                            pkg.applicationInfo.secondaryCpuAbi);
10511                }
10512            }
10513        } else {
10514            if ((scanFlags & SCAN_MOVE) != 0) {
10515                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10516                // but we already have this packages package info in the PackageSetting. We just
10517                // use that and derive the native library path based on the new codepath.
10518                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10519                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10520            }
10521
10522            // Set native library paths again. For moves, the path will be updated based on the
10523            // ABIs we've determined above. For non-moves, the path will be updated based on the
10524            // ABIs we determined during compilation, but the path will depend on the final
10525            // package path (after the rename away from the stage path).
10526            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10527        }
10528
10529        // This is a special case for the "system" package, where the ABI is
10530        // dictated by the zygote configuration (and init.rc). We should keep track
10531        // of this ABI so that we can deal with "normal" applications that run under
10532        // the same UID correctly.
10533        if (isPlatformPackage) {
10534            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10535                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10536        }
10537
10538        // If there's a mismatch between the abi-override in the package setting
10539        // and the abiOverride specified for the install. Warn about this because we
10540        // would've already compiled the app without taking the package setting into
10541        // account.
10542        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10543            if (cpuAbiOverride == null && pkg.packageName != null) {
10544                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10545                        " for package " + pkg.packageName);
10546            }
10547        }
10548
10549        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10550        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10551        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10552
10553        // Copy the derived override back to the parsed package, so that we can
10554        // update the package settings accordingly.
10555        pkg.cpuAbiOverride = cpuAbiOverride;
10556
10557        if (DEBUG_ABI_SELECTION) {
10558            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10559                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10560                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10561        }
10562
10563        // Push the derived path down into PackageSettings so we know what to
10564        // clean up at uninstall time.
10565        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10566
10567        if (DEBUG_ABI_SELECTION) {
10568            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10569                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10570                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10571        }
10572
10573        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10574            // We don't do this here during boot because we can do it all
10575            // at once after scanning all existing packages.
10576            //
10577            // We also do this *before* we perform dexopt on this package, so that
10578            // we can avoid redundant dexopts, and also to make sure we've got the
10579            // code and package path correct.
10580            changedAbiCodePath =
10581                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10582        }
10583
10584        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10585                android.Manifest.permission.FACTORY_TEST)) {
10586            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10587        }
10588
10589        if (isSystemApp(pkg)) {
10590            pkgSetting.isOrphaned = true;
10591        }
10592
10593        // Take care of first install / last update times.
10594        final long scanFileTime = getLastModifiedTime(pkg);
10595        if (currentTime != 0) {
10596            if (pkgSetting.firstInstallTime == 0) {
10597                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10598            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10599                pkgSetting.lastUpdateTime = currentTime;
10600            }
10601        } else if (pkgSetting.firstInstallTime == 0) {
10602            // We need *something*.  Take time time stamp of the file.
10603            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10604        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10605            if (scanFileTime != pkgSetting.timeStamp) {
10606                // A package on the system image has changed; consider this
10607                // to be an update.
10608                pkgSetting.lastUpdateTime = scanFileTime;
10609            }
10610        }
10611        pkgSetting.setTimeStamp(scanFileTime);
10612
10613        pkgSetting.pkg = pkg;
10614        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10615        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10616            pkgSetting.versionCode = pkg.getLongVersionCode();
10617        }
10618        // Update volume if needed
10619        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10620        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10621            Slog.i(PackageManagerService.TAG,
10622                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10623                    + " package " + pkg.packageName
10624                    + " volume from " + pkgSetting.volumeUuid
10625                    + " to " + volumeUuid);
10626            pkgSetting.volumeUuid = volumeUuid;
10627        }
10628
10629        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10630    }
10631
10632    /**
10633     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10634     */
10635    private static boolean apkHasCode(String fileName) {
10636        StrictJarFile jarFile = null;
10637        try {
10638            jarFile = new StrictJarFile(fileName,
10639                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10640            return jarFile.findEntry("classes.dex") != null;
10641        } catch (IOException ignore) {
10642        } finally {
10643            try {
10644                if (jarFile != null) {
10645                    jarFile.close();
10646                }
10647            } catch (IOException ignore) {}
10648        }
10649        return false;
10650    }
10651
10652    /**
10653     * Enforces code policy for the package. This ensures that if an APK has
10654     * declared hasCode="true" in its manifest that the APK actually contains
10655     * code.
10656     *
10657     * @throws PackageManagerException If bytecode could not be found when it should exist
10658     */
10659    private static void assertCodePolicy(PackageParser.Package pkg)
10660            throws PackageManagerException {
10661        final boolean shouldHaveCode =
10662                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10663        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10664            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10665                    "Package " + pkg.baseCodePath + " code is missing");
10666        }
10667
10668        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10669            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10670                final boolean splitShouldHaveCode =
10671                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10672                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10673                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10674                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10675                }
10676            }
10677        }
10678    }
10679
10680    /**
10681     * Applies policy to the parsed package based upon the given policy flags.
10682     * Ensures the package is in a good state.
10683     * <p>
10684     * Implementation detail: This method must NOT have any side effect. It would
10685     * ideally be static, but, it requires locks to read system state.
10686     */
10687    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10688            final @ScanFlags int scanFlags) {
10689        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10690            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10691            if (pkg.applicationInfo.isDirectBootAware()) {
10692                // we're direct boot aware; set for all components
10693                for (PackageParser.Service s : pkg.services) {
10694                    s.info.encryptionAware = s.info.directBootAware = true;
10695                }
10696                for (PackageParser.Provider p : pkg.providers) {
10697                    p.info.encryptionAware = p.info.directBootAware = true;
10698                }
10699                for (PackageParser.Activity a : pkg.activities) {
10700                    a.info.encryptionAware = a.info.directBootAware = true;
10701                }
10702                for (PackageParser.Activity r : pkg.receivers) {
10703                    r.info.encryptionAware = r.info.directBootAware = true;
10704                }
10705            }
10706            if (compressedFileExists(pkg.codePath)) {
10707                pkg.isStub = true;
10708            }
10709        } else {
10710            // non system apps can't be flagged as core
10711            pkg.coreApp = false;
10712            // clear flags not applicable to regular apps
10713            pkg.applicationInfo.flags &=
10714                    ~ApplicationInfo.FLAG_PERSISTENT;
10715            pkg.applicationInfo.privateFlags &=
10716                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10717            pkg.applicationInfo.privateFlags &=
10718                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10719            // cap permission priorities
10720            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10721                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10722                    pkg.permissionGroups.get(i).info.priority = 0;
10723                }
10724            }
10725        }
10726        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10727            // clear protected broadcasts
10728            pkg.protectedBroadcasts = null;
10729            // ignore export request for single user receivers
10730            if (pkg.receivers != null) {
10731                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10732                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10733                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10734                        receiver.info.exported = false;
10735                    }
10736                }
10737            }
10738            // ignore export request for single user services
10739            if (pkg.services != null) {
10740                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10741                    final PackageParser.Service service = pkg.services.get(i);
10742                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10743                        service.info.exported = false;
10744                    }
10745                }
10746            }
10747            // ignore export request for single user providers
10748            if (pkg.providers != null) {
10749                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10750                    final PackageParser.Provider provider = pkg.providers.get(i);
10751                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10752                        provider.info.exported = false;
10753                    }
10754                }
10755            }
10756        }
10757
10758        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10759            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10760        }
10761
10762        if ((scanFlags & SCAN_AS_OEM) != 0) {
10763            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10764        }
10765
10766        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10767            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10768        }
10769
10770        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10771            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10772        }
10773
10774        if (!isSystemApp(pkg)) {
10775            // Only system apps can use these features.
10776            pkg.mOriginalPackages = null;
10777            pkg.mRealPackage = null;
10778            pkg.mAdoptPermissions = null;
10779        }
10780    }
10781
10782    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10783            throws PackageManagerException {
10784        if (object == null) {
10785            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10786        }
10787        return object;
10788    }
10789
10790    /**
10791     * Asserts the parsed package is valid according to the given policy. If the
10792     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10793     * <p>
10794     * Implementation detail: This method must NOT have any side effects. It would
10795     * ideally be static, but, it requires locks to read system state.
10796     *
10797     * @throws PackageManagerException If the package fails any of the validation checks
10798     */
10799    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10800            final @ScanFlags int scanFlags)
10801                    throws PackageManagerException {
10802        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10803            assertCodePolicy(pkg);
10804        }
10805
10806        if (pkg.applicationInfo.getCodePath() == null ||
10807                pkg.applicationInfo.getResourcePath() == null) {
10808            // Bail out. The resource and code paths haven't been set.
10809            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10810                    "Code and resource paths haven't been set correctly");
10811        }
10812
10813        // Make sure we're not adding any bogus keyset info
10814        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10815        ksms.assertScannedPackageValid(pkg);
10816
10817        synchronized (mPackages) {
10818            // The special "android" package can only be defined once
10819            if (pkg.packageName.equals("android")) {
10820                if (mAndroidApplication != null) {
10821                    Slog.w(TAG, "*************************************************");
10822                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10823                    Slog.w(TAG, " codePath=" + pkg.codePath);
10824                    Slog.w(TAG, "*************************************************");
10825                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10826                            "Core android package being redefined.  Skipping.");
10827                }
10828            }
10829
10830            // A package name must be unique; don't allow duplicates
10831            if (mPackages.containsKey(pkg.packageName)) {
10832                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10833                        "Application package " + pkg.packageName
10834                        + " already installed.  Skipping duplicate.");
10835            }
10836
10837            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10838                // Static libs have a synthetic package name containing the version
10839                // but we still want the base name to be unique.
10840                if (mPackages.containsKey(pkg.manifestPackageName)) {
10841                    throw new PackageManagerException(
10842                            "Duplicate static shared lib provider package");
10843                }
10844
10845                // Static shared libraries should have at least O target SDK
10846                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10847                    throw new PackageManagerException(
10848                            "Packages declaring static-shared libs must target O SDK or higher");
10849                }
10850
10851                // Package declaring static a shared lib cannot be instant apps
10852                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10853                    throw new PackageManagerException(
10854                            "Packages declaring static-shared libs cannot be instant apps");
10855                }
10856
10857                // Package declaring static a shared lib cannot be renamed since the package
10858                // name is synthetic and apps can't code around package manager internals.
10859                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10860                    throw new PackageManagerException(
10861                            "Packages declaring static-shared libs cannot be renamed");
10862                }
10863
10864                // Package declaring static a shared lib cannot declare child packages
10865                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10866                    throw new PackageManagerException(
10867                            "Packages declaring static-shared libs cannot have child packages");
10868                }
10869
10870                // Package declaring static a shared lib cannot declare dynamic libs
10871                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10872                    throw new PackageManagerException(
10873                            "Packages declaring static-shared libs cannot declare dynamic libs");
10874                }
10875
10876                // Package declaring static a shared lib cannot declare shared users
10877                if (pkg.mSharedUserId != null) {
10878                    throw new PackageManagerException(
10879                            "Packages declaring static-shared libs cannot declare shared users");
10880                }
10881
10882                // Static shared libs cannot declare activities
10883                if (!pkg.activities.isEmpty()) {
10884                    throw new PackageManagerException(
10885                            "Static shared libs cannot declare activities");
10886                }
10887
10888                // Static shared libs cannot declare services
10889                if (!pkg.services.isEmpty()) {
10890                    throw new PackageManagerException(
10891                            "Static shared libs cannot declare services");
10892                }
10893
10894                // Static shared libs cannot declare providers
10895                if (!pkg.providers.isEmpty()) {
10896                    throw new PackageManagerException(
10897                            "Static shared libs cannot declare content providers");
10898                }
10899
10900                // Static shared libs cannot declare receivers
10901                if (!pkg.receivers.isEmpty()) {
10902                    throw new PackageManagerException(
10903                            "Static shared libs cannot declare broadcast receivers");
10904                }
10905
10906                // Static shared libs cannot declare permission groups
10907                if (!pkg.permissionGroups.isEmpty()) {
10908                    throw new PackageManagerException(
10909                            "Static shared libs cannot declare permission groups");
10910                }
10911
10912                // Static shared libs cannot declare permissions
10913                if (!pkg.permissions.isEmpty()) {
10914                    throw new PackageManagerException(
10915                            "Static shared libs cannot declare permissions");
10916                }
10917
10918                // Static shared libs cannot declare protected broadcasts
10919                if (pkg.protectedBroadcasts != null) {
10920                    throw new PackageManagerException(
10921                            "Static shared libs cannot declare protected broadcasts");
10922                }
10923
10924                // Static shared libs cannot be overlay targets
10925                if (pkg.mOverlayTarget != null) {
10926                    throw new PackageManagerException(
10927                            "Static shared libs cannot be overlay targets");
10928                }
10929
10930                // The version codes must be ordered as lib versions
10931                long minVersionCode = Long.MIN_VALUE;
10932                long maxVersionCode = Long.MAX_VALUE;
10933
10934                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10935                        pkg.staticSharedLibName);
10936                if (versionedLib != null) {
10937                    final int versionCount = versionedLib.size();
10938                    for (int i = 0; i < versionCount; i++) {
10939                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10940                        final long libVersionCode = libInfo.getDeclaringPackage()
10941                                .getLongVersionCode();
10942                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10943                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10944                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10945                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10946                        } else {
10947                            minVersionCode = maxVersionCode = libVersionCode;
10948                            break;
10949                        }
10950                    }
10951                }
10952                if (pkg.getLongVersionCode() < minVersionCode
10953                        || pkg.getLongVersionCode() > maxVersionCode) {
10954                    throw new PackageManagerException("Static shared"
10955                            + " lib version codes must be ordered as lib versions");
10956                }
10957            }
10958
10959            // Only privileged apps and updated privileged apps can add child packages.
10960            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10961                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10962                    throw new PackageManagerException("Only privileged apps can add child "
10963                            + "packages. Ignoring package " + pkg.packageName);
10964                }
10965                final int childCount = pkg.childPackages.size();
10966                for (int i = 0; i < childCount; i++) {
10967                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10968                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10969                            childPkg.packageName)) {
10970                        throw new PackageManagerException("Can't override child of "
10971                                + "another disabled app. Ignoring package " + pkg.packageName);
10972                    }
10973                }
10974            }
10975
10976            // If we're only installing presumed-existing packages, require that the
10977            // scanned APK is both already known and at the path previously established
10978            // for it.  Previously unknown packages we pick up normally, but if we have an
10979            // a priori expectation about this package's install presence, enforce it.
10980            // With a singular exception for new system packages. When an OTA contains
10981            // a new system package, we allow the codepath to change from a system location
10982            // to the user-installed location. If we don't allow this change, any newer,
10983            // user-installed version of the application will be ignored.
10984            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10985                if (mExpectingBetter.containsKey(pkg.packageName)) {
10986                    logCriticalInfo(Log.WARN,
10987                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10988                } else {
10989                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10990                    if (known != null) {
10991                        if (DEBUG_PACKAGE_SCANNING) {
10992                            Log.d(TAG, "Examining " + pkg.codePath
10993                                    + " and requiring known paths " + known.codePathString
10994                                    + " & " + known.resourcePathString);
10995                        }
10996                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10997                                || !pkg.applicationInfo.getResourcePath().equals(
10998                                        known.resourcePathString)) {
10999                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11000                                    "Application package " + pkg.packageName
11001                                    + " found at " + pkg.applicationInfo.getCodePath()
11002                                    + " but expected at " + known.codePathString
11003                                    + "; ignoring.");
11004                        }
11005                    } else {
11006                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11007                                "Application package " + pkg.packageName
11008                                + " not found; ignoring.");
11009                    }
11010                }
11011            }
11012
11013            // Verify that this new package doesn't have any content providers
11014            // that conflict with existing packages.  Only do this if the
11015            // package isn't already installed, since we don't want to break
11016            // things that are installed.
11017            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11018                final int N = pkg.providers.size();
11019                int i;
11020                for (i=0; i<N; i++) {
11021                    PackageParser.Provider p = pkg.providers.get(i);
11022                    if (p.info.authority != null) {
11023                        String names[] = p.info.authority.split(";");
11024                        for (int j = 0; j < names.length; j++) {
11025                            if (mProvidersByAuthority.containsKey(names[j])) {
11026                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11027                                final String otherPackageName =
11028                                        ((other != null && other.getComponentName() != null) ?
11029                                                other.getComponentName().getPackageName() : "?");
11030                                throw new PackageManagerException(
11031                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11032                                        "Can't install because provider name " + names[j]
11033                                                + " (in package " + pkg.applicationInfo.packageName
11034                                                + ") is already used by " + otherPackageName);
11035                            }
11036                        }
11037                    }
11038                }
11039            }
11040
11041            // Verify that packages sharing a user with a privileged app are marked as privileged.
11042            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11043                SharedUserSetting sharedUserSetting = null;
11044                try {
11045                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11046                } catch (PackageManagerException ignore) {}
11047                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11048                    // Exempt SharedUsers signed with the platform key.
11049                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11050                    if ((platformPkgSetting.signatures.mSigningDetails
11051                            != PackageParser.SigningDetails.UNKNOWN)
11052                            && (compareSignatures(
11053                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11054                                    pkg.mSigningDetails.signatures)
11055                                            != PackageManager.SIGNATURE_MATCH)) {
11056                        throw new PackageManagerException("Apps that share a user with a " +
11057                                "privileged app must themselves be marked as privileged. " +
11058                                pkg.packageName + " shares privileged user " +
11059                                pkg.mSharedUserId + ".");
11060                    }
11061                }
11062            }
11063
11064            // Apply policies specific for runtime resource overlays (RROs).
11065            if (pkg.mOverlayTarget != null) {
11066                // System overlays have some restrictions on their use of the 'static' state.
11067                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11068                    // We are scanning a system overlay. This can be the first scan of the
11069                    // system/vendor/oem partition, or an update to the system overlay.
11070                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11071                        // This must be an update to a system overlay.
11072                        final PackageSetting previousPkg = assertNotNull(
11073                                mSettings.getPackageLPr(pkg.packageName),
11074                                "previous package state not present");
11075
11076                        // Static overlays cannot be updated.
11077                        if (previousPkg.pkg.mOverlayIsStatic) {
11078                            throw new PackageManagerException("Overlay " + pkg.packageName +
11079                                    " is static and cannot be upgraded.");
11080                        // Non-static overlays cannot be converted to static overlays.
11081                        } else if (pkg.mOverlayIsStatic) {
11082                            throw new PackageManagerException("Overlay " + pkg.packageName +
11083                                    " cannot be upgraded into a static overlay.");
11084                        }
11085                    }
11086                } else {
11087                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11088                    if (pkg.mOverlayIsStatic) {
11089                        throw new PackageManagerException("Overlay " + pkg.packageName +
11090                                " is static but not pre-installed.");
11091                    }
11092
11093                    // The only case where we allow installation of a non-system overlay is when
11094                    // its signature is signed with the platform certificate.
11095                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11096                    if ((platformPkgSetting.signatures.mSigningDetails
11097                            != PackageParser.SigningDetails.UNKNOWN)
11098                            && (compareSignatures(
11099                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11100                                    pkg.mSigningDetails.signatures)
11101                                            != PackageManager.SIGNATURE_MATCH)) {
11102                        throw new PackageManagerException("Overlay " + pkg.packageName +
11103                                " must be signed with the platform certificate.");
11104                    }
11105                }
11106            }
11107        }
11108    }
11109
11110    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11111            int type, String declaringPackageName, long declaringVersionCode) {
11112        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11113        if (versionedLib == null) {
11114            versionedLib = new LongSparseArray<>();
11115            mSharedLibraries.put(name, versionedLib);
11116            if (type == SharedLibraryInfo.TYPE_STATIC) {
11117                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11118            }
11119        } else if (versionedLib.indexOfKey(version) >= 0) {
11120            return false;
11121        }
11122        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11123                version, type, declaringPackageName, declaringVersionCode);
11124        versionedLib.put(version, libEntry);
11125        return true;
11126    }
11127
11128    private boolean removeSharedLibraryLPw(String name, long version) {
11129        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11130        if (versionedLib == null) {
11131            return false;
11132        }
11133        final int libIdx = versionedLib.indexOfKey(version);
11134        if (libIdx < 0) {
11135            return false;
11136        }
11137        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11138        versionedLib.remove(version);
11139        if (versionedLib.size() <= 0) {
11140            mSharedLibraries.remove(name);
11141            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11142                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11143                        .getPackageName());
11144            }
11145        }
11146        return true;
11147    }
11148
11149    /**
11150     * Adds a scanned package to the system. When this method is finished, the package will
11151     * be available for query, resolution, etc...
11152     */
11153    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11154            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11155        final String pkgName = pkg.packageName;
11156        if (mCustomResolverComponentName != null &&
11157                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11158            setUpCustomResolverActivity(pkg);
11159        }
11160
11161        if (pkg.packageName.equals("android")) {
11162            synchronized (mPackages) {
11163                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11164                    // Set up information for our fall-back user intent resolution activity.
11165                    mPlatformPackage = pkg;
11166                    pkg.mVersionCode = mSdkVersion;
11167                    pkg.mVersionCodeMajor = 0;
11168                    mAndroidApplication = pkg.applicationInfo;
11169                    if (!mResolverReplaced) {
11170                        mResolveActivity.applicationInfo = mAndroidApplication;
11171                        mResolveActivity.name = ResolverActivity.class.getName();
11172                        mResolveActivity.packageName = mAndroidApplication.packageName;
11173                        mResolveActivity.processName = "system:ui";
11174                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11175                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11176                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11177                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11178                        mResolveActivity.exported = true;
11179                        mResolveActivity.enabled = true;
11180                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11181                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11182                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11183                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11184                                | ActivityInfo.CONFIG_ORIENTATION
11185                                | ActivityInfo.CONFIG_KEYBOARD
11186                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11187                        mResolveInfo.activityInfo = mResolveActivity;
11188                        mResolveInfo.priority = 0;
11189                        mResolveInfo.preferredOrder = 0;
11190                        mResolveInfo.match = 0;
11191                        mResolveComponentName = new ComponentName(
11192                                mAndroidApplication.packageName, mResolveActivity.name);
11193                    }
11194                }
11195            }
11196        }
11197
11198        ArrayList<PackageParser.Package> clientLibPkgs = null;
11199        // writer
11200        synchronized (mPackages) {
11201            boolean hasStaticSharedLibs = false;
11202
11203            // Any app can add new static shared libraries
11204            if (pkg.staticSharedLibName != null) {
11205                // Static shared libs don't allow renaming as they have synthetic package
11206                // names to allow install of multiple versions, so use name from manifest.
11207                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11208                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11209                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11210                    hasStaticSharedLibs = true;
11211                } else {
11212                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11213                                + pkg.staticSharedLibName + " already exists; skipping");
11214                }
11215                // Static shared libs cannot be updated once installed since they
11216                // use synthetic package name which includes the version code, so
11217                // not need to update other packages's shared lib dependencies.
11218            }
11219
11220            if (!hasStaticSharedLibs
11221                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11222                // Only system apps can add new dynamic shared libraries.
11223                if (pkg.libraryNames != null) {
11224                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11225                        String name = pkg.libraryNames.get(i);
11226                        boolean allowed = false;
11227                        if (pkg.isUpdatedSystemApp()) {
11228                            // New library entries can only be added through the
11229                            // system image.  This is important to get rid of a lot
11230                            // of nasty edge cases: for example if we allowed a non-
11231                            // system update of the app to add a library, then uninstalling
11232                            // the update would make the library go away, and assumptions
11233                            // we made such as through app install filtering would now
11234                            // have allowed apps on the device which aren't compatible
11235                            // with it.  Better to just have the restriction here, be
11236                            // conservative, and create many fewer cases that can negatively
11237                            // impact the user experience.
11238                            final PackageSetting sysPs = mSettings
11239                                    .getDisabledSystemPkgLPr(pkg.packageName);
11240                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11241                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11242                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11243                                        allowed = true;
11244                                        break;
11245                                    }
11246                                }
11247                            }
11248                        } else {
11249                            allowed = true;
11250                        }
11251                        if (allowed) {
11252                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11253                                    SharedLibraryInfo.VERSION_UNDEFINED,
11254                                    SharedLibraryInfo.TYPE_DYNAMIC,
11255                                    pkg.packageName, pkg.getLongVersionCode())) {
11256                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11257                                        + name + " already exists; skipping");
11258                            }
11259                        } else {
11260                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11261                                    + name + " that is not declared on system image; skipping");
11262                        }
11263                    }
11264
11265                    if ((scanFlags & SCAN_BOOTING) == 0) {
11266                        // If we are not booting, we need to update any applications
11267                        // that are clients of our shared library.  If we are booting,
11268                        // this will all be done once the scan is complete.
11269                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11270                    }
11271                }
11272            }
11273        }
11274
11275        if ((scanFlags & SCAN_BOOTING) != 0) {
11276            // No apps can run during boot scan, so they don't need to be frozen
11277        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11278            // Caller asked to not kill app, so it's probably not frozen
11279        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11280            // Caller asked us to ignore frozen check for some reason; they
11281            // probably didn't know the package name
11282        } else {
11283            // We're doing major surgery on this package, so it better be frozen
11284            // right now to keep it from launching
11285            checkPackageFrozen(pkgName);
11286        }
11287
11288        // Also need to kill any apps that are dependent on the library.
11289        if (clientLibPkgs != null) {
11290            for (int i=0; i<clientLibPkgs.size(); i++) {
11291                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11292                killApplication(clientPkg.applicationInfo.packageName,
11293                        clientPkg.applicationInfo.uid, "update lib");
11294            }
11295        }
11296
11297        // writer
11298        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11299
11300        synchronized (mPackages) {
11301            // We don't expect installation to fail beyond this point
11302
11303            // Add the new setting to mSettings
11304            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11305            // Add the new setting to mPackages
11306            mPackages.put(pkg.applicationInfo.packageName, pkg);
11307            // Make sure we don't accidentally delete its data.
11308            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11309            while (iter.hasNext()) {
11310                PackageCleanItem item = iter.next();
11311                if (pkgName.equals(item.packageName)) {
11312                    iter.remove();
11313                }
11314            }
11315
11316            // Add the package's KeySets to the global KeySetManagerService
11317            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11318            ksms.addScannedPackageLPw(pkg);
11319
11320            int N = pkg.providers.size();
11321            StringBuilder r = null;
11322            int i;
11323            for (i=0; i<N; i++) {
11324                PackageParser.Provider p = pkg.providers.get(i);
11325                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11326                        p.info.processName);
11327                mProviders.addProvider(p);
11328                p.syncable = p.info.isSyncable;
11329                if (p.info.authority != null) {
11330                    String names[] = p.info.authority.split(";");
11331                    p.info.authority = null;
11332                    for (int j = 0; j < names.length; j++) {
11333                        if (j == 1 && p.syncable) {
11334                            // We only want the first authority for a provider to possibly be
11335                            // syncable, so if we already added this provider using a different
11336                            // authority clear the syncable flag. We copy the provider before
11337                            // changing it because the mProviders object contains a reference
11338                            // to a provider that we don't want to change.
11339                            // Only do this for the second authority since the resulting provider
11340                            // object can be the same for all future authorities for this provider.
11341                            p = new PackageParser.Provider(p);
11342                            p.syncable = false;
11343                        }
11344                        if (!mProvidersByAuthority.containsKey(names[j])) {
11345                            mProvidersByAuthority.put(names[j], p);
11346                            if (p.info.authority == null) {
11347                                p.info.authority = names[j];
11348                            } else {
11349                                p.info.authority = p.info.authority + ";" + names[j];
11350                            }
11351                            if (DEBUG_PACKAGE_SCANNING) {
11352                                if (chatty)
11353                                    Log.d(TAG, "Registered content provider: " + names[j]
11354                                            + ", className = " + p.info.name + ", isSyncable = "
11355                                            + p.info.isSyncable);
11356                            }
11357                        } else {
11358                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11359                            Slog.w(TAG, "Skipping provider name " + names[j] +
11360                                    " (in package " + pkg.applicationInfo.packageName +
11361                                    "): name already used by "
11362                                    + ((other != null && other.getComponentName() != null)
11363                                            ? other.getComponentName().getPackageName() : "?"));
11364                        }
11365                    }
11366                }
11367                if (chatty) {
11368                    if (r == null) {
11369                        r = new StringBuilder(256);
11370                    } else {
11371                        r.append(' ');
11372                    }
11373                    r.append(p.info.name);
11374                }
11375            }
11376            if (r != null) {
11377                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11378            }
11379
11380            N = pkg.services.size();
11381            r = null;
11382            for (i=0; i<N; i++) {
11383                PackageParser.Service s = pkg.services.get(i);
11384                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11385                        s.info.processName);
11386                mServices.addService(s);
11387                if (chatty) {
11388                    if (r == null) {
11389                        r = new StringBuilder(256);
11390                    } else {
11391                        r.append(' ');
11392                    }
11393                    r.append(s.info.name);
11394                }
11395            }
11396            if (r != null) {
11397                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11398            }
11399
11400            N = pkg.receivers.size();
11401            r = null;
11402            for (i=0; i<N; i++) {
11403                PackageParser.Activity a = pkg.receivers.get(i);
11404                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11405                        a.info.processName);
11406                mReceivers.addActivity(a, "receiver");
11407                if (chatty) {
11408                    if (r == null) {
11409                        r = new StringBuilder(256);
11410                    } else {
11411                        r.append(' ');
11412                    }
11413                    r.append(a.info.name);
11414                }
11415            }
11416            if (r != null) {
11417                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11418            }
11419
11420            N = pkg.activities.size();
11421            r = null;
11422            for (i=0; i<N; i++) {
11423                PackageParser.Activity a = pkg.activities.get(i);
11424                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11425                        a.info.processName);
11426                mActivities.addActivity(a, "activity");
11427                if (chatty) {
11428                    if (r == null) {
11429                        r = new StringBuilder(256);
11430                    } else {
11431                        r.append(' ');
11432                    }
11433                    r.append(a.info.name);
11434                }
11435            }
11436            if (r != null) {
11437                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11438            }
11439
11440            // Don't allow ephemeral applications to define new permissions groups.
11441            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11442                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11443                        + " ignored: instant apps cannot define new permission groups.");
11444            } else {
11445                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11446            }
11447
11448            // Don't allow ephemeral applications to define new permissions.
11449            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11450                Slog.w(TAG, "Permissions from package " + pkg.packageName
11451                        + " ignored: instant apps cannot define new permissions.");
11452            } else {
11453                mPermissionManager.addAllPermissions(pkg, chatty);
11454            }
11455
11456            N = pkg.instrumentation.size();
11457            r = null;
11458            for (i=0; i<N; i++) {
11459                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11460                a.info.packageName = pkg.applicationInfo.packageName;
11461                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11462                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11463                a.info.splitNames = pkg.splitNames;
11464                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11465                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11466                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11467                a.info.dataDir = pkg.applicationInfo.dataDir;
11468                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11469                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11470                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11471                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11472                mInstrumentation.put(a.getComponentName(), a);
11473                if (chatty) {
11474                    if (r == null) {
11475                        r = new StringBuilder(256);
11476                    } else {
11477                        r.append(' ');
11478                    }
11479                    r.append(a.info.name);
11480                }
11481            }
11482            if (r != null) {
11483                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11484            }
11485
11486            if (pkg.protectedBroadcasts != null) {
11487                N = pkg.protectedBroadcasts.size();
11488                synchronized (mProtectedBroadcasts) {
11489                    for (i = 0; i < N; i++) {
11490                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11491                    }
11492                }
11493            }
11494        }
11495
11496        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11497    }
11498
11499    /**
11500     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11501     * is derived purely on the basis of the contents of {@code scanFile} and
11502     * {@code cpuAbiOverride}.
11503     *
11504     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11505     */
11506    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11507            boolean extractLibs)
11508                    throws PackageManagerException {
11509        // Give ourselves some initial paths; we'll come back for another
11510        // pass once we've determined ABI below.
11511        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11512
11513        // We would never need to extract libs for forward-locked and external packages,
11514        // since the container service will do it for us. We shouldn't attempt to
11515        // extract libs from system app when it was not updated.
11516        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11517                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11518            extractLibs = false;
11519        }
11520
11521        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11522        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11523
11524        NativeLibraryHelper.Handle handle = null;
11525        try {
11526            handle = NativeLibraryHelper.Handle.create(pkg);
11527            // TODO(multiArch): This can be null for apps that didn't go through the
11528            // usual installation process. We can calculate it again, like we
11529            // do during install time.
11530            //
11531            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11532            // unnecessary.
11533            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11534
11535            // Null out the abis so that they can be recalculated.
11536            pkg.applicationInfo.primaryCpuAbi = null;
11537            pkg.applicationInfo.secondaryCpuAbi = null;
11538            if (isMultiArch(pkg.applicationInfo)) {
11539                // Warn if we've set an abiOverride for multi-lib packages..
11540                // By definition, we need to copy both 32 and 64 bit libraries for
11541                // such packages.
11542                if (pkg.cpuAbiOverride != null
11543                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11544                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11545                }
11546
11547                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11548                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11549                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11550                    if (extractLibs) {
11551                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11552                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11553                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11554                                useIsaSpecificSubdirs);
11555                    } else {
11556                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11557                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11558                    }
11559                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11560                }
11561
11562                // Shared library native code should be in the APK zip aligned
11563                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11564                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11565                            "Shared library native lib extraction not supported");
11566                }
11567
11568                maybeThrowExceptionForMultiArchCopy(
11569                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11570
11571                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11572                    if (extractLibs) {
11573                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11574                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11575                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11576                                useIsaSpecificSubdirs);
11577                    } else {
11578                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11579                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11580                    }
11581                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11582                }
11583
11584                maybeThrowExceptionForMultiArchCopy(
11585                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11586
11587                if (abi64 >= 0) {
11588                    // Shared library native libs should be in the APK zip aligned
11589                    if (extractLibs && pkg.isLibrary()) {
11590                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11591                                "Shared library native lib extraction not supported");
11592                    }
11593                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11594                }
11595
11596                if (abi32 >= 0) {
11597                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11598                    if (abi64 >= 0) {
11599                        if (pkg.use32bitAbi) {
11600                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11601                            pkg.applicationInfo.primaryCpuAbi = abi;
11602                        } else {
11603                            pkg.applicationInfo.secondaryCpuAbi = abi;
11604                        }
11605                    } else {
11606                        pkg.applicationInfo.primaryCpuAbi = abi;
11607                    }
11608                }
11609            } else {
11610                String[] abiList = (cpuAbiOverride != null) ?
11611                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11612
11613                // Enable gross and lame hacks for apps that are built with old
11614                // SDK tools. We must scan their APKs for renderscript bitcode and
11615                // not launch them if it's present. Don't bother checking on devices
11616                // that don't have 64 bit support.
11617                boolean needsRenderScriptOverride = false;
11618                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11619                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11620                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11621                    needsRenderScriptOverride = true;
11622                }
11623
11624                final int copyRet;
11625                if (extractLibs) {
11626                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11627                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11628                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11629                } else {
11630                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11631                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11632                }
11633                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11634
11635                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11636                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11637                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11638                }
11639
11640                if (copyRet >= 0) {
11641                    // Shared libraries that have native libs must be multi-architecture
11642                    if (pkg.isLibrary()) {
11643                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11644                                "Shared library with native libs must be multiarch");
11645                    }
11646                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11647                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11648                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11649                } else if (needsRenderScriptOverride) {
11650                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11651                }
11652            }
11653        } catch (IOException ioe) {
11654            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11655        } finally {
11656            IoUtils.closeQuietly(handle);
11657        }
11658
11659        // Now that we've calculated the ABIs and determined if it's an internal app,
11660        // we will go ahead and populate the nativeLibraryPath.
11661        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11662    }
11663
11664    /**
11665     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11666     * i.e, so that all packages can be run inside a single process if required.
11667     *
11668     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11669     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11670     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11671     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11672     * updating a package that belongs to a shared user.
11673     *
11674     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11675     * adds unnecessary complexity.
11676     */
11677    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11678            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11679        List<String> changedAbiCodePath = null;
11680        String requiredInstructionSet = null;
11681        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11682            requiredInstructionSet = VMRuntime.getInstructionSet(
11683                     scannedPackage.applicationInfo.primaryCpuAbi);
11684        }
11685
11686        PackageSetting requirer = null;
11687        for (PackageSetting ps : packagesForUser) {
11688            // If packagesForUser contains scannedPackage, we skip it. This will happen
11689            // when scannedPackage is an update of an existing package. Without this check,
11690            // we will never be able to change the ABI of any package belonging to a shared
11691            // user, even if it's compatible with other packages.
11692            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11693                if (ps.primaryCpuAbiString == null) {
11694                    continue;
11695                }
11696
11697                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11698                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11699                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11700                    // this but there's not much we can do.
11701                    String errorMessage = "Instruction set mismatch, "
11702                            + ((requirer == null) ? "[caller]" : requirer)
11703                            + " requires " + requiredInstructionSet + " whereas " + ps
11704                            + " requires " + instructionSet;
11705                    Slog.w(TAG, errorMessage);
11706                }
11707
11708                if (requiredInstructionSet == null) {
11709                    requiredInstructionSet = instructionSet;
11710                    requirer = ps;
11711                }
11712            }
11713        }
11714
11715        if (requiredInstructionSet != null) {
11716            String adjustedAbi;
11717            if (requirer != null) {
11718                // requirer != null implies that either scannedPackage was null or that scannedPackage
11719                // did not require an ABI, in which case we have to adjust scannedPackage to match
11720                // the ABI of the set (which is the same as requirer's ABI)
11721                adjustedAbi = requirer.primaryCpuAbiString;
11722                if (scannedPackage != null) {
11723                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11724                }
11725            } else {
11726                // requirer == null implies that we're updating all ABIs in the set to
11727                // match scannedPackage.
11728                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11729            }
11730
11731            for (PackageSetting ps : packagesForUser) {
11732                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11733                    if (ps.primaryCpuAbiString != null) {
11734                        continue;
11735                    }
11736
11737                    ps.primaryCpuAbiString = adjustedAbi;
11738                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11739                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11740                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11741                        if (DEBUG_ABI_SELECTION) {
11742                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11743                                    + " (requirer="
11744                                    + (requirer != null ? requirer.pkg : "null")
11745                                    + ", scannedPackage="
11746                                    + (scannedPackage != null ? scannedPackage : "null")
11747                                    + ")");
11748                        }
11749                        if (changedAbiCodePath == null) {
11750                            changedAbiCodePath = new ArrayList<>();
11751                        }
11752                        changedAbiCodePath.add(ps.codePathString);
11753                    }
11754                }
11755            }
11756        }
11757        return changedAbiCodePath;
11758    }
11759
11760    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11761        synchronized (mPackages) {
11762            mResolverReplaced = true;
11763            // Set up information for custom user intent resolution activity.
11764            mResolveActivity.applicationInfo = pkg.applicationInfo;
11765            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11766            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11767            mResolveActivity.processName = pkg.applicationInfo.packageName;
11768            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11769            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11770                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11771            mResolveActivity.theme = 0;
11772            mResolveActivity.exported = true;
11773            mResolveActivity.enabled = true;
11774            mResolveInfo.activityInfo = mResolveActivity;
11775            mResolveInfo.priority = 0;
11776            mResolveInfo.preferredOrder = 0;
11777            mResolveInfo.match = 0;
11778            mResolveComponentName = mCustomResolverComponentName;
11779            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11780                    mResolveComponentName);
11781        }
11782    }
11783
11784    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11785        if (installerActivity == null) {
11786            if (DEBUG_INSTANT) {
11787                Slog.d(TAG, "Clear ephemeral installer activity");
11788            }
11789            mInstantAppInstallerActivity = null;
11790            return;
11791        }
11792
11793        if (DEBUG_INSTANT) {
11794            Slog.d(TAG, "Set ephemeral installer activity: "
11795                    + installerActivity.getComponentName());
11796        }
11797        // Set up information for ephemeral installer activity
11798        mInstantAppInstallerActivity = installerActivity;
11799        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11800                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11801        mInstantAppInstallerActivity.exported = true;
11802        mInstantAppInstallerActivity.enabled = true;
11803        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11804        mInstantAppInstallerInfo.priority = 1;
11805        mInstantAppInstallerInfo.preferredOrder = 1;
11806        mInstantAppInstallerInfo.isDefault = true;
11807        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11808                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11809    }
11810
11811    private static String calculateBundledApkRoot(final String codePathString) {
11812        final File codePath = new File(codePathString);
11813        final File codeRoot;
11814        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11815            codeRoot = Environment.getRootDirectory();
11816        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11817            codeRoot = Environment.getOemDirectory();
11818        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11819            codeRoot = Environment.getVendorDirectory();
11820        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11821            codeRoot = Environment.getOdmDirectory();
11822        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11823            codeRoot = Environment.getProductDirectory();
11824        } else {
11825            // Unrecognized code path; take its top real segment as the apk root:
11826            // e.g. /something/app/blah.apk => /something
11827            try {
11828                File f = codePath.getCanonicalFile();
11829                File parent = f.getParentFile();    // non-null because codePath is a file
11830                File tmp;
11831                while ((tmp = parent.getParentFile()) != null) {
11832                    f = parent;
11833                    parent = tmp;
11834                }
11835                codeRoot = f;
11836                Slog.w(TAG, "Unrecognized code path "
11837                        + codePath + " - using " + codeRoot);
11838            } catch (IOException e) {
11839                // Can't canonicalize the code path -- shenanigans?
11840                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11841                return Environment.getRootDirectory().getPath();
11842            }
11843        }
11844        return codeRoot.getPath();
11845    }
11846
11847    /**
11848     * Derive and set the location of native libraries for the given package,
11849     * which varies depending on where and how the package was installed.
11850     */
11851    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11852        final ApplicationInfo info = pkg.applicationInfo;
11853        final String codePath = pkg.codePath;
11854        final File codeFile = new File(codePath);
11855        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11856        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11857
11858        info.nativeLibraryRootDir = null;
11859        info.nativeLibraryRootRequiresIsa = false;
11860        info.nativeLibraryDir = null;
11861        info.secondaryNativeLibraryDir = null;
11862
11863        if (isApkFile(codeFile)) {
11864            // Monolithic install
11865            if (bundledApp) {
11866                // If "/system/lib64/apkname" exists, assume that is the per-package
11867                // native library directory to use; otherwise use "/system/lib/apkname".
11868                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11869                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11870                        getPrimaryInstructionSet(info));
11871
11872                // This is a bundled system app so choose the path based on the ABI.
11873                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11874                // is just the default path.
11875                final String apkName = deriveCodePathName(codePath);
11876                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11877                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11878                        apkName).getAbsolutePath();
11879
11880                if (info.secondaryCpuAbi != null) {
11881                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11882                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11883                            secondaryLibDir, apkName).getAbsolutePath();
11884                }
11885            } else if (asecApp) {
11886                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11887                        .getAbsolutePath();
11888            } else {
11889                final String apkName = deriveCodePathName(codePath);
11890                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11891                        .getAbsolutePath();
11892            }
11893
11894            info.nativeLibraryRootRequiresIsa = false;
11895            info.nativeLibraryDir = info.nativeLibraryRootDir;
11896        } else {
11897            // Cluster install
11898            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11899            info.nativeLibraryRootRequiresIsa = true;
11900
11901            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11902                    getPrimaryInstructionSet(info)).getAbsolutePath();
11903
11904            if (info.secondaryCpuAbi != null) {
11905                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11906                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11907            }
11908        }
11909    }
11910
11911    /**
11912     * Calculate the abis and roots for a bundled app. These can uniquely
11913     * be determined from the contents of the system partition, i.e whether
11914     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11915     * of this information, and instead assume that the system was built
11916     * sensibly.
11917     */
11918    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11919                                           PackageSetting pkgSetting) {
11920        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11921
11922        // If "/system/lib64/apkname" exists, assume that is the per-package
11923        // native library directory to use; otherwise use "/system/lib/apkname".
11924        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11925        setBundledAppAbi(pkg, apkRoot, apkName);
11926        // pkgSetting might be null during rescan following uninstall of updates
11927        // to a bundled app, so accommodate that possibility.  The settings in
11928        // that case will be established later from the parsed package.
11929        //
11930        // If the settings aren't null, sync them up with what we've just derived.
11931        // note that apkRoot isn't stored in the package settings.
11932        if (pkgSetting != null) {
11933            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11934            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11935        }
11936    }
11937
11938    /**
11939     * Deduces the ABI of a bundled app and sets the relevant fields on the
11940     * parsed pkg object.
11941     *
11942     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11943     *        under which system libraries are installed.
11944     * @param apkName the name of the installed package.
11945     */
11946    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11947        final File codeFile = new File(pkg.codePath);
11948
11949        final boolean has64BitLibs;
11950        final boolean has32BitLibs;
11951        if (isApkFile(codeFile)) {
11952            // Monolithic install
11953            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11954            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11955        } else {
11956            // Cluster install
11957            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11958            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11959                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11960                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11961                has64BitLibs = (new File(rootDir, isa)).exists();
11962            } else {
11963                has64BitLibs = false;
11964            }
11965            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11966                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11967                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11968                has32BitLibs = (new File(rootDir, isa)).exists();
11969            } else {
11970                has32BitLibs = false;
11971            }
11972        }
11973
11974        if (has64BitLibs && !has32BitLibs) {
11975            // The package has 64 bit libs, but not 32 bit libs. Its primary
11976            // ABI should be 64 bit. We can safely assume here that the bundled
11977            // native libraries correspond to the most preferred ABI in the list.
11978
11979            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11980            pkg.applicationInfo.secondaryCpuAbi = null;
11981        } else if (has32BitLibs && !has64BitLibs) {
11982            // The package has 32 bit libs but not 64 bit libs. Its primary
11983            // ABI should be 32 bit.
11984
11985            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11986            pkg.applicationInfo.secondaryCpuAbi = null;
11987        } else if (has32BitLibs && has64BitLibs) {
11988            // The application has both 64 and 32 bit bundled libraries. We check
11989            // here that the app declares multiArch support, and warn if it doesn't.
11990            //
11991            // We will be lenient here and record both ABIs. The primary will be the
11992            // ABI that's higher on the list, i.e, a device that's configured to prefer
11993            // 64 bit apps will see a 64 bit primary ABI,
11994
11995            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11996                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11997            }
11998
11999            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12000                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12001                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12002            } else {
12003                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12004                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12005            }
12006        } else {
12007            pkg.applicationInfo.primaryCpuAbi = null;
12008            pkg.applicationInfo.secondaryCpuAbi = null;
12009        }
12010    }
12011
12012    private void killApplication(String pkgName, int appId, String reason) {
12013        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12014    }
12015
12016    private void killApplication(String pkgName, int appId, int userId, String reason) {
12017        // Request the ActivityManager to kill the process(only for existing packages)
12018        // so that we do not end up in a confused state while the user is still using the older
12019        // version of the application while the new one gets installed.
12020        final long token = Binder.clearCallingIdentity();
12021        try {
12022            IActivityManager am = ActivityManager.getService();
12023            if (am != null) {
12024                try {
12025                    am.killApplication(pkgName, appId, userId, reason);
12026                } catch (RemoteException e) {
12027                }
12028            }
12029        } finally {
12030            Binder.restoreCallingIdentity(token);
12031        }
12032    }
12033
12034    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12035        // Remove the parent package setting
12036        PackageSetting ps = (PackageSetting) pkg.mExtras;
12037        if (ps != null) {
12038            removePackageLI(ps, chatty);
12039        }
12040        // Remove the child package setting
12041        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12042        for (int i = 0; i < childCount; i++) {
12043            PackageParser.Package childPkg = pkg.childPackages.get(i);
12044            ps = (PackageSetting) childPkg.mExtras;
12045            if (ps != null) {
12046                removePackageLI(ps, chatty);
12047            }
12048        }
12049    }
12050
12051    void removePackageLI(PackageSetting ps, boolean chatty) {
12052        if (DEBUG_INSTALL) {
12053            if (chatty)
12054                Log.d(TAG, "Removing package " + ps.name);
12055        }
12056
12057        // writer
12058        synchronized (mPackages) {
12059            mPackages.remove(ps.name);
12060            final PackageParser.Package pkg = ps.pkg;
12061            if (pkg != null) {
12062                cleanPackageDataStructuresLILPw(pkg, chatty);
12063            }
12064        }
12065    }
12066
12067    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12068        if (DEBUG_INSTALL) {
12069            if (chatty)
12070                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12071        }
12072
12073        // writer
12074        synchronized (mPackages) {
12075            // Remove the parent package
12076            mPackages.remove(pkg.applicationInfo.packageName);
12077            cleanPackageDataStructuresLILPw(pkg, chatty);
12078
12079            // Remove the child packages
12080            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12081            for (int i = 0; i < childCount; i++) {
12082                PackageParser.Package childPkg = pkg.childPackages.get(i);
12083                mPackages.remove(childPkg.applicationInfo.packageName);
12084                cleanPackageDataStructuresLILPw(childPkg, chatty);
12085            }
12086        }
12087    }
12088
12089    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12090        int N = pkg.providers.size();
12091        StringBuilder r = null;
12092        int i;
12093        for (i=0; i<N; i++) {
12094            PackageParser.Provider p = pkg.providers.get(i);
12095            mProviders.removeProvider(p);
12096            if (p.info.authority == null) {
12097
12098                /* There was another ContentProvider with this authority when
12099                 * this app was installed so this authority is null,
12100                 * Ignore it as we don't have to unregister the provider.
12101                 */
12102                continue;
12103            }
12104            String names[] = p.info.authority.split(";");
12105            for (int j = 0; j < names.length; j++) {
12106                if (mProvidersByAuthority.get(names[j]) == p) {
12107                    mProvidersByAuthority.remove(names[j]);
12108                    if (DEBUG_REMOVE) {
12109                        if (chatty)
12110                            Log.d(TAG, "Unregistered content provider: " + names[j]
12111                                    + ", className = " + p.info.name + ", isSyncable = "
12112                                    + p.info.isSyncable);
12113                    }
12114                }
12115            }
12116            if (DEBUG_REMOVE && chatty) {
12117                if (r == null) {
12118                    r = new StringBuilder(256);
12119                } else {
12120                    r.append(' ');
12121                }
12122                r.append(p.info.name);
12123            }
12124        }
12125        if (r != null) {
12126            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12127        }
12128
12129        N = pkg.services.size();
12130        r = null;
12131        for (i=0; i<N; i++) {
12132            PackageParser.Service s = pkg.services.get(i);
12133            mServices.removeService(s);
12134            if (chatty) {
12135                if (r == null) {
12136                    r = new StringBuilder(256);
12137                } else {
12138                    r.append(' ');
12139                }
12140                r.append(s.info.name);
12141            }
12142        }
12143        if (r != null) {
12144            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12145        }
12146
12147        N = pkg.receivers.size();
12148        r = null;
12149        for (i=0; i<N; i++) {
12150            PackageParser.Activity a = pkg.receivers.get(i);
12151            mReceivers.removeActivity(a, "receiver");
12152            if (DEBUG_REMOVE && chatty) {
12153                if (r == null) {
12154                    r = new StringBuilder(256);
12155                } else {
12156                    r.append(' ');
12157                }
12158                r.append(a.info.name);
12159            }
12160        }
12161        if (r != null) {
12162            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12163        }
12164
12165        N = pkg.activities.size();
12166        r = null;
12167        for (i=0; i<N; i++) {
12168            PackageParser.Activity a = pkg.activities.get(i);
12169            mActivities.removeActivity(a, "activity");
12170            if (DEBUG_REMOVE && chatty) {
12171                if (r == null) {
12172                    r = new StringBuilder(256);
12173                } else {
12174                    r.append(' ');
12175                }
12176                r.append(a.info.name);
12177            }
12178        }
12179        if (r != null) {
12180            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12181        }
12182
12183        mPermissionManager.removeAllPermissions(pkg, chatty);
12184
12185        N = pkg.instrumentation.size();
12186        r = null;
12187        for (i=0; i<N; i++) {
12188            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12189            mInstrumentation.remove(a.getComponentName());
12190            if (DEBUG_REMOVE && chatty) {
12191                if (r == null) {
12192                    r = new StringBuilder(256);
12193                } else {
12194                    r.append(' ');
12195                }
12196                r.append(a.info.name);
12197            }
12198        }
12199        if (r != null) {
12200            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12201        }
12202
12203        r = null;
12204        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12205            // Only system apps can hold shared libraries.
12206            if (pkg.libraryNames != null) {
12207                for (i = 0; i < pkg.libraryNames.size(); i++) {
12208                    String name = pkg.libraryNames.get(i);
12209                    if (removeSharedLibraryLPw(name, 0)) {
12210                        if (DEBUG_REMOVE && chatty) {
12211                            if (r == null) {
12212                                r = new StringBuilder(256);
12213                            } else {
12214                                r.append(' ');
12215                            }
12216                            r.append(name);
12217                        }
12218                    }
12219                }
12220            }
12221        }
12222
12223        r = null;
12224
12225        // Any package can hold static shared libraries.
12226        if (pkg.staticSharedLibName != null) {
12227            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12228                if (DEBUG_REMOVE && chatty) {
12229                    if (r == null) {
12230                        r = new StringBuilder(256);
12231                    } else {
12232                        r.append(' ');
12233                    }
12234                    r.append(pkg.staticSharedLibName);
12235                }
12236            }
12237        }
12238
12239        if (r != null) {
12240            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12241        }
12242    }
12243
12244
12245    final class ActivityIntentResolver
12246            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12247        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12248                boolean defaultOnly, int userId) {
12249            if (!sUserManager.exists(userId)) return null;
12250            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12251            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12252        }
12253
12254        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12255                int userId) {
12256            if (!sUserManager.exists(userId)) return null;
12257            mFlags = flags;
12258            return super.queryIntent(intent, resolvedType,
12259                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12260                    userId);
12261        }
12262
12263        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12264                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12265            if (!sUserManager.exists(userId)) return null;
12266            if (packageActivities == null) {
12267                return null;
12268            }
12269            mFlags = flags;
12270            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12271            final int N = packageActivities.size();
12272            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12273                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12274
12275            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12276            for (int i = 0; i < N; ++i) {
12277                intentFilters = packageActivities.get(i).intents;
12278                if (intentFilters != null && intentFilters.size() > 0) {
12279                    PackageParser.ActivityIntentInfo[] array =
12280                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12281                    intentFilters.toArray(array);
12282                    listCut.add(array);
12283                }
12284            }
12285            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12286        }
12287
12288        /**
12289         * Finds a privileged activity that matches the specified activity names.
12290         */
12291        private PackageParser.Activity findMatchingActivity(
12292                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12293            for (PackageParser.Activity sysActivity : activityList) {
12294                if (sysActivity.info.name.equals(activityInfo.name)) {
12295                    return sysActivity;
12296                }
12297                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12298                    return sysActivity;
12299                }
12300                if (sysActivity.info.targetActivity != null) {
12301                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12302                        return sysActivity;
12303                    }
12304                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12305                        return sysActivity;
12306                    }
12307                }
12308            }
12309            return null;
12310        }
12311
12312        public class IterGenerator<E> {
12313            public Iterator<E> generate(ActivityIntentInfo info) {
12314                return null;
12315            }
12316        }
12317
12318        public class ActionIterGenerator extends IterGenerator<String> {
12319            @Override
12320            public Iterator<String> generate(ActivityIntentInfo info) {
12321                return info.actionsIterator();
12322            }
12323        }
12324
12325        public class CategoriesIterGenerator extends IterGenerator<String> {
12326            @Override
12327            public Iterator<String> generate(ActivityIntentInfo info) {
12328                return info.categoriesIterator();
12329            }
12330        }
12331
12332        public class SchemesIterGenerator extends IterGenerator<String> {
12333            @Override
12334            public Iterator<String> generate(ActivityIntentInfo info) {
12335                return info.schemesIterator();
12336            }
12337        }
12338
12339        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12340            @Override
12341            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12342                return info.authoritiesIterator();
12343            }
12344        }
12345
12346        /**
12347         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12348         * MODIFIED. Do not pass in a list that should not be changed.
12349         */
12350        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12351                IterGenerator<T> generator, Iterator<T> searchIterator) {
12352            // loop through the set of actions; every one must be found in the intent filter
12353            while (searchIterator.hasNext()) {
12354                // we must have at least one filter in the list to consider a match
12355                if (intentList.size() == 0) {
12356                    break;
12357                }
12358
12359                final T searchAction = searchIterator.next();
12360
12361                // loop through the set of intent filters
12362                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12363                while (intentIter.hasNext()) {
12364                    final ActivityIntentInfo intentInfo = intentIter.next();
12365                    boolean selectionFound = false;
12366
12367                    // loop through the intent filter's selection criteria; at least one
12368                    // of them must match the searched criteria
12369                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12370                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12371                        final T intentSelection = intentSelectionIter.next();
12372                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12373                            selectionFound = true;
12374                            break;
12375                        }
12376                    }
12377
12378                    // the selection criteria wasn't found in this filter's set; this filter
12379                    // is not a potential match
12380                    if (!selectionFound) {
12381                        intentIter.remove();
12382                    }
12383                }
12384            }
12385        }
12386
12387        private boolean isProtectedAction(ActivityIntentInfo filter) {
12388            final Iterator<String> actionsIter = filter.actionsIterator();
12389            while (actionsIter != null && actionsIter.hasNext()) {
12390                final String filterAction = actionsIter.next();
12391                if (PROTECTED_ACTIONS.contains(filterAction)) {
12392                    return true;
12393                }
12394            }
12395            return false;
12396        }
12397
12398        /**
12399         * Adjusts the priority of the given intent filter according to policy.
12400         * <p>
12401         * <ul>
12402         * <li>The priority for non privileged applications is capped to '0'</li>
12403         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12404         * <li>The priority for unbundled updates to privileged applications is capped to the
12405         *      priority defined on the system partition</li>
12406         * </ul>
12407         * <p>
12408         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12409         * allowed to obtain any priority on any action.
12410         */
12411        private void adjustPriority(
12412                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12413            // nothing to do; priority is fine as-is
12414            if (intent.getPriority() <= 0) {
12415                return;
12416            }
12417
12418            final ActivityInfo activityInfo = intent.activity.info;
12419            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12420
12421            final boolean privilegedApp =
12422                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12423            if (!privilegedApp) {
12424                // non-privileged applications can never define a priority >0
12425                if (DEBUG_FILTERS) {
12426                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12427                            + " package: " + applicationInfo.packageName
12428                            + " activity: " + intent.activity.className
12429                            + " origPrio: " + intent.getPriority());
12430                }
12431                intent.setPriority(0);
12432                return;
12433            }
12434
12435            if (systemActivities == null) {
12436                // the system package is not disabled; we're parsing the system partition
12437                if (isProtectedAction(intent)) {
12438                    if (mDeferProtectedFilters) {
12439                        // We can't deal with these just yet. No component should ever obtain a
12440                        // >0 priority for a protected actions, with ONE exception -- the setup
12441                        // wizard. The setup wizard, however, cannot be known until we're able to
12442                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12443                        // until all intent filters have been processed. Chicken, meet egg.
12444                        // Let the filter temporarily have a high priority and rectify the
12445                        // priorities after all system packages have been scanned.
12446                        mProtectedFilters.add(intent);
12447                        if (DEBUG_FILTERS) {
12448                            Slog.i(TAG, "Protected action; save for later;"
12449                                    + " package: " + applicationInfo.packageName
12450                                    + " activity: " + intent.activity.className
12451                                    + " origPrio: " + intent.getPriority());
12452                        }
12453                        return;
12454                    } else {
12455                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12456                            Slog.i(TAG, "No setup wizard;"
12457                                + " All protected intents capped to priority 0");
12458                        }
12459                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12460                            if (DEBUG_FILTERS) {
12461                                Slog.i(TAG, "Found setup wizard;"
12462                                    + " allow priority " + intent.getPriority() + ";"
12463                                    + " package: " + intent.activity.info.packageName
12464                                    + " activity: " + intent.activity.className
12465                                    + " priority: " + intent.getPriority());
12466                            }
12467                            // setup wizard gets whatever it wants
12468                            return;
12469                        }
12470                        if (DEBUG_FILTERS) {
12471                            Slog.i(TAG, "Protected action; cap priority to 0;"
12472                                    + " package: " + intent.activity.info.packageName
12473                                    + " activity: " + intent.activity.className
12474                                    + " origPrio: " + intent.getPriority());
12475                        }
12476                        intent.setPriority(0);
12477                        return;
12478                    }
12479                }
12480                // privileged apps on the system image get whatever priority they request
12481                return;
12482            }
12483
12484            // privileged app unbundled update ... try to find the same activity
12485            final PackageParser.Activity foundActivity =
12486                    findMatchingActivity(systemActivities, activityInfo);
12487            if (foundActivity == null) {
12488                // this is a new activity; it cannot obtain >0 priority
12489                if (DEBUG_FILTERS) {
12490                    Slog.i(TAG, "New activity; cap priority to 0;"
12491                            + " package: " + applicationInfo.packageName
12492                            + " activity: " + intent.activity.className
12493                            + " origPrio: " + intent.getPriority());
12494                }
12495                intent.setPriority(0);
12496                return;
12497            }
12498
12499            // found activity, now check for filter equivalence
12500
12501            // a shallow copy is enough; we modify the list, not its contents
12502            final List<ActivityIntentInfo> intentListCopy =
12503                    new ArrayList<>(foundActivity.intents);
12504            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12505
12506            // find matching action subsets
12507            final Iterator<String> actionsIterator = intent.actionsIterator();
12508            if (actionsIterator != null) {
12509                getIntentListSubset(
12510                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12511                if (intentListCopy.size() == 0) {
12512                    // no more intents to match; we're not equivalent
12513                    if (DEBUG_FILTERS) {
12514                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12515                                + " package: " + applicationInfo.packageName
12516                                + " activity: " + intent.activity.className
12517                                + " origPrio: " + intent.getPriority());
12518                    }
12519                    intent.setPriority(0);
12520                    return;
12521                }
12522            }
12523
12524            // find matching category subsets
12525            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12526            if (categoriesIterator != null) {
12527                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12528                        categoriesIterator);
12529                if (intentListCopy.size() == 0) {
12530                    // no more intents to match; we're not equivalent
12531                    if (DEBUG_FILTERS) {
12532                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12533                                + " package: " + applicationInfo.packageName
12534                                + " activity: " + intent.activity.className
12535                                + " origPrio: " + intent.getPriority());
12536                    }
12537                    intent.setPriority(0);
12538                    return;
12539                }
12540            }
12541
12542            // find matching schemes subsets
12543            final Iterator<String> schemesIterator = intent.schemesIterator();
12544            if (schemesIterator != null) {
12545                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12546                        schemesIterator);
12547                if (intentListCopy.size() == 0) {
12548                    // no more intents to match; we're not equivalent
12549                    if (DEBUG_FILTERS) {
12550                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12551                                + " package: " + applicationInfo.packageName
12552                                + " activity: " + intent.activity.className
12553                                + " origPrio: " + intent.getPriority());
12554                    }
12555                    intent.setPriority(0);
12556                    return;
12557                }
12558            }
12559
12560            // find matching authorities subsets
12561            final Iterator<IntentFilter.AuthorityEntry>
12562                    authoritiesIterator = intent.authoritiesIterator();
12563            if (authoritiesIterator != null) {
12564                getIntentListSubset(intentListCopy,
12565                        new AuthoritiesIterGenerator(),
12566                        authoritiesIterator);
12567                if (intentListCopy.size() == 0) {
12568                    // no more intents to match; we're not equivalent
12569                    if (DEBUG_FILTERS) {
12570                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12571                                + " package: " + applicationInfo.packageName
12572                                + " activity: " + intent.activity.className
12573                                + " origPrio: " + intent.getPriority());
12574                    }
12575                    intent.setPriority(0);
12576                    return;
12577                }
12578            }
12579
12580            // we found matching filter(s); app gets the max priority of all intents
12581            int cappedPriority = 0;
12582            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12583                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12584            }
12585            if (intent.getPriority() > cappedPriority) {
12586                if (DEBUG_FILTERS) {
12587                    Slog.i(TAG, "Found matching filter(s);"
12588                            + " cap priority to " + cappedPriority + ";"
12589                            + " package: " + applicationInfo.packageName
12590                            + " activity: " + intent.activity.className
12591                            + " origPrio: " + intent.getPriority());
12592                }
12593                intent.setPriority(cappedPriority);
12594                return;
12595            }
12596            // all this for nothing; the requested priority was <= what was on the system
12597        }
12598
12599        public final void addActivity(PackageParser.Activity a, String type) {
12600            mActivities.put(a.getComponentName(), a);
12601            if (DEBUG_SHOW_INFO)
12602                Log.v(
12603                TAG, "  " + type + " " +
12604                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12605            if (DEBUG_SHOW_INFO)
12606                Log.v(TAG, "    Class=" + a.info.name);
12607            final int NI = a.intents.size();
12608            for (int j=0; j<NI; j++) {
12609                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12610                if ("activity".equals(type)) {
12611                    final PackageSetting ps =
12612                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12613                    final List<PackageParser.Activity> systemActivities =
12614                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12615                    adjustPriority(systemActivities, intent);
12616                }
12617                if (DEBUG_SHOW_INFO) {
12618                    Log.v(TAG, "    IntentFilter:");
12619                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12620                }
12621                if (!intent.debugCheck()) {
12622                    Log.w(TAG, "==> For Activity " + a.info.name);
12623                }
12624                addFilter(intent);
12625            }
12626        }
12627
12628        public final void removeActivity(PackageParser.Activity a, String type) {
12629            mActivities.remove(a.getComponentName());
12630            if (DEBUG_SHOW_INFO) {
12631                Log.v(TAG, "  " + type + " "
12632                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12633                                : a.info.name) + ":");
12634                Log.v(TAG, "    Class=" + a.info.name);
12635            }
12636            final int NI = a.intents.size();
12637            for (int j=0; j<NI; j++) {
12638                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12639                if (DEBUG_SHOW_INFO) {
12640                    Log.v(TAG, "    IntentFilter:");
12641                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12642                }
12643                removeFilter(intent);
12644            }
12645        }
12646
12647        @Override
12648        protected boolean allowFilterResult(
12649                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12650            ActivityInfo filterAi = filter.activity.info;
12651            for (int i=dest.size()-1; i>=0; i--) {
12652                ActivityInfo destAi = dest.get(i).activityInfo;
12653                if (destAi.name == filterAi.name
12654                        && destAi.packageName == filterAi.packageName) {
12655                    return false;
12656                }
12657            }
12658            return true;
12659        }
12660
12661        @Override
12662        protected ActivityIntentInfo[] newArray(int size) {
12663            return new ActivityIntentInfo[size];
12664        }
12665
12666        @Override
12667        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12668            if (!sUserManager.exists(userId)) return true;
12669            PackageParser.Package p = filter.activity.owner;
12670            if (p != null) {
12671                PackageSetting ps = (PackageSetting)p.mExtras;
12672                if (ps != null) {
12673                    // System apps are never considered stopped for purposes of
12674                    // filtering, because there may be no way for the user to
12675                    // actually re-launch them.
12676                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12677                            && ps.getStopped(userId);
12678                }
12679            }
12680            return false;
12681        }
12682
12683        @Override
12684        protected boolean isPackageForFilter(String packageName,
12685                PackageParser.ActivityIntentInfo info) {
12686            return packageName.equals(info.activity.owner.packageName);
12687        }
12688
12689        @Override
12690        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12691                int match, int userId) {
12692            if (!sUserManager.exists(userId)) return null;
12693            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12694                return null;
12695            }
12696            final PackageParser.Activity activity = info.activity;
12697            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12698            if (ps == null) {
12699                return null;
12700            }
12701            final PackageUserState userState = ps.readUserState(userId);
12702            ActivityInfo ai =
12703                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12704            if (ai == null) {
12705                return null;
12706            }
12707            final boolean matchExplicitlyVisibleOnly =
12708                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12709            final boolean matchVisibleToInstantApp =
12710                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12711            final boolean componentVisible =
12712                    matchVisibleToInstantApp
12713                    && info.isVisibleToInstantApp()
12714                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12715            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12716            // throw out filters that aren't visible to ephemeral apps
12717            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12718                return null;
12719            }
12720            // throw out instant app filters if we're not explicitly requesting them
12721            if (!matchInstantApp && userState.instantApp) {
12722                return null;
12723            }
12724            // throw out instant app filters if updates are available; will trigger
12725            // instant app resolution
12726            if (userState.instantApp && ps.isUpdateAvailable()) {
12727                return null;
12728            }
12729            final ResolveInfo res = new ResolveInfo();
12730            res.activityInfo = ai;
12731            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12732                res.filter = info;
12733            }
12734            if (info != null) {
12735                res.handleAllWebDataURI = info.handleAllWebDataURI();
12736            }
12737            res.priority = info.getPriority();
12738            res.preferredOrder = activity.owner.mPreferredOrder;
12739            //System.out.println("Result: " + res.activityInfo.className +
12740            //                   " = " + res.priority);
12741            res.match = match;
12742            res.isDefault = info.hasDefault;
12743            res.labelRes = info.labelRes;
12744            res.nonLocalizedLabel = info.nonLocalizedLabel;
12745            if (userNeedsBadging(userId)) {
12746                res.noResourceId = true;
12747            } else {
12748                res.icon = info.icon;
12749            }
12750            res.iconResourceId = info.icon;
12751            res.system = res.activityInfo.applicationInfo.isSystemApp();
12752            res.isInstantAppAvailable = userState.instantApp;
12753            return res;
12754        }
12755
12756        @Override
12757        protected void sortResults(List<ResolveInfo> results) {
12758            Collections.sort(results, mResolvePrioritySorter);
12759        }
12760
12761        @Override
12762        protected void dumpFilter(PrintWriter out, String prefix,
12763                PackageParser.ActivityIntentInfo filter) {
12764            out.print(prefix); out.print(
12765                    Integer.toHexString(System.identityHashCode(filter.activity)));
12766                    out.print(' ');
12767                    filter.activity.printComponentShortName(out);
12768                    out.print(" filter ");
12769                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12770        }
12771
12772        @Override
12773        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12774            return filter.activity;
12775        }
12776
12777        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12778            PackageParser.Activity activity = (PackageParser.Activity)label;
12779            out.print(prefix); out.print(
12780                    Integer.toHexString(System.identityHashCode(activity)));
12781                    out.print(' ');
12782                    activity.printComponentShortName(out);
12783            if (count > 1) {
12784                out.print(" ("); out.print(count); out.print(" filters)");
12785            }
12786            out.println();
12787        }
12788
12789        // Keys are String (activity class name), values are Activity.
12790        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12791                = new ArrayMap<ComponentName, PackageParser.Activity>();
12792        private int mFlags;
12793    }
12794
12795    private final class ServiceIntentResolver
12796            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12797        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12798                boolean defaultOnly, int userId) {
12799            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12800            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12801        }
12802
12803        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12804                int userId) {
12805            if (!sUserManager.exists(userId)) return null;
12806            mFlags = flags;
12807            return super.queryIntent(intent, resolvedType,
12808                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12809                    userId);
12810        }
12811
12812        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12813                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12814            if (!sUserManager.exists(userId)) return null;
12815            if (packageServices == null) {
12816                return null;
12817            }
12818            mFlags = flags;
12819            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12820            final int N = packageServices.size();
12821            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12822                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12823
12824            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12825            for (int i = 0; i < N; ++i) {
12826                intentFilters = packageServices.get(i).intents;
12827                if (intentFilters != null && intentFilters.size() > 0) {
12828                    PackageParser.ServiceIntentInfo[] array =
12829                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12830                    intentFilters.toArray(array);
12831                    listCut.add(array);
12832                }
12833            }
12834            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12835        }
12836
12837        public final void addService(PackageParser.Service s) {
12838            mServices.put(s.getComponentName(), s);
12839            if (DEBUG_SHOW_INFO) {
12840                Log.v(TAG, "  "
12841                        + (s.info.nonLocalizedLabel != null
12842                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12843                Log.v(TAG, "    Class=" + s.info.name);
12844            }
12845            final int NI = s.intents.size();
12846            int j;
12847            for (j=0; j<NI; j++) {
12848                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12849                if (DEBUG_SHOW_INFO) {
12850                    Log.v(TAG, "    IntentFilter:");
12851                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12852                }
12853                if (!intent.debugCheck()) {
12854                    Log.w(TAG, "==> For Service " + s.info.name);
12855                }
12856                addFilter(intent);
12857            }
12858        }
12859
12860        public final void removeService(PackageParser.Service s) {
12861            mServices.remove(s.getComponentName());
12862            if (DEBUG_SHOW_INFO) {
12863                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12864                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12865                Log.v(TAG, "    Class=" + s.info.name);
12866            }
12867            final int NI = s.intents.size();
12868            int j;
12869            for (j=0; j<NI; j++) {
12870                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12871                if (DEBUG_SHOW_INFO) {
12872                    Log.v(TAG, "    IntentFilter:");
12873                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12874                }
12875                removeFilter(intent);
12876            }
12877        }
12878
12879        @Override
12880        protected boolean allowFilterResult(
12881                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12882            ServiceInfo filterSi = filter.service.info;
12883            for (int i=dest.size()-1; i>=0; i--) {
12884                ServiceInfo destAi = dest.get(i).serviceInfo;
12885                if (destAi.name == filterSi.name
12886                        && destAi.packageName == filterSi.packageName) {
12887                    return false;
12888                }
12889            }
12890            return true;
12891        }
12892
12893        @Override
12894        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12895            return new PackageParser.ServiceIntentInfo[size];
12896        }
12897
12898        @Override
12899        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12900            if (!sUserManager.exists(userId)) return true;
12901            PackageParser.Package p = filter.service.owner;
12902            if (p != null) {
12903                PackageSetting ps = (PackageSetting)p.mExtras;
12904                if (ps != null) {
12905                    // System apps are never considered stopped for purposes of
12906                    // filtering, because there may be no way for the user to
12907                    // actually re-launch them.
12908                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12909                            && ps.getStopped(userId);
12910                }
12911            }
12912            return false;
12913        }
12914
12915        @Override
12916        protected boolean isPackageForFilter(String packageName,
12917                PackageParser.ServiceIntentInfo info) {
12918            return packageName.equals(info.service.owner.packageName);
12919        }
12920
12921        @Override
12922        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12923                int match, int userId) {
12924            if (!sUserManager.exists(userId)) return null;
12925            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12926            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12927                return null;
12928            }
12929            final PackageParser.Service service = info.service;
12930            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12931            if (ps == null) {
12932                return null;
12933            }
12934            final PackageUserState userState = ps.readUserState(userId);
12935            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12936                    userState, userId);
12937            if (si == null) {
12938                return null;
12939            }
12940            final boolean matchVisibleToInstantApp =
12941                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12942            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12943            // throw out filters that aren't visible to ephemeral apps
12944            if (matchVisibleToInstantApp
12945                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12946                return null;
12947            }
12948            // throw out ephemeral filters if we're not explicitly requesting them
12949            if (!isInstantApp && userState.instantApp) {
12950                return null;
12951            }
12952            // throw out instant app filters if updates are available; will trigger
12953            // instant app resolution
12954            if (userState.instantApp && ps.isUpdateAvailable()) {
12955                return null;
12956            }
12957            final ResolveInfo res = new ResolveInfo();
12958            res.serviceInfo = si;
12959            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12960                res.filter = filter;
12961            }
12962            res.priority = info.getPriority();
12963            res.preferredOrder = service.owner.mPreferredOrder;
12964            res.match = match;
12965            res.isDefault = info.hasDefault;
12966            res.labelRes = info.labelRes;
12967            res.nonLocalizedLabel = info.nonLocalizedLabel;
12968            res.icon = info.icon;
12969            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12970            return res;
12971        }
12972
12973        @Override
12974        protected void sortResults(List<ResolveInfo> results) {
12975            Collections.sort(results, mResolvePrioritySorter);
12976        }
12977
12978        @Override
12979        protected void dumpFilter(PrintWriter out, String prefix,
12980                PackageParser.ServiceIntentInfo filter) {
12981            out.print(prefix); out.print(
12982                    Integer.toHexString(System.identityHashCode(filter.service)));
12983                    out.print(' ');
12984                    filter.service.printComponentShortName(out);
12985                    out.print(" filter ");
12986                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12987                    if (filter.service.info.permission != null) {
12988                        out.print(" permission "); out.println(filter.service.info.permission);
12989                    } else {
12990                        out.println();
12991                    }
12992        }
12993
12994        @Override
12995        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12996            return filter.service;
12997        }
12998
12999        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13000            PackageParser.Service service = (PackageParser.Service)label;
13001            out.print(prefix); out.print(
13002                    Integer.toHexString(System.identityHashCode(service)));
13003                    out.print(' ');
13004                    service.printComponentShortName(out);
13005            if (count > 1) {
13006                out.print(" ("); out.print(count); out.print(" filters)");
13007            }
13008            out.println();
13009        }
13010
13011//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13012//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13013//            final List<ResolveInfo> retList = Lists.newArrayList();
13014//            while (i.hasNext()) {
13015//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13016//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13017//                    retList.add(resolveInfo);
13018//                }
13019//            }
13020//            return retList;
13021//        }
13022
13023        // Keys are String (activity class name), values are Activity.
13024        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13025                = new ArrayMap<ComponentName, PackageParser.Service>();
13026        private int mFlags;
13027    }
13028
13029    private final class ProviderIntentResolver
13030            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13031        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13032                boolean defaultOnly, int userId) {
13033            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13034            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13035        }
13036
13037        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13038                int userId) {
13039            if (!sUserManager.exists(userId))
13040                return null;
13041            mFlags = flags;
13042            return super.queryIntent(intent, resolvedType,
13043                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13044                    userId);
13045        }
13046
13047        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13048                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13049            if (!sUserManager.exists(userId))
13050                return null;
13051            if (packageProviders == null) {
13052                return null;
13053            }
13054            mFlags = flags;
13055            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13056            final int N = packageProviders.size();
13057            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13058                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13059
13060            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13061            for (int i = 0; i < N; ++i) {
13062                intentFilters = packageProviders.get(i).intents;
13063                if (intentFilters != null && intentFilters.size() > 0) {
13064                    PackageParser.ProviderIntentInfo[] array =
13065                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13066                    intentFilters.toArray(array);
13067                    listCut.add(array);
13068                }
13069            }
13070            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13071        }
13072
13073        public final void addProvider(PackageParser.Provider p) {
13074            if (mProviders.containsKey(p.getComponentName())) {
13075                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13076                return;
13077            }
13078
13079            mProviders.put(p.getComponentName(), p);
13080            if (DEBUG_SHOW_INFO) {
13081                Log.v(TAG, "  "
13082                        + (p.info.nonLocalizedLabel != null
13083                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13084                Log.v(TAG, "    Class=" + p.info.name);
13085            }
13086            final int NI = p.intents.size();
13087            int j;
13088            for (j = 0; j < NI; j++) {
13089                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13090                if (DEBUG_SHOW_INFO) {
13091                    Log.v(TAG, "    IntentFilter:");
13092                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13093                }
13094                if (!intent.debugCheck()) {
13095                    Log.w(TAG, "==> For Provider " + p.info.name);
13096                }
13097                addFilter(intent);
13098            }
13099        }
13100
13101        public final void removeProvider(PackageParser.Provider p) {
13102            mProviders.remove(p.getComponentName());
13103            if (DEBUG_SHOW_INFO) {
13104                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13105                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13106                Log.v(TAG, "    Class=" + p.info.name);
13107            }
13108            final int NI = p.intents.size();
13109            int j;
13110            for (j = 0; j < NI; j++) {
13111                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13112                if (DEBUG_SHOW_INFO) {
13113                    Log.v(TAG, "    IntentFilter:");
13114                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13115                }
13116                removeFilter(intent);
13117            }
13118        }
13119
13120        @Override
13121        protected boolean allowFilterResult(
13122                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13123            ProviderInfo filterPi = filter.provider.info;
13124            for (int i = dest.size() - 1; i >= 0; i--) {
13125                ProviderInfo destPi = dest.get(i).providerInfo;
13126                if (destPi.name == filterPi.name
13127                        && destPi.packageName == filterPi.packageName) {
13128                    return false;
13129                }
13130            }
13131            return true;
13132        }
13133
13134        @Override
13135        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13136            return new PackageParser.ProviderIntentInfo[size];
13137        }
13138
13139        @Override
13140        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13141            if (!sUserManager.exists(userId))
13142                return true;
13143            PackageParser.Package p = filter.provider.owner;
13144            if (p != null) {
13145                PackageSetting ps = (PackageSetting) p.mExtras;
13146                if (ps != null) {
13147                    // System apps are never considered stopped for purposes of
13148                    // filtering, because there may be no way for the user to
13149                    // actually re-launch them.
13150                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13151                            && ps.getStopped(userId);
13152                }
13153            }
13154            return false;
13155        }
13156
13157        @Override
13158        protected boolean isPackageForFilter(String packageName,
13159                PackageParser.ProviderIntentInfo info) {
13160            return packageName.equals(info.provider.owner.packageName);
13161        }
13162
13163        @Override
13164        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13165                int match, int userId) {
13166            if (!sUserManager.exists(userId))
13167                return null;
13168            final PackageParser.ProviderIntentInfo info = filter;
13169            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13170                return null;
13171            }
13172            final PackageParser.Provider provider = info.provider;
13173            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13174            if (ps == null) {
13175                return null;
13176            }
13177            final PackageUserState userState = ps.readUserState(userId);
13178            final boolean matchVisibleToInstantApp =
13179                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13180            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13181            // throw out filters that aren't visible to instant applications
13182            if (matchVisibleToInstantApp
13183                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13184                return null;
13185            }
13186            // throw out instant application filters if we're not explicitly requesting them
13187            if (!isInstantApp && userState.instantApp) {
13188                return null;
13189            }
13190            // throw out instant application filters if updates are available; will trigger
13191            // instant application resolution
13192            if (userState.instantApp && ps.isUpdateAvailable()) {
13193                return null;
13194            }
13195            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13196                    userState, userId);
13197            if (pi == null) {
13198                return null;
13199            }
13200            final ResolveInfo res = new ResolveInfo();
13201            res.providerInfo = pi;
13202            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13203                res.filter = filter;
13204            }
13205            res.priority = info.getPriority();
13206            res.preferredOrder = provider.owner.mPreferredOrder;
13207            res.match = match;
13208            res.isDefault = info.hasDefault;
13209            res.labelRes = info.labelRes;
13210            res.nonLocalizedLabel = info.nonLocalizedLabel;
13211            res.icon = info.icon;
13212            res.system = res.providerInfo.applicationInfo.isSystemApp();
13213            return res;
13214        }
13215
13216        @Override
13217        protected void sortResults(List<ResolveInfo> results) {
13218            Collections.sort(results, mResolvePrioritySorter);
13219        }
13220
13221        @Override
13222        protected void dumpFilter(PrintWriter out, String prefix,
13223                PackageParser.ProviderIntentInfo filter) {
13224            out.print(prefix);
13225            out.print(
13226                    Integer.toHexString(System.identityHashCode(filter.provider)));
13227            out.print(' ');
13228            filter.provider.printComponentShortName(out);
13229            out.print(" filter ");
13230            out.println(Integer.toHexString(System.identityHashCode(filter)));
13231        }
13232
13233        @Override
13234        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13235            return filter.provider;
13236        }
13237
13238        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13239            PackageParser.Provider provider = (PackageParser.Provider)label;
13240            out.print(prefix); out.print(
13241                    Integer.toHexString(System.identityHashCode(provider)));
13242                    out.print(' ');
13243                    provider.printComponentShortName(out);
13244            if (count > 1) {
13245                out.print(" ("); out.print(count); out.print(" filters)");
13246            }
13247            out.println();
13248        }
13249
13250        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13251                = new ArrayMap<ComponentName, PackageParser.Provider>();
13252        private int mFlags;
13253    }
13254
13255    static final class InstantAppIntentResolver
13256            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13257            AuxiliaryResolveInfo.AuxiliaryFilter> {
13258        /**
13259         * The result that has the highest defined order. Ordering applies on a
13260         * per-package basis. Mapping is from package name to Pair of order and
13261         * EphemeralResolveInfo.
13262         * <p>
13263         * NOTE: This is implemented as a field variable for convenience and efficiency.
13264         * By having a field variable, we're able to track filter ordering as soon as
13265         * a non-zero order is defined. Otherwise, multiple loops across the result set
13266         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13267         * this needs to be contained entirely within {@link #filterResults}.
13268         */
13269        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13270
13271        @Override
13272        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13273            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13274        }
13275
13276        @Override
13277        protected boolean isPackageForFilter(String packageName,
13278                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13279            return true;
13280        }
13281
13282        @Override
13283        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13284                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13285            if (!sUserManager.exists(userId)) {
13286                return null;
13287            }
13288            final String packageName = responseObj.resolveInfo.getPackageName();
13289            final Integer order = responseObj.getOrder();
13290            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13291                    mOrderResult.get(packageName);
13292            // ordering is enabled and this item's order isn't high enough
13293            if (lastOrderResult != null && lastOrderResult.first >= order) {
13294                return null;
13295            }
13296            final InstantAppResolveInfo res = responseObj.resolveInfo;
13297            if (order > 0) {
13298                // non-zero order, enable ordering
13299                mOrderResult.put(packageName, new Pair<>(order, res));
13300            }
13301            return responseObj;
13302        }
13303
13304        @Override
13305        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13306            // only do work if ordering is enabled [most of the time it won't be]
13307            if (mOrderResult.size() == 0) {
13308                return;
13309            }
13310            int resultSize = results.size();
13311            for (int i = 0; i < resultSize; i++) {
13312                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13313                final String packageName = info.getPackageName();
13314                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13315                if (savedInfo == null) {
13316                    // package doesn't having ordering
13317                    continue;
13318                }
13319                if (savedInfo.second == info) {
13320                    // circled back to the highest ordered item; remove from order list
13321                    mOrderResult.remove(packageName);
13322                    if (mOrderResult.size() == 0) {
13323                        // no more ordered items
13324                        break;
13325                    }
13326                    continue;
13327                }
13328                // item has a worse order, remove it from the result list
13329                results.remove(i);
13330                resultSize--;
13331                i--;
13332            }
13333        }
13334    }
13335
13336    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13337            new Comparator<ResolveInfo>() {
13338        public int compare(ResolveInfo r1, ResolveInfo r2) {
13339            int v1 = r1.priority;
13340            int v2 = r2.priority;
13341            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13342            if (v1 != v2) {
13343                return (v1 > v2) ? -1 : 1;
13344            }
13345            v1 = r1.preferredOrder;
13346            v2 = r2.preferredOrder;
13347            if (v1 != v2) {
13348                return (v1 > v2) ? -1 : 1;
13349            }
13350            if (r1.isDefault != r2.isDefault) {
13351                return r1.isDefault ? -1 : 1;
13352            }
13353            v1 = r1.match;
13354            v2 = r2.match;
13355            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13356            if (v1 != v2) {
13357                return (v1 > v2) ? -1 : 1;
13358            }
13359            if (r1.system != r2.system) {
13360                return r1.system ? -1 : 1;
13361            }
13362            if (r1.activityInfo != null) {
13363                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13364            }
13365            if (r1.serviceInfo != null) {
13366                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13367            }
13368            if (r1.providerInfo != null) {
13369                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13370            }
13371            return 0;
13372        }
13373    };
13374
13375    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13376            new Comparator<ProviderInfo>() {
13377        public int compare(ProviderInfo p1, ProviderInfo p2) {
13378            final int v1 = p1.initOrder;
13379            final int v2 = p2.initOrder;
13380            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13381        }
13382    };
13383
13384    @Override
13385    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13386            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13387            final int[] userIds, int[] instantUserIds) {
13388        mHandler.post(new Runnable() {
13389            @Override
13390            public void run() {
13391                try {
13392                    final IActivityManager am = ActivityManager.getService();
13393                    if (am == null) return;
13394                    final int[] resolvedUserIds;
13395                    if (userIds == null) {
13396                        resolvedUserIds = am.getRunningUserIds();
13397                    } else {
13398                        resolvedUserIds = userIds;
13399                    }
13400                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13401                            resolvedUserIds, false);
13402                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13403                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13404                                instantUserIds, true);
13405                    }
13406                } catch (RemoteException ex) {
13407                }
13408            }
13409        });
13410    }
13411
13412    @Override
13413    public void notifyPackageAdded(String packageName) {
13414        final PackageListObserver[] observers;
13415        synchronized (mPackages) {
13416            if (mPackageListObservers.size() == 0) {
13417                return;
13418            }
13419            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13420        }
13421        for (int i = observers.length - 1; i >= 0; --i) {
13422            observers[i].onPackageAdded(packageName);
13423        }
13424    }
13425
13426    @Override
13427    public void notifyPackageRemoved(String packageName) {
13428        final PackageListObserver[] observers;
13429        synchronized (mPackages) {
13430            if (mPackageListObservers.size() == 0) {
13431                return;
13432            }
13433            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13434        }
13435        for (int i = observers.length - 1; i >= 0; --i) {
13436            observers[i].onPackageRemoved(packageName);
13437        }
13438    }
13439
13440    /**
13441     * Sends a broadcast for the given action.
13442     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13443     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13444     * the system and applications allowed to see instant applications to receive package
13445     * lifecycle events for instant applications.
13446     */
13447    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13448            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13449            int[] userIds, boolean isInstantApp)
13450                    throws RemoteException {
13451        for (int id : userIds) {
13452            final Intent intent = new Intent(action,
13453                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13454            final String[] requiredPermissions =
13455                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13456            if (extras != null) {
13457                intent.putExtras(extras);
13458            }
13459            if (targetPkg != null) {
13460                intent.setPackage(targetPkg);
13461            }
13462            // Modify the UID when posting to other users
13463            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13464            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13465                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13466                intent.putExtra(Intent.EXTRA_UID, uid);
13467            }
13468            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13469            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13470            if (DEBUG_BROADCASTS) {
13471                RuntimeException here = new RuntimeException("here");
13472                here.fillInStackTrace();
13473                Slog.d(TAG, "Sending to user " + id + ": "
13474                        + intent.toShortString(false, true, false, false)
13475                        + " " + intent.getExtras(), here);
13476            }
13477            am.broadcastIntent(null, intent, null, finishedReceiver,
13478                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13479                    null, finishedReceiver != null, false, id);
13480        }
13481    }
13482
13483    /**
13484     * Check if the external storage media is available. This is true if there
13485     * is a mounted external storage medium or if the external storage is
13486     * emulated.
13487     */
13488    private boolean isExternalMediaAvailable() {
13489        return mMediaMounted || Environment.isExternalStorageEmulated();
13490    }
13491
13492    @Override
13493    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13494        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13495            return null;
13496        }
13497        if (!isExternalMediaAvailable()) {
13498                // If the external storage is no longer mounted at this point,
13499                // the caller may not have been able to delete all of this
13500                // packages files and can not delete any more.  Bail.
13501            return null;
13502        }
13503        synchronized (mPackages) {
13504            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13505            if (lastPackage != null) {
13506                pkgs.remove(lastPackage);
13507            }
13508            if (pkgs.size() > 0) {
13509                return pkgs.get(0);
13510            }
13511        }
13512        return null;
13513    }
13514
13515    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13516        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13517                userId, andCode ? 1 : 0, packageName);
13518        if (mSystemReady) {
13519            msg.sendToTarget();
13520        } else {
13521            if (mPostSystemReadyMessages == null) {
13522                mPostSystemReadyMessages = new ArrayList<>();
13523            }
13524            mPostSystemReadyMessages.add(msg);
13525        }
13526    }
13527
13528    void startCleaningPackages() {
13529        // reader
13530        if (!isExternalMediaAvailable()) {
13531            return;
13532        }
13533        synchronized (mPackages) {
13534            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13535                return;
13536            }
13537        }
13538        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13539        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13540        IActivityManager am = ActivityManager.getService();
13541        if (am != null) {
13542            int dcsUid = -1;
13543            synchronized (mPackages) {
13544                if (!mDefaultContainerWhitelisted) {
13545                    mDefaultContainerWhitelisted = true;
13546                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13547                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13548                }
13549            }
13550            try {
13551                if (dcsUid > 0) {
13552                    am.backgroundWhitelistUid(dcsUid);
13553                }
13554                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13555                        UserHandle.USER_SYSTEM);
13556            } catch (RemoteException e) {
13557            }
13558        }
13559    }
13560
13561    /**
13562     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13563     * it is acting on behalf on an enterprise or the user).
13564     *
13565     * Note that the ordering of the conditionals in this method is important. The checks we perform
13566     * are as follows, in this order:
13567     *
13568     * 1) If the install is being performed by a system app, we can trust the app to have set the
13569     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13570     *    what it is.
13571     * 2) If the install is being performed by a device or profile owner app, the install reason
13572     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13573     *    set the install reason correctly. If the app targets an older SDK version where install
13574     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13575     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13576     * 3) In all other cases, the install is being performed by a regular app that is neither part
13577     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13578     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13579     *    set to enterprise policy and if so, change it to unknown instead.
13580     */
13581    private int fixUpInstallReason(String installerPackageName, int installerUid,
13582            int installReason) {
13583        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13584                == PERMISSION_GRANTED) {
13585            // If the install is being performed by a system app, we trust that app to have set the
13586            // install reason correctly.
13587            return installReason;
13588        }
13589
13590        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13591            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13592        if (dpm != null) {
13593            ComponentName owner = null;
13594            try {
13595                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13596                if (owner == null) {
13597                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13598                }
13599            } catch (RemoteException e) {
13600            }
13601            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13602                // If the install is being performed by a device or profile owner, the install
13603                // reason should be enterprise policy.
13604                return PackageManager.INSTALL_REASON_POLICY;
13605            }
13606        }
13607
13608        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13609            // If the install is being performed by a regular app (i.e. neither system app nor
13610            // device or profile owner), we have no reason to believe that the app is acting on
13611            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13612            // change it to unknown instead.
13613            return PackageManager.INSTALL_REASON_UNKNOWN;
13614        }
13615
13616        // If the install is being performed by a regular app and the install reason was set to any
13617        // value but enterprise policy, leave the install reason unchanged.
13618        return installReason;
13619    }
13620
13621    void installStage(String packageName, File stagedDir,
13622            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13623            String installerPackageName, int installerUid, UserHandle user,
13624            PackageParser.SigningDetails signingDetails) {
13625        if (DEBUG_INSTANT) {
13626            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13627                Slog.d(TAG, "Ephemeral install of " + packageName);
13628            }
13629        }
13630        final VerificationInfo verificationInfo = new VerificationInfo(
13631                sessionParams.originatingUri, sessionParams.referrerUri,
13632                sessionParams.originatingUid, installerUid);
13633
13634        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13635
13636        final Message msg = mHandler.obtainMessage(INIT_COPY);
13637        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13638                sessionParams.installReason);
13639        final InstallParams params = new InstallParams(origin, null, observer,
13640                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13641                verificationInfo, user, sessionParams.abiOverride,
13642                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13643        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13644        msg.obj = params;
13645
13646        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13647                System.identityHashCode(msg.obj));
13648        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13649                System.identityHashCode(msg.obj));
13650
13651        mHandler.sendMessage(msg);
13652    }
13653
13654    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13655            int userId) {
13656        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13657        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13658        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13659        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13660        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13661                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13662
13663        // Send a session commit broadcast
13664        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13665        info.installReason = pkgSetting.getInstallReason(userId);
13666        info.appPackageName = packageName;
13667        sendSessionCommitBroadcast(info, userId);
13668    }
13669
13670    @Override
13671    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13672            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13673        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13674            return;
13675        }
13676        Bundle extras = new Bundle(1);
13677        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13678        final int uid = UserHandle.getUid(
13679                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13680        extras.putInt(Intent.EXTRA_UID, uid);
13681
13682        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13683                packageName, extras, 0, null, null, userIds, instantUserIds);
13684        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13685            mHandler.post(() -> {
13686                        for (int userId : userIds) {
13687                            sendBootCompletedBroadcastToSystemApp(
13688                                    packageName, includeStopped, userId);
13689                        }
13690                    }
13691            );
13692        }
13693    }
13694
13695    /**
13696     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13697     * automatically without needing an explicit launch.
13698     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13699     */
13700    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13701            int userId) {
13702        // If user is not running, the app didn't miss any broadcast
13703        if (!mUserManagerInternal.isUserRunning(userId)) {
13704            return;
13705        }
13706        final IActivityManager am = ActivityManager.getService();
13707        try {
13708            // Deliver LOCKED_BOOT_COMPLETED first
13709            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13710                    .setPackage(packageName);
13711            if (includeStopped) {
13712                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13713            }
13714            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13715            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13716                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13717
13718            // Deliver BOOT_COMPLETED only if user is unlocked
13719            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13720                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13721                if (includeStopped) {
13722                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13723                }
13724                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13725                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13726            }
13727        } catch (RemoteException e) {
13728            throw e.rethrowFromSystemServer();
13729        }
13730    }
13731
13732    @Override
13733    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13734            int userId) {
13735        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13736        PackageSetting pkgSetting;
13737        final int callingUid = Binder.getCallingUid();
13738        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13739                true /* requireFullPermission */, true /* checkShell */,
13740                "setApplicationHiddenSetting for user " + userId);
13741
13742        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13743            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13744            return false;
13745        }
13746
13747        long callingId = Binder.clearCallingIdentity();
13748        try {
13749            boolean sendAdded = false;
13750            boolean sendRemoved = false;
13751            // writer
13752            synchronized (mPackages) {
13753                pkgSetting = mSettings.mPackages.get(packageName);
13754                if (pkgSetting == null) {
13755                    return false;
13756                }
13757                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13758                    return false;
13759                }
13760                // Do not allow "android" is being disabled
13761                if ("android".equals(packageName)) {
13762                    Slog.w(TAG, "Cannot hide package: android");
13763                    return false;
13764                }
13765                // Cannot hide static shared libs as they are considered
13766                // a part of the using app (emulating static linking). Also
13767                // static libs are installed always on internal storage.
13768                PackageParser.Package pkg = mPackages.get(packageName);
13769                if (pkg != null && pkg.staticSharedLibName != null) {
13770                    Slog.w(TAG, "Cannot hide package: " + packageName
13771                            + " providing static shared library: "
13772                            + pkg.staticSharedLibName);
13773                    return false;
13774                }
13775                // Only allow protected packages to hide themselves.
13776                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13777                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13778                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13779                    return false;
13780                }
13781
13782                if (pkgSetting.getHidden(userId) != hidden) {
13783                    pkgSetting.setHidden(hidden, userId);
13784                    mSettings.writePackageRestrictionsLPr(userId);
13785                    if (hidden) {
13786                        sendRemoved = true;
13787                    } else {
13788                        sendAdded = true;
13789                    }
13790                }
13791            }
13792            if (sendAdded) {
13793                sendPackageAddedForUser(packageName, pkgSetting, userId);
13794                return true;
13795            }
13796            if (sendRemoved) {
13797                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13798                        "hiding pkg");
13799                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13800                return true;
13801            }
13802        } finally {
13803            Binder.restoreCallingIdentity(callingId);
13804        }
13805        return false;
13806    }
13807
13808    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13809            int userId) {
13810        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13811        info.removedPackage = packageName;
13812        info.installerPackageName = pkgSetting.installerPackageName;
13813        info.removedUsers = new int[] {userId};
13814        info.broadcastUsers = new int[] {userId};
13815        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13816        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13817    }
13818
13819    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13820            PersistableBundle launcherExtras) {
13821        if (pkgList.length > 0) {
13822            Bundle extras = new Bundle(1);
13823            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13824            if (launcherExtras != null) {
13825                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13826                        new Bundle(launcherExtras.deepCopy()));
13827            }
13828            sendPackageBroadcast(
13829                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13830                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13831                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13832                    new int[] {userId}, null);
13833        }
13834    }
13835
13836    /**
13837     * Returns true if application is not found or there was an error. Otherwise it returns
13838     * the hidden state of the package for the given user.
13839     */
13840    @Override
13841    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13842        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13843        final int callingUid = Binder.getCallingUid();
13844        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13845                true /* requireFullPermission */, false /* checkShell */,
13846                "getApplicationHidden for user " + userId);
13847        PackageSetting ps;
13848        long callingId = Binder.clearCallingIdentity();
13849        try {
13850            // writer
13851            synchronized (mPackages) {
13852                ps = mSettings.mPackages.get(packageName);
13853                if (ps == null) {
13854                    return true;
13855                }
13856                if (filterAppAccessLPr(ps, callingUid, userId)) {
13857                    return true;
13858                }
13859                return ps.getHidden(userId);
13860            }
13861        } finally {
13862            Binder.restoreCallingIdentity(callingId);
13863        }
13864    }
13865
13866    /**
13867     * @hide
13868     */
13869    @Override
13870    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13871            int installReason) {
13872        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13873                null);
13874        PackageSetting pkgSetting;
13875        final int callingUid = Binder.getCallingUid();
13876        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13877                true /* requireFullPermission */, true /* checkShell */,
13878                "installExistingPackage for user " + userId);
13879        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13880            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13881        }
13882
13883        long callingId = Binder.clearCallingIdentity();
13884        try {
13885            boolean installed = false;
13886            final boolean instantApp =
13887                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13888            final boolean fullApp =
13889                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13890
13891            // writer
13892            synchronized (mPackages) {
13893                pkgSetting = mSettings.mPackages.get(packageName);
13894                if (pkgSetting == null) {
13895                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13896                }
13897                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13898                    // only allow the existing package to be used if it's installed as a full
13899                    // application for at least one user
13900                    boolean installAllowed = false;
13901                    for (int checkUserId : sUserManager.getUserIds()) {
13902                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13903                        if (installAllowed) {
13904                            break;
13905                        }
13906                    }
13907                    if (!installAllowed) {
13908                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13909                    }
13910                }
13911                if (!pkgSetting.getInstalled(userId)) {
13912                    pkgSetting.setInstalled(true, userId);
13913                    pkgSetting.setHidden(false, userId);
13914                    pkgSetting.setInstallReason(installReason, userId);
13915                    mSettings.writePackageRestrictionsLPr(userId);
13916                    mSettings.writeKernelMappingLPr(pkgSetting);
13917                    installed = true;
13918                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13919                    // upgrade app from instant to full; we don't allow app downgrade
13920                    installed = true;
13921                }
13922                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13923            }
13924
13925            if (installed) {
13926                if (pkgSetting.pkg != null) {
13927                    synchronized (mInstallLock) {
13928                        // We don't need to freeze for a brand new install
13929                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13930                    }
13931                }
13932                sendPackageAddedForUser(packageName, pkgSetting, userId);
13933                synchronized (mPackages) {
13934                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13935                }
13936            }
13937        } finally {
13938            Binder.restoreCallingIdentity(callingId);
13939        }
13940
13941        return PackageManager.INSTALL_SUCCEEDED;
13942    }
13943
13944    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13945            boolean instantApp, boolean fullApp) {
13946        // no state specified; do nothing
13947        if (!instantApp && !fullApp) {
13948            return;
13949        }
13950        if (userId != UserHandle.USER_ALL) {
13951            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13952                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13953            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13954                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13955            }
13956        } else {
13957            for (int currentUserId : sUserManager.getUserIds()) {
13958                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13959                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13960                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13961                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13962                }
13963            }
13964        }
13965    }
13966
13967    boolean isUserRestricted(int userId, String restrictionKey) {
13968        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13969        if (restrictions.getBoolean(restrictionKey, false)) {
13970            Log.w(TAG, "User is restricted: " + restrictionKey);
13971            return true;
13972        }
13973        return false;
13974    }
13975
13976    @Override
13977    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13978            PersistableBundle appExtras, PersistableBundle launcherExtras, String callingPackage,
13979            int userId) {
13980        try {
13981            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
13982        } catch (SecurityException e) {
13983            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
13984                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
13985                            + Manifest.permission.MANAGE_USERS);
13986        }
13987        final int callingUid = Binder.getCallingUid();
13988        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13989                true /* requireFullPermission */, true /* checkShell */,
13990                "setPackagesSuspended for user " + userId);
13991        if (callingUid != Process.ROOT_UID &&
13992                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
13993            throw new IllegalArgumentException("callingPackage " + callingPackage + " does not"
13994                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
13995        }
13996
13997        if (ArrayUtils.isEmpty(packageNames)) {
13998            return packageNames;
13999        }
14000
14001        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14002        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14003        final long callingId = Binder.clearCallingIdentity();
14004        try {
14005            synchronized (mPackages) {
14006                for (int i = 0; i < packageNames.length; i++) {
14007                    final String packageName = packageNames[i];
14008                    if (callingPackage.equals(packageName)) {
14009                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14010                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14011                        unactionedPackages.add(packageName);
14012                        continue;
14013                    }
14014                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14015                    if (pkgSetting == null
14016                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14017                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14018                                + "\". Skipping suspending/un-suspending.");
14019                        unactionedPackages.add(packageName);
14020                        continue;
14021                    }
14022                    if (pkgSetting.getSuspended(userId) != suspended) {
14023                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14024                            unactionedPackages.add(packageName);
14025                            continue;
14026                        }
14027                        pkgSetting.setSuspended(suspended, callingPackage, appExtras,
14028                                launcherExtras, userId);
14029                        changedPackagesList.add(packageName);
14030                    }
14031                }
14032            }
14033        } finally {
14034            Binder.restoreCallingIdentity(callingId);
14035        }
14036        if (!changedPackagesList.isEmpty()) {
14037            final String[] changedPackages = changedPackagesList.toArray(
14038                    new String[changedPackagesList.size()]);
14039            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14040            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14041            synchronized (mPackages) {
14042                scheduleWritePackageRestrictionsLocked(userId);
14043            }
14044        }
14045
14046        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14047    }
14048
14049    @Override
14050    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14051        final int callingUid = Binder.getCallingUid();
14052        if (getPackageUid(packageName, 0, userId) != callingUid) {
14053            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14054        }
14055        synchronized (mPackages) {
14056            final PackageSetting ps = mSettings.mPackages.get(packageName);
14057            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14058                throw new IllegalArgumentException("Unknown target package: " + packageName);
14059            }
14060            final PackageUserState packageUserState = ps.readUserState(userId);
14061            if (packageUserState.suspended) {
14062                return packageUserState.suspendedAppExtras;
14063            }
14064            return null;
14065        }
14066    }
14067
14068    @Override
14069    public void setSuspendedPackageAppExtras(String packageName, PersistableBundle appExtras,
14070            int userId) {
14071        final int callingUid = Binder.getCallingUid();
14072        mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14073        synchronized (mPackages) {
14074            final PackageSetting ps = mSettings.mPackages.get(packageName);
14075            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14076                throw new IllegalArgumentException("Unknown target package: " + packageName);
14077            }
14078            final PackageUserState packageUserState = ps.readUserState(userId);
14079            if (packageUserState.suspended) {
14080                packageUserState.suspendedAppExtras = appExtras;
14081                sendMyPackageSuspendedOrUnsuspended(new String[] {packageName}, true, appExtras,
14082                        userId);
14083            }
14084        }
14085    }
14086
14087    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14088            PersistableBundle appExtras, int userId) {
14089        final String action;
14090        final Bundle intentExtras = new Bundle();
14091        if (suspended) {
14092            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14093            if (appExtras != null) {
14094                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14095                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14096            }
14097        } else {
14098            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14099        }
14100        mHandler.post(new Runnable() {
14101            @Override
14102            public void run() {
14103                try {
14104                    final IActivityManager am = ActivityManager.getService();
14105                    if (am == null) {
14106                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14107                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14108                        return;
14109                    }
14110                    final int[] targetUserIds = new int[] {userId};
14111                    for (String packageName : affectedPackages) {
14112                        doSendBroadcast(am, action, null, intentExtras,
14113                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14114                                targetUserIds, false);
14115                    }
14116                } catch (RemoteException ex) {
14117                    // Shouldn't happen as AMS is in the same process.
14118                }
14119            }
14120        });
14121    }
14122
14123    @Override
14124    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14125        final int callingUid = Binder.getCallingUid();
14126        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14127                true /* requireFullPermission */, false /* checkShell */,
14128                "isPackageSuspendedForUser for user " + userId);
14129        if (getPackageUid(packageName, 0, userId) != callingUid) {
14130            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14131        }
14132        synchronized (mPackages) {
14133            final PackageSetting ps = mSettings.mPackages.get(packageName);
14134            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14135                throw new IllegalArgumentException("Unknown target package: " + packageName);
14136            }
14137            return ps.getSuspended(userId);
14138        }
14139    }
14140
14141    void onSuspendingPackageRemoved(String packageName, int userId) {
14142        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14143                : new int[] {userId};
14144        synchronized (mPackages) {
14145            for (PackageSetting ps : mSettings.mPackages.values()) {
14146                for (int user : userIds) {
14147                    final PackageUserState pus = ps.readUserState(user);
14148                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14149                        ps.setSuspended(false, null, null, null, user);
14150                    }
14151                }
14152            }
14153        }
14154    }
14155
14156    @GuardedBy("mPackages")
14157    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14158        if (isPackageDeviceAdmin(packageName, userId)) {
14159            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14160                    + "\": has an active device admin");
14161            return false;
14162        }
14163
14164        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14165        if (packageName.equals(activeLauncherPackageName)) {
14166            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14167                    + "\": contains the active launcher");
14168            return false;
14169        }
14170
14171        if (packageName.equals(mRequiredInstallerPackage)) {
14172            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14173                    + "\": required for package installation");
14174            return false;
14175        }
14176
14177        if (packageName.equals(mRequiredUninstallerPackage)) {
14178            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14179                    + "\": required for package uninstallation");
14180            return false;
14181        }
14182
14183        if (packageName.equals(mRequiredVerifierPackage)) {
14184            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14185                    + "\": required for package verification");
14186            return false;
14187        }
14188
14189        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14190            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14191                    + "\": is the default dialer");
14192            return false;
14193        }
14194
14195        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14196            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14197                    + "\": protected package");
14198            return false;
14199        }
14200
14201        // Cannot suspend static shared libs as they are considered
14202        // a part of the using app (emulating static linking). Also
14203        // static libs are installed always on internal storage.
14204        PackageParser.Package pkg = mPackages.get(packageName);
14205        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14206            Slog.w(TAG, "Cannot suspend package: " + packageName
14207                    + " providing static shared library: "
14208                    + pkg.staticSharedLibName);
14209            return false;
14210        }
14211
14212        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14213            Slog.w(TAG, "Cannot suspend package: " + packageName);
14214            return false;
14215        }
14216
14217        return true;
14218    }
14219
14220    private String getActiveLauncherPackageName(int userId) {
14221        Intent intent = new Intent(Intent.ACTION_MAIN);
14222        intent.addCategory(Intent.CATEGORY_HOME);
14223        ResolveInfo resolveInfo = resolveIntent(
14224                intent,
14225                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14226                PackageManager.MATCH_DEFAULT_ONLY,
14227                userId);
14228
14229        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14230    }
14231
14232    private String getDefaultDialerPackageName(int userId) {
14233        synchronized (mPackages) {
14234            return mSettings.getDefaultDialerPackageNameLPw(userId);
14235        }
14236    }
14237
14238    @Override
14239    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14240        mContext.enforceCallingOrSelfPermission(
14241                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14242                "Only package verification agents can verify applications");
14243
14244        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14245        final PackageVerificationResponse response = new PackageVerificationResponse(
14246                verificationCode, Binder.getCallingUid());
14247        msg.arg1 = id;
14248        msg.obj = response;
14249        mHandler.sendMessage(msg);
14250    }
14251
14252    @Override
14253    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14254            long millisecondsToDelay) {
14255        mContext.enforceCallingOrSelfPermission(
14256                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14257                "Only package verification agents can extend verification timeouts");
14258
14259        final PackageVerificationState state = mPendingVerification.get(id);
14260        final PackageVerificationResponse response = new PackageVerificationResponse(
14261                verificationCodeAtTimeout, Binder.getCallingUid());
14262
14263        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14264            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14265        }
14266        if (millisecondsToDelay < 0) {
14267            millisecondsToDelay = 0;
14268        }
14269        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14270                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14271            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14272        }
14273
14274        if ((state != null) && !state.timeoutExtended()) {
14275            state.extendTimeout();
14276
14277            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14278            msg.arg1 = id;
14279            msg.obj = response;
14280            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14281        }
14282    }
14283
14284    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14285            int verificationCode, UserHandle user) {
14286        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14287        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14288        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14289        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14290        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14291
14292        mContext.sendBroadcastAsUser(intent, user,
14293                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14294    }
14295
14296    private ComponentName matchComponentForVerifier(String packageName,
14297            List<ResolveInfo> receivers) {
14298        ActivityInfo targetReceiver = null;
14299
14300        final int NR = receivers.size();
14301        for (int i = 0; i < NR; i++) {
14302            final ResolveInfo info = receivers.get(i);
14303            if (info.activityInfo == null) {
14304                continue;
14305            }
14306
14307            if (packageName.equals(info.activityInfo.packageName)) {
14308                targetReceiver = info.activityInfo;
14309                break;
14310            }
14311        }
14312
14313        if (targetReceiver == null) {
14314            return null;
14315        }
14316
14317        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14318    }
14319
14320    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14321            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14322        if (pkgInfo.verifiers.length == 0) {
14323            return null;
14324        }
14325
14326        final int N = pkgInfo.verifiers.length;
14327        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14328        for (int i = 0; i < N; i++) {
14329            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14330
14331            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14332                    receivers);
14333            if (comp == null) {
14334                continue;
14335            }
14336
14337            final int verifierUid = getUidForVerifier(verifierInfo);
14338            if (verifierUid == -1) {
14339                continue;
14340            }
14341
14342            if (DEBUG_VERIFY) {
14343                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14344                        + " with the correct signature");
14345            }
14346            sufficientVerifiers.add(comp);
14347            verificationState.addSufficientVerifier(verifierUid);
14348        }
14349
14350        return sufficientVerifiers;
14351    }
14352
14353    private int getUidForVerifier(VerifierInfo verifierInfo) {
14354        synchronized (mPackages) {
14355            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14356            if (pkg == null) {
14357                return -1;
14358            } else if (pkg.mSigningDetails.signatures.length != 1) {
14359                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14360                        + " has more than one signature; ignoring");
14361                return -1;
14362            }
14363
14364            /*
14365             * If the public key of the package's signature does not match
14366             * our expected public key, then this is a different package and
14367             * we should skip.
14368             */
14369
14370            final byte[] expectedPublicKey;
14371            try {
14372                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14373                final PublicKey publicKey = verifierSig.getPublicKey();
14374                expectedPublicKey = publicKey.getEncoded();
14375            } catch (CertificateException e) {
14376                return -1;
14377            }
14378
14379            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14380
14381            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14382                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14383                        + " does not have the expected public key; ignoring");
14384                return -1;
14385            }
14386
14387            return pkg.applicationInfo.uid;
14388        }
14389    }
14390
14391    @Override
14392    public void finishPackageInstall(int token, boolean didLaunch) {
14393        enforceSystemOrRoot("Only the system is allowed to finish installs");
14394
14395        if (DEBUG_INSTALL) {
14396            Slog.v(TAG, "BM finishing package install for " + token);
14397        }
14398        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14399
14400        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14401        mHandler.sendMessage(msg);
14402    }
14403
14404    /**
14405     * Get the verification agent timeout.  Used for both the APK verifier and the
14406     * intent filter verifier.
14407     *
14408     * @return verification timeout in milliseconds
14409     */
14410    private long getVerificationTimeout() {
14411        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14412                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14413                DEFAULT_VERIFICATION_TIMEOUT);
14414    }
14415
14416    /**
14417     * Get the default verification agent response code.
14418     *
14419     * @return default verification response code
14420     */
14421    private int getDefaultVerificationResponse(UserHandle user) {
14422        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14423            return PackageManager.VERIFICATION_REJECT;
14424        }
14425        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14426                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14427                DEFAULT_VERIFICATION_RESPONSE);
14428    }
14429
14430    /**
14431     * Check whether or not package verification has been enabled.
14432     *
14433     * @return true if verification should be performed
14434     */
14435    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14436        if (!DEFAULT_VERIFY_ENABLE) {
14437            return false;
14438        }
14439
14440        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14441
14442        // Check if installing from ADB
14443        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14444            // Do not run verification in a test harness environment
14445            if (ActivityManager.isRunningInTestHarness()) {
14446                return false;
14447            }
14448            if (ensureVerifyAppsEnabled) {
14449                return true;
14450            }
14451            // Check if the developer does not want package verification for ADB installs
14452            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14453                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14454                return false;
14455            }
14456        } else {
14457            // only when not installed from ADB, skip verification for instant apps when
14458            // the installer and verifier are the same.
14459            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14460                if (mInstantAppInstallerActivity != null
14461                        && mInstantAppInstallerActivity.packageName.equals(
14462                                mRequiredVerifierPackage)) {
14463                    try {
14464                        mContext.getSystemService(AppOpsManager.class)
14465                                .checkPackage(installerUid, mRequiredVerifierPackage);
14466                        if (DEBUG_VERIFY) {
14467                            Slog.i(TAG, "disable verification for instant app");
14468                        }
14469                        return false;
14470                    } catch (SecurityException ignore) { }
14471                }
14472            }
14473        }
14474
14475        if (ensureVerifyAppsEnabled) {
14476            return true;
14477        }
14478
14479        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14480                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14481    }
14482
14483    @Override
14484    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14485            throws RemoteException {
14486        mContext.enforceCallingOrSelfPermission(
14487                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14488                "Only intentfilter verification agents can verify applications");
14489
14490        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14491        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14492                Binder.getCallingUid(), verificationCode, failedDomains);
14493        msg.arg1 = id;
14494        msg.obj = response;
14495        mHandler.sendMessage(msg);
14496    }
14497
14498    @Override
14499    public int getIntentVerificationStatus(String packageName, int userId) {
14500        final int callingUid = Binder.getCallingUid();
14501        if (UserHandle.getUserId(callingUid) != userId) {
14502            mContext.enforceCallingOrSelfPermission(
14503                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14504                    "getIntentVerificationStatus" + userId);
14505        }
14506        if (getInstantAppPackageName(callingUid) != null) {
14507            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14508        }
14509        synchronized (mPackages) {
14510            final PackageSetting ps = mSettings.mPackages.get(packageName);
14511            if (ps == null
14512                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14513                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14514            }
14515            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14516        }
14517    }
14518
14519    @Override
14520    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14521        mContext.enforceCallingOrSelfPermission(
14522                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14523
14524        boolean result = false;
14525        synchronized (mPackages) {
14526            final PackageSetting ps = mSettings.mPackages.get(packageName);
14527            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14528                return false;
14529            }
14530            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14531        }
14532        if (result) {
14533            scheduleWritePackageRestrictionsLocked(userId);
14534        }
14535        return result;
14536    }
14537
14538    @Override
14539    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14540            String packageName) {
14541        final int callingUid = Binder.getCallingUid();
14542        if (getInstantAppPackageName(callingUid) != null) {
14543            return ParceledListSlice.emptyList();
14544        }
14545        synchronized (mPackages) {
14546            final PackageSetting ps = mSettings.mPackages.get(packageName);
14547            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14548                return ParceledListSlice.emptyList();
14549            }
14550            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14551        }
14552    }
14553
14554    @Override
14555    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14556        if (TextUtils.isEmpty(packageName)) {
14557            return ParceledListSlice.emptyList();
14558        }
14559        final int callingUid = Binder.getCallingUid();
14560        final int callingUserId = UserHandle.getUserId(callingUid);
14561        synchronized (mPackages) {
14562            PackageParser.Package pkg = mPackages.get(packageName);
14563            if (pkg == null || pkg.activities == null) {
14564                return ParceledListSlice.emptyList();
14565            }
14566            if (pkg.mExtras == null) {
14567                return ParceledListSlice.emptyList();
14568            }
14569            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14570            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14571                return ParceledListSlice.emptyList();
14572            }
14573            final int count = pkg.activities.size();
14574            ArrayList<IntentFilter> result = new ArrayList<>();
14575            for (int n=0; n<count; n++) {
14576                PackageParser.Activity activity = pkg.activities.get(n);
14577                if (activity.intents != null && activity.intents.size() > 0) {
14578                    result.addAll(activity.intents);
14579                }
14580            }
14581            return new ParceledListSlice<>(result);
14582        }
14583    }
14584
14585    @Override
14586    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14587        mContext.enforceCallingOrSelfPermission(
14588                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14589        if (UserHandle.getCallingUserId() != userId) {
14590            mContext.enforceCallingOrSelfPermission(
14591                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14592        }
14593
14594        synchronized (mPackages) {
14595            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14596            if (packageName != null) {
14597                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14598                        packageName, userId);
14599            }
14600            return result;
14601        }
14602    }
14603
14604    @Override
14605    public String getDefaultBrowserPackageName(int userId) {
14606        if (UserHandle.getCallingUserId() != userId) {
14607            mContext.enforceCallingOrSelfPermission(
14608                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14609        }
14610        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14611            return null;
14612        }
14613        synchronized (mPackages) {
14614            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14615        }
14616    }
14617
14618    /**
14619     * Get the "allow unknown sources" setting.
14620     *
14621     * @return the current "allow unknown sources" setting
14622     */
14623    private int getUnknownSourcesSettings() {
14624        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14625                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14626                -1);
14627    }
14628
14629    @Override
14630    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14631        final int callingUid = Binder.getCallingUid();
14632        if (getInstantAppPackageName(callingUid) != null) {
14633            return;
14634        }
14635        // writer
14636        synchronized (mPackages) {
14637            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14638            if (targetPackageSetting == null
14639                    || filterAppAccessLPr(
14640                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14641                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14642            }
14643
14644            PackageSetting installerPackageSetting;
14645            if (installerPackageName != null) {
14646                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14647                if (installerPackageSetting == null) {
14648                    throw new IllegalArgumentException("Unknown installer package: "
14649                            + installerPackageName);
14650                }
14651            } else {
14652                installerPackageSetting = null;
14653            }
14654
14655            Signature[] callerSignature;
14656            Object obj = mSettings.getUserIdLPr(callingUid);
14657            if (obj != null) {
14658                if (obj instanceof SharedUserSetting) {
14659                    callerSignature =
14660                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14661                } else if (obj instanceof PackageSetting) {
14662                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14663                } else {
14664                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14665                }
14666            } else {
14667                throw new SecurityException("Unknown calling UID: " + callingUid);
14668            }
14669
14670            // Verify: can't set installerPackageName to a package that is
14671            // not signed with the same cert as the caller.
14672            if (installerPackageSetting != null) {
14673                if (compareSignatures(callerSignature,
14674                        installerPackageSetting.signatures.mSigningDetails.signatures)
14675                        != PackageManager.SIGNATURE_MATCH) {
14676                    throw new SecurityException(
14677                            "Caller does not have same cert as new installer package "
14678                            + installerPackageName);
14679                }
14680            }
14681
14682            // Verify: if target already has an installer package, it must
14683            // be signed with the same cert as the caller.
14684            if (targetPackageSetting.installerPackageName != null) {
14685                PackageSetting setting = mSettings.mPackages.get(
14686                        targetPackageSetting.installerPackageName);
14687                // If the currently set package isn't valid, then it's always
14688                // okay to change it.
14689                if (setting != null) {
14690                    if (compareSignatures(callerSignature,
14691                            setting.signatures.mSigningDetails.signatures)
14692                            != PackageManager.SIGNATURE_MATCH) {
14693                        throw new SecurityException(
14694                                "Caller does not have same cert as old installer package "
14695                                + targetPackageSetting.installerPackageName);
14696                    }
14697                }
14698            }
14699
14700            // Okay!
14701            targetPackageSetting.installerPackageName = installerPackageName;
14702            if (installerPackageName != null) {
14703                mSettings.mInstallerPackages.add(installerPackageName);
14704            }
14705            scheduleWriteSettingsLocked();
14706        }
14707    }
14708
14709    @Override
14710    public void setApplicationCategoryHint(String packageName, int categoryHint,
14711            String callerPackageName) {
14712        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14713            throw new SecurityException("Instant applications don't have access to this method");
14714        }
14715        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14716                callerPackageName);
14717        synchronized (mPackages) {
14718            PackageSetting ps = mSettings.mPackages.get(packageName);
14719            if (ps == null) {
14720                throw new IllegalArgumentException("Unknown target package " + packageName);
14721            }
14722            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14723                throw new IllegalArgumentException("Unknown target package " + packageName);
14724            }
14725            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14726                throw new IllegalArgumentException("Calling package " + callerPackageName
14727                        + " is not installer for " + packageName);
14728            }
14729
14730            if (ps.categoryHint != categoryHint) {
14731                ps.categoryHint = categoryHint;
14732                scheduleWriteSettingsLocked();
14733            }
14734        }
14735    }
14736
14737    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14738        // Queue up an async operation since the package installation may take a little while.
14739        mHandler.post(new Runnable() {
14740            public void run() {
14741                mHandler.removeCallbacks(this);
14742                 // Result object to be returned
14743                PackageInstalledInfo res = new PackageInstalledInfo();
14744                res.setReturnCode(currentStatus);
14745                res.uid = -1;
14746                res.pkg = null;
14747                res.removedInfo = null;
14748                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14749                    args.doPreInstall(res.returnCode);
14750                    synchronized (mInstallLock) {
14751                        installPackageTracedLI(args, res);
14752                    }
14753                    args.doPostInstall(res.returnCode, res.uid);
14754                }
14755
14756                // A restore should be performed at this point if (a) the install
14757                // succeeded, (b) the operation is not an update, and (c) the new
14758                // package has not opted out of backup participation.
14759                final boolean update = res.removedInfo != null
14760                        && res.removedInfo.removedPackage != null;
14761                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14762                boolean doRestore = !update
14763                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14764
14765                // Set up the post-install work request bookkeeping.  This will be used
14766                // and cleaned up by the post-install event handling regardless of whether
14767                // there's a restore pass performed.  Token values are >= 1.
14768                int token;
14769                if (mNextInstallToken < 0) mNextInstallToken = 1;
14770                token = mNextInstallToken++;
14771
14772                PostInstallData data = new PostInstallData(args, res);
14773                mRunningInstalls.put(token, data);
14774                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14775
14776                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14777                    // Pass responsibility to the Backup Manager.  It will perform a
14778                    // restore if appropriate, then pass responsibility back to the
14779                    // Package Manager to run the post-install observer callbacks
14780                    // and broadcasts.
14781                    IBackupManager bm = IBackupManager.Stub.asInterface(
14782                            ServiceManager.getService(Context.BACKUP_SERVICE));
14783                    if (bm != null) {
14784                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14785                                + " to BM for possible restore");
14786                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14787                        try {
14788                            // TODO: http://b/22388012
14789                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14790                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14791                            } else {
14792                                doRestore = false;
14793                            }
14794                        } catch (RemoteException e) {
14795                            // can't happen; the backup manager is local
14796                        } catch (Exception e) {
14797                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14798                            doRestore = false;
14799                        }
14800                    } else {
14801                        Slog.e(TAG, "Backup Manager not found!");
14802                        doRestore = false;
14803                    }
14804                }
14805
14806                if (!doRestore) {
14807                    // No restore possible, or the Backup Manager was mysteriously not
14808                    // available -- just fire the post-install work request directly.
14809                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14810
14811                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14812
14813                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14814                    mHandler.sendMessage(msg);
14815                }
14816            }
14817        });
14818    }
14819
14820    /**
14821     * Callback from PackageSettings whenever an app is first transitioned out of the
14822     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14823     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14824     * here whether the app is the target of an ongoing install, and only send the
14825     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14826     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14827     * handling.
14828     */
14829    void notifyFirstLaunch(final String packageName, final String installerPackage,
14830            final int userId) {
14831        // Serialize this with the rest of the install-process message chain.  In the
14832        // restore-at-install case, this Runnable will necessarily run before the
14833        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14834        // are coherent.  In the non-restore case, the app has already completed install
14835        // and been launched through some other means, so it is not in a problematic
14836        // state for observers to see the FIRST_LAUNCH signal.
14837        mHandler.post(new Runnable() {
14838            @Override
14839            public void run() {
14840                for (int i = 0; i < mRunningInstalls.size(); i++) {
14841                    final PostInstallData data = mRunningInstalls.valueAt(i);
14842                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14843                        continue;
14844                    }
14845                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14846                        // right package; but is it for the right user?
14847                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14848                            if (userId == data.res.newUsers[uIndex]) {
14849                                if (DEBUG_BACKUP) {
14850                                    Slog.i(TAG, "Package " + packageName
14851                                            + " being restored so deferring FIRST_LAUNCH");
14852                                }
14853                                return;
14854                            }
14855                        }
14856                    }
14857                }
14858                // didn't find it, so not being restored
14859                if (DEBUG_BACKUP) {
14860                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14861                }
14862                final boolean isInstantApp = isInstantApp(packageName, userId);
14863                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14864                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14865                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14866            }
14867        });
14868    }
14869
14870    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14871            int[] userIds, int[] instantUserIds) {
14872        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14873                installerPkg, null, userIds, instantUserIds);
14874    }
14875
14876    private abstract class HandlerParams {
14877        private static final int MAX_RETRIES = 4;
14878
14879        /**
14880         * Number of times startCopy() has been attempted and had a non-fatal
14881         * error.
14882         */
14883        private int mRetries = 0;
14884
14885        /** User handle for the user requesting the information or installation. */
14886        private final UserHandle mUser;
14887        String traceMethod;
14888        int traceCookie;
14889
14890        HandlerParams(UserHandle user) {
14891            mUser = user;
14892        }
14893
14894        UserHandle getUser() {
14895            return mUser;
14896        }
14897
14898        HandlerParams setTraceMethod(String traceMethod) {
14899            this.traceMethod = traceMethod;
14900            return this;
14901        }
14902
14903        HandlerParams setTraceCookie(int traceCookie) {
14904            this.traceCookie = traceCookie;
14905            return this;
14906        }
14907
14908        final boolean startCopy() {
14909            boolean res;
14910            try {
14911                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14912
14913                if (++mRetries > MAX_RETRIES) {
14914                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14915                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14916                    handleServiceError();
14917                    return false;
14918                } else {
14919                    handleStartCopy();
14920                    res = true;
14921                }
14922            } catch (RemoteException e) {
14923                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14924                mHandler.sendEmptyMessage(MCS_RECONNECT);
14925                res = false;
14926            }
14927            handleReturnCode();
14928            return res;
14929        }
14930
14931        final void serviceError() {
14932            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14933            handleServiceError();
14934            handleReturnCode();
14935        }
14936
14937        abstract void handleStartCopy() throws RemoteException;
14938        abstract void handleServiceError();
14939        abstract void handleReturnCode();
14940    }
14941
14942    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14943        for (File path : paths) {
14944            try {
14945                mcs.clearDirectory(path.getAbsolutePath());
14946            } catch (RemoteException e) {
14947            }
14948        }
14949    }
14950
14951    static class OriginInfo {
14952        /**
14953         * Location where install is coming from, before it has been
14954         * copied/renamed into place. This could be a single monolithic APK
14955         * file, or a cluster directory. This location may be untrusted.
14956         */
14957        final File file;
14958
14959        /**
14960         * Flag indicating that {@link #file} or {@link #cid} has already been
14961         * staged, meaning downstream users don't need to defensively copy the
14962         * contents.
14963         */
14964        final boolean staged;
14965
14966        /**
14967         * Flag indicating that {@link #file} or {@link #cid} is an already
14968         * installed app that is being moved.
14969         */
14970        final boolean existing;
14971
14972        final String resolvedPath;
14973        final File resolvedFile;
14974
14975        static OriginInfo fromNothing() {
14976            return new OriginInfo(null, false, false);
14977        }
14978
14979        static OriginInfo fromUntrustedFile(File file) {
14980            return new OriginInfo(file, false, false);
14981        }
14982
14983        static OriginInfo fromExistingFile(File file) {
14984            return new OriginInfo(file, false, true);
14985        }
14986
14987        static OriginInfo fromStagedFile(File file) {
14988            return new OriginInfo(file, true, false);
14989        }
14990
14991        private OriginInfo(File file, boolean staged, boolean existing) {
14992            this.file = file;
14993            this.staged = staged;
14994            this.existing = existing;
14995
14996            if (file != null) {
14997                resolvedPath = file.getAbsolutePath();
14998                resolvedFile = file;
14999            } else {
15000                resolvedPath = null;
15001                resolvedFile = null;
15002            }
15003        }
15004    }
15005
15006    static class MoveInfo {
15007        final int moveId;
15008        final String fromUuid;
15009        final String toUuid;
15010        final String packageName;
15011        final String dataAppName;
15012        final int appId;
15013        final String seinfo;
15014        final int targetSdkVersion;
15015
15016        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15017                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15018            this.moveId = moveId;
15019            this.fromUuid = fromUuid;
15020            this.toUuid = toUuid;
15021            this.packageName = packageName;
15022            this.dataAppName = dataAppName;
15023            this.appId = appId;
15024            this.seinfo = seinfo;
15025            this.targetSdkVersion = targetSdkVersion;
15026        }
15027    }
15028
15029    static class VerificationInfo {
15030        /** A constant used to indicate that a uid value is not present. */
15031        public static final int NO_UID = -1;
15032
15033        /** URI referencing where the package was downloaded from. */
15034        final Uri originatingUri;
15035
15036        /** HTTP referrer URI associated with the originatingURI. */
15037        final Uri referrer;
15038
15039        /** UID of the application that the install request originated from. */
15040        final int originatingUid;
15041
15042        /** UID of application requesting the install */
15043        final int installerUid;
15044
15045        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15046            this.originatingUri = originatingUri;
15047            this.referrer = referrer;
15048            this.originatingUid = originatingUid;
15049            this.installerUid = installerUid;
15050        }
15051    }
15052
15053    class InstallParams extends HandlerParams {
15054        final OriginInfo origin;
15055        final MoveInfo move;
15056        final IPackageInstallObserver2 observer;
15057        int installFlags;
15058        final String installerPackageName;
15059        final String volumeUuid;
15060        private InstallArgs mArgs;
15061        private int mRet;
15062        final String packageAbiOverride;
15063        final String[] grantedRuntimePermissions;
15064        final VerificationInfo verificationInfo;
15065        final PackageParser.SigningDetails signingDetails;
15066        final int installReason;
15067
15068        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15069                int installFlags, String installerPackageName, String volumeUuid,
15070                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15071                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15072            super(user);
15073            this.origin = origin;
15074            this.move = move;
15075            this.observer = observer;
15076            this.installFlags = installFlags;
15077            this.installerPackageName = installerPackageName;
15078            this.volumeUuid = volumeUuid;
15079            this.verificationInfo = verificationInfo;
15080            this.packageAbiOverride = packageAbiOverride;
15081            this.grantedRuntimePermissions = grantedPermissions;
15082            this.signingDetails = signingDetails;
15083            this.installReason = installReason;
15084        }
15085
15086        @Override
15087        public String toString() {
15088            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15089                    + " file=" + origin.file + "}";
15090        }
15091
15092        private int installLocationPolicy(PackageInfoLite pkgLite) {
15093            String packageName = pkgLite.packageName;
15094            int installLocation = pkgLite.installLocation;
15095            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15096            // reader
15097            synchronized (mPackages) {
15098                // Currently installed package which the new package is attempting to replace or
15099                // null if no such package is installed.
15100                PackageParser.Package installedPkg = mPackages.get(packageName);
15101                // Package which currently owns the data which the new package will own if installed.
15102                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15103                // will be null whereas dataOwnerPkg will contain information about the package
15104                // which was uninstalled while keeping its data.
15105                PackageParser.Package dataOwnerPkg = installedPkg;
15106                if (dataOwnerPkg  == null) {
15107                    PackageSetting ps = mSettings.mPackages.get(packageName);
15108                    if (ps != null) {
15109                        dataOwnerPkg = ps.pkg;
15110                    }
15111                }
15112
15113                if (dataOwnerPkg != null) {
15114                    // If installed, the package will get access to data left on the device by its
15115                    // predecessor. As a security measure, this is permited only if this is not a
15116                    // version downgrade or if the predecessor package is marked as debuggable and
15117                    // a downgrade is explicitly requested.
15118                    //
15119                    // On debuggable platform builds, downgrades are permitted even for
15120                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15121                    // not offer security guarantees and thus it's OK to disable some security
15122                    // mechanisms to make debugging/testing easier on those builds. However, even on
15123                    // debuggable builds downgrades of packages are permitted only if requested via
15124                    // installFlags. This is because we aim to keep the behavior of debuggable
15125                    // platform builds as close as possible to the behavior of non-debuggable
15126                    // platform builds.
15127                    final boolean downgradeRequested =
15128                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15129                    final boolean packageDebuggable =
15130                                (dataOwnerPkg.applicationInfo.flags
15131                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15132                    final boolean downgradePermitted =
15133                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15134                    if (!downgradePermitted) {
15135                        try {
15136                            checkDowngrade(dataOwnerPkg, pkgLite);
15137                        } catch (PackageManagerException e) {
15138                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15139                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15140                        }
15141                    }
15142                }
15143
15144                if (installedPkg != null) {
15145                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15146                        // Check for updated system application.
15147                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15148                            if (onSd) {
15149                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15150                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15151                            }
15152                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15153                        } else {
15154                            if (onSd) {
15155                                // Install flag overrides everything.
15156                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15157                            }
15158                            // If current upgrade specifies particular preference
15159                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15160                                // Application explicitly specified internal.
15161                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15162                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15163                                // App explictly prefers external. Let policy decide
15164                            } else {
15165                                // Prefer previous location
15166                                if (isExternal(installedPkg)) {
15167                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15168                                }
15169                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15170                            }
15171                        }
15172                    } else {
15173                        // Invalid install. Return error code
15174                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15175                    }
15176                }
15177            }
15178            // All the special cases have been taken care of.
15179            // Return result based on recommended install location.
15180            if (onSd) {
15181                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15182            }
15183            return pkgLite.recommendedInstallLocation;
15184        }
15185
15186        /*
15187         * Invoke remote method to get package information and install
15188         * location values. Override install location based on default
15189         * policy if needed and then create install arguments based
15190         * on the install location.
15191         */
15192        public void handleStartCopy() throws RemoteException {
15193            int ret = PackageManager.INSTALL_SUCCEEDED;
15194
15195            // If we're already staged, we've firmly committed to an install location
15196            if (origin.staged) {
15197                if (origin.file != null) {
15198                    installFlags |= PackageManager.INSTALL_INTERNAL;
15199                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15200                } else {
15201                    throw new IllegalStateException("Invalid stage location");
15202                }
15203            }
15204
15205            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15206            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15207            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15208            PackageInfoLite pkgLite = null;
15209
15210            if (onInt && onSd) {
15211                // Check if both bits are set.
15212                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15213                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15214            } else if (onSd && ephemeral) {
15215                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15216                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15217            } else {
15218                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15219                        packageAbiOverride);
15220
15221                if (DEBUG_INSTANT && ephemeral) {
15222                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15223                }
15224
15225                /*
15226                 * If we have too little free space, try to free cache
15227                 * before giving up.
15228                 */
15229                if (!origin.staged && pkgLite.recommendedInstallLocation
15230                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15231                    // TODO: focus freeing disk space on the target device
15232                    final StorageManager storage = StorageManager.from(mContext);
15233                    final long lowThreshold = storage.getStorageLowBytes(
15234                            Environment.getDataDirectory());
15235
15236                    final long sizeBytes = mContainerService.calculateInstalledSize(
15237                            origin.resolvedPath, packageAbiOverride);
15238
15239                    try {
15240                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15241                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15242                                installFlags, packageAbiOverride);
15243                    } catch (InstallerException e) {
15244                        Slog.w(TAG, "Failed to free cache", e);
15245                    }
15246
15247                    /*
15248                     * The cache free must have deleted the file we
15249                     * downloaded to install.
15250                     *
15251                     * TODO: fix the "freeCache" call to not delete
15252                     *       the file we care about.
15253                     */
15254                    if (pkgLite.recommendedInstallLocation
15255                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15256                        pkgLite.recommendedInstallLocation
15257                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15258                    }
15259                }
15260            }
15261
15262            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15263                int loc = pkgLite.recommendedInstallLocation;
15264                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15265                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15266                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15267                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15268                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15269                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15270                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15271                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15272                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15273                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15274                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15275                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15276                } else {
15277                    // Override with defaults if needed.
15278                    loc = installLocationPolicy(pkgLite);
15279                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15280                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15281                    } else if (!onSd && !onInt) {
15282                        // Override install location with flags
15283                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15284                            // Set the flag to install on external media.
15285                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15286                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15287                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15288                            if (DEBUG_INSTANT) {
15289                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15290                            }
15291                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15292                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15293                                    |PackageManager.INSTALL_INTERNAL);
15294                        } else {
15295                            // Make sure the flag for installing on external
15296                            // media is unset
15297                            installFlags |= PackageManager.INSTALL_INTERNAL;
15298                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15299                        }
15300                    }
15301                }
15302            }
15303
15304            final InstallArgs args = createInstallArgs(this);
15305            mArgs = args;
15306
15307            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15308                // TODO: http://b/22976637
15309                // Apps installed for "all" users use the device owner to verify the app
15310                UserHandle verifierUser = getUser();
15311                if (verifierUser == UserHandle.ALL) {
15312                    verifierUser = UserHandle.SYSTEM;
15313                }
15314
15315                /*
15316                 * Determine if we have any installed package verifiers. If we
15317                 * do, then we'll defer to them to verify the packages.
15318                 */
15319                final int requiredUid = mRequiredVerifierPackage == null ? -1
15320                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15321                                verifierUser.getIdentifier());
15322                final int installerUid =
15323                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15324                if (!origin.existing && requiredUid != -1
15325                        && isVerificationEnabled(
15326                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15327                    final Intent verification = new Intent(
15328                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15329                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15330                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15331                            PACKAGE_MIME_TYPE);
15332                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15333
15334                    // Query all live verifiers based on current user state
15335                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15336                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15337                            false /*allowDynamicSplits*/);
15338
15339                    if (DEBUG_VERIFY) {
15340                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15341                                + verification.toString() + " with " + pkgLite.verifiers.length
15342                                + " optional verifiers");
15343                    }
15344
15345                    final int verificationId = mPendingVerificationToken++;
15346
15347                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15348
15349                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15350                            installerPackageName);
15351
15352                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15353                            installFlags);
15354
15355                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15356                            pkgLite.packageName);
15357
15358                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15359                            pkgLite.versionCode);
15360
15361                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15362                            pkgLite.getLongVersionCode());
15363
15364                    if (verificationInfo != null) {
15365                        if (verificationInfo.originatingUri != null) {
15366                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15367                                    verificationInfo.originatingUri);
15368                        }
15369                        if (verificationInfo.referrer != null) {
15370                            verification.putExtra(Intent.EXTRA_REFERRER,
15371                                    verificationInfo.referrer);
15372                        }
15373                        if (verificationInfo.originatingUid >= 0) {
15374                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15375                                    verificationInfo.originatingUid);
15376                        }
15377                        if (verificationInfo.installerUid >= 0) {
15378                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15379                                    verificationInfo.installerUid);
15380                        }
15381                    }
15382
15383                    final PackageVerificationState verificationState = new PackageVerificationState(
15384                            requiredUid, args);
15385
15386                    mPendingVerification.append(verificationId, verificationState);
15387
15388                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15389                            receivers, verificationState);
15390
15391                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15392                    final long idleDuration = getVerificationTimeout();
15393
15394                    /*
15395                     * If any sufficient verifiers were listed in the package
15396                     * manifest, attempt to ask them.
15397                     */
15398                    if (sufficientVerifiers != null) {
15399                        final int N = sufficientVerifiers.size();
15400                        if (N == 0) {
15401                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15402                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15403                        } else {
15404                            for (int i = 0; i < N; i++) {
15405                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15406                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15407                                        verifierComponent.getPackageName(), idleDuration,
15408                                        verifierUser.getIdentifier(), false, "package verifier");
15409
15410                                final Intent sufficientIntent = new Intent(verification);
15411                                sufficientIntent.setComponent(verifierComponent);
15412                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15413                            }
15414                        }
15415                    }
15416
15417                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15418                            mRequiredVerifierPackage, receivers);
15419                    if (ret == PackageManager.INSTALL_SUCCEEDED
15420                            && mRequiredVerifierPackage != null) {
15421                        Trace.asyncTraceBegin(
15422                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15423                        /*
15424                         * Send the intent to the required verification agent,
15425                         * but only start the verification timeout after the
15426                         * target BroadcastReceivers have run.
15427                         */
15428                        verification.setComponent(requiredVerifierComponent);
15429                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15430                                mRequiredVerifierPackage, idleDuration,
15431                                verifierUser.getIdentifier(), false, "package verifier");
15432                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15433                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15434                                new BroadcastReceiver() {
15435                                    @Override
15436                                    public void onReceive(Context context, Intent intent) {
15437                                        final Message msg = mHandler
15438                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15439                                        msg.arg1 = verificationId;
15440                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15441                                    }
15442                                }, null, 0, null, null);
15443
15444                        /*
15445                         * We don't want the copy to proceed until verification
15446                         * succeeds, so null out this field.
15447                         */
15448                        mArgs = null;
15449                    }
15450                } else {
15451                    /*
15452                     * No package verification is enabled, so immediately start
15453                     * the remote call to initiate copy using temporary file.
15454                     */
15455                    ret = args.copyApk(mContainerService, true);
15456                }
15457            }
15458
15459            mRet = ret;
15460        }
15461
15462        @Override
15463        void handleReturnCode() {
15464            // If mArgs is null, then MCS couldn't be reached. When it
15465            // reconnects, it will try again to install. At that point, this
15466            // will succeed.
15467            if (mArgs != null) {
15468                processPendingInstall(mArgs, mRet);
15469            }
15470        }
15471
15472        @Override
15473        void handleServiceError() {
15474            mArgs = createInstallArgs(this);
15475            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15476        }
15477    }
15478
15479    private InstallArgs createInstallArgs(InstallParams params) {
15480        if (params.move != null) {
15481            return new MoveInstallArgs(params);
15482        } else {
15483            return new FileInstallArgs(params);
15484        }
15485    }
15486
15487    /**
15488     * Create args that describe an existing installed package. Typically used
15489     * when cleaning up old installs, or used as a move source.
15490     */
15491    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15492            String resourcePath, String[] instructionSets) {
15493        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15494    }
15495
15496    static abstract class InstallArgs {
15497        /** @see InstallParams#origin */
15498        final OriginInfo origin;
15499        /** @see InstallParams#move */
15500        final MoveInfo move;
15501
15502        final IPackageInstallObserver2 observer;
15503        // Always refers to PackageManager flags only
15504        final int installFlags;
15505        final String installerPackageName;
15506        final String volumeUuid;
15507        final UserHandle user;
15508        final String abiOverride;
15509        final String[] installGrantPermissions;
15510        /** If non-null, drop an async trace when the install completes */
15511        final String traceMethod;
15512        final int traceCookie;
15513        final PackageParser.SigningDetails signingDetails;
15514        final int installReason;
15515
15516        // The list of instruction sets supported by this app. This is currently
15517        // only used during the rmdex() phase to clean up resources. We can get rid of this
15518        // if we move dex files under the common app path.
15519        /* nullable */ String[] instructionSets;
15520
15521        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15522                int installFlags, String installerPackageName, String volumeUuid,
15523                UserHandle user, String[] instructionSets,
15524                String abiOverride, String[] installGrantPermissions,
15525                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15526                int installReason) {
15527            this.origin = origin;
15528            this.move = move;
15529            this.installFlags = installFlags;
15530            this.observer = observer;
15531            this.installerPackageName = installerPackageName;
15532            this.volumeUuid = volumeUuid;
15533            this.user = user;
15534            this.instructionSets = instructionSets;
15535            this.abiOverride = abiOverride;
15536            this.installGrantPermissions = installGrantPermissions;
15537            this.traceMethod = traceMethod;
15538            this.traceCookie = traceCookie;
15539            this.signingDetails = signingDetails;
15540            this.installReason = installReason;
15541        }
15542
15543        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15544        abstract int doPreInstall(int status);
15545
15546        /**
15547         * Rename package into final resting place. All paths on the given
15548         * scanned package should be updated to reflect the rename.
15549         */
15550        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15551        abstract int doPostInstall(int status, int uid);
15552
15553        /** @see PackageSettingBase#codePathString */
15554        abstract String getCodePath();
15555        /** @see PackageSettingBase#resourcePathString */
15556        abstract String getResourcePath();
15557
15558        // Need installer lock especially for dex file removal.
15559        abstract void cleanUpResourcesLI();
15560        abstract boolean doPostDeleteLI(boolean delete);
15561
15562        /**
15563         * Called before the source arguments are copied. This is used mostly
15564         * for MoveParams when it needs to read the source file to put it in the
15565         * destination.
15566         */
15567        int doPreCopy() {
15568            return PackageManager.INSTALL_SUCCEEDED;
15569        }
15570
15571        /**
15572         * Called after the source arguments are copied. This is used mostly for
15573         * MoveParams when it needs to read the source file to put it in the
15574         * destination.
15575         */
15576        int doPostCopy(int uid) {
15577            return PackageManager.INSTALL_SUCCEEDED;
15578        }
15579
15580        protected boolean isFwdLocked() {
15581            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15582        }
15583
15584        protected boolean isExternalAsec() {
15585            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15586        }
15587
15588        protected boolean isEphemeral() {
15589            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15590        }
15591
15592        UserHandle getUser() {
15593            return user;
15594        }
15595    }
15596
15597    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15598        if (!allCodePaths.isEmpty()) {
15599            if (instructionSets == null) {
15600                throw new IllegalStateException("instructionSet == null");
15601            }
15602            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15603            for (String codePath : allCodePaths) {
15604                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15605                    try {
15606                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15607                    } catch (InstallerException ignored) {
15608                    }
15609                }
15610            }
15611        }
15612    }
15613
15614    /**
15615     * Logic to handle installation of non-ASEC applications, including copying
15616     * and renaming logic.
15617     */
15618    class FileInstallArgs extends InstallArgs {
15619        private File codeFile;
15620        private File resourceFile;
15621
15622        // Example topology:
15623        // /data/app/com.example/base.apk
15624        // /data/app/com.example/split_foo.apk
15625        // /data/app/com.example/lib/arm/libfoo.so
15626        // /data/app/com.example/lib/arm64/libfoo.so
15627        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15628
15629        /** New install */
15630        FileInstallArgs(InstallParams params) {
15631            super(params.origin, params.move, params.observer, params.installFlags,
15632                    params.installerPackageName, params.volumeUuid,
15633                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15634                    params.grantedRuntimePermissions,
15635                    params.traceMethod, params.traceCookie, params.signingDetails,
15636                    params.installReason);
15637            if (isFwdLocked()) {
15638                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15639            }
15640        }
15641
15642        /** Existing install */
15643        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15644            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15645                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15646                    PackageManager.INSTALL_REASON_UNKNOWN);
15647            this.codeFile = (codePath != null) ? new File(codePath) : null;
15648            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15649        }
15650
15651        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15652            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15653            try {
15654                return doCopyApk(imcs, temp);
15655            } finally {
15656                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15657            }
15658        }
15659
15660        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15661            if (origin.staged) {
15662                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15663                codeFile = origin.file;
15664                resourceFile = origin.file;
15665                return PackageManager.INSTALL_SUCCEEDED;
15666            }
15667
15668            try {
15669                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15670                final File tempDir =
15671                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15672                codeFile = tempDir;
15673                resourceFile = tempDir;
15674            } catch (IOException e) {
15675                Slog.w(TAG, "Failed to create copy file: " + e);
15676                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15677            }
15678
15679            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15680                @Override
15681                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15682                    if (!FileUtils.isValidExtFilename(name)) {
15683                        throw new IllegalArgumentException("Invalid filename: " + name);
15684                    }
15685                    try {
15686                        final File file = new File(codeFile, name);
15687                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15688                                O_RDWR | O_CREAT, 0644);
15689                        Os.chmod(file.getAbsolutePath(), 0644);
15690                        return new ParcelFileDescriptor(fd);
15691                    } catch (ErrnoException e) {
15692                        throw new RemoteException("Failed to open: " + e.getMessage());
15693                    }
15694                }
15695            };
15696
15697            int ret = PackageManager.INSTALL_SUCCEEDED;
15698            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15699            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15700                Slog.e(TAG, "Failed to copy package");
15701                return ret;
15702            }
15703
15704            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15705            NativeLibraryHelper.Handle handle = null;
15706            try {
15707                handle = NativeLibraryHelper.Handle.create(codeFile);
15708                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15709                        abiOverride);
15710            } catch (IOException e) {
15711                Slog.e(TAG, "Copying native libraries failed", e);
15712                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15713            } finally {
15714                IoUtils.closeQuietly(handle);
15715            }
15716
15717            return ret;
15718        }
15719
15720        int doPreInstall(int status) {
15721            if (status != PackageManager.INSTALL_SUCCEEDED) {
15722                cleanUp();
15723            }
15724            return status;
15725        }
15726
15727        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15728            if (status != PackageManager.INSTALL_SUCCEEDED) {
15729                cleanUp();
15730                return false;
15731            }
15732
15733            final File targetDir = codeFile.getParentFile();
15734            final File beforeCodeFile = codeFile;
15735            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15736
15737            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15738            try {
15739                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15740            } catch (ErrnoException e) {
15741                Slog.w(TAG, "Failed to rename", e);
15742                return false;
15743            }
15744
15745            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15746                Slog.w(TAG, "Failed to restorecon");
15747                return false;
15748            }
15749
15750            // Reflect the rename internally
15751            codeFile = afterCodeFile;
15752            resourceFile = afterCodeFile;
15753
15754            // Reflect the rename in scanned details
15755            try {
15756                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15757            } catch (IOException e) {
15758                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15759                return false;
15760            }
15761            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15762                    afterCodeFile, pkg.baseCodePath));
15763            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15764                    afterCodeFile, pkg.splitCodePaths));
15765
15766            // Reflect the rename in app info
15767            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15768            pkg.setApplicationInfoCodePath(pkg.codePath);
15769            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15770            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15771            pkg.setApplicationInfoResourcePath(pkg.codePath);
15772            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15773            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15774
15775            return true;
15776        }
15777
15778        int doPostInstall(int status, int uid) {
15779            if (status != PackageManager.INSTALL_SUCCEEDED) {
15780                cleanUp();
15781            }
15782            return status;
15783        }
15784
15785        @Override
15786        String getCodePath() {
15787            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15788        }
15789
15790        @Override
15791        String getResourcePath() {
15792            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15793        }
15794
15795        private boolean cleanUp() {
15796            if (codeFile == null || !codeFile.exists()) {
15797                return false;
15798            }
15799
15800            removeCodePathLI(codeFile);
15801
15802            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15803                resourceFile.delete();
15804            }
15805
15806            return true;
15807        }
15808
15809        void cleanUpResourcesLI() {
15810            // Try enumerating all code paths before deleting
15811            List<String> allCodePaths = Collections.EMPTY_LIST;
15812            if (codeFile != null && codeFile.exists()) {
15813                try {
15814                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15815                    allCodePaths = pkg.getAllCodePaths();
15816                } catch (PackageParserException e) {
15817                    // Ignored; we tried our best
15818                }
15819            }
15820
15821            cleanUp();
15822            removeDexFiles(allCodePaths, instructionSets);
15823        }
15824
15825        boolean doPostDeleteLI(boolean delete) {
15826            // XXX err, shouldn't we respect the delete flag?
15827            cleanUpResourcesLI();
15828            return true;
15829        }
15830    }
15831
15832    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15833            PackageManagerException {
15834        if (copyRet < 0) {
15835            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15836                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15837                throw new PackageManagerException(copyRet, message);
15838            }
15839        }
15840    }
15841
15842    /**
15843     * Extract the StorageManagerService "container ID" from the full code path of an
15844     * .apk.
15845     */
15846    static String cidFromCodePath(String fullCodePath) {
15847        int eidx = fullCodePath.lastIndexOf("/");
15848        String subStr1 = fullCodePath.substring(0, eidx);
15849        int sidx = subStr1.lastIndexOf("/");
15850        return subStr1.substring(sidx+1, eidx);
15851    }
15852
15853    /**
15854     * Logic to handle movement of existing installed applications.
15855     */
15856    class MoveInstallArgs extends InstallArgs {
15857        private File codeFile;
15858        private File resourceFile;
15859
15860        /** New install */
15861        MoveInstallArgs(InstallParams params) {
15862            super(params.origin, params.move, params.observer, params.installFlags,
15863                    params.installerPackageName, params.volumeUuid,
15864                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15865                    params.grantedRuntimePermissions,
15866                    params.traceMethod, params.traceCookie, params.signingDetails,
15867                    params.installReason);
15868        }
15869
15870        int copyApk(IMediaContainerService imcs, boolean temp) {
15871            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15872                    + move.fromUuid + " to " + move.toUuid);
15873            synchronized (mInstaller) {
15874                try {
15875                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15876                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15877                } catch (InstallerException e) {
15878                    Slog.w(TAG, "Failed to move app", e);
15879                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15880                }
15881            }
15882
15883            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15884            resourceFile = codeFile;
15885            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15886
15887            return PackageManager.INSTALL_SUCCEEDED;
15888        }
15889
15890        int doPreInstall(int status) {
15891            if (status != PackageManager.INSTALL_SUCCEEDED) {
15892                cleanUp(move.toUuid);
15893            }
15894            return status;
15895        }
15896
15897        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15898            if (status != PackageManager.INSTALL_SUCCEEDED) {
15899                cleanUp(move.toUuid);
15900                return false;
15901            }
15902
15903            // Reflect the move in app info
15904            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15905            pkg.setApplicationInfoCodePath(pkg.codePath);
15906            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15907            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15908            pkg.setApplicationInfoResourcePath(pkg.codePath);
15909            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15910            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15911
15912            return true;
15913        }
15914
15915        int doPostInstall(int status, int uid) {
15916            if (status == PackageManager.INSTALL_SUCCEEDED) {
15917                cleanUp(move.fromUuid);
15918            } else {
15919                cleanUp(move.toUuid);
15920            }
15921            return status;
15922        }
15923
15924        @Override
15925        String getCodePath() {
15926            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15927        }
15928
15929        @Override
15930        String getResourcePath() {
15931            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15932        }
15933
15934        private boolean cleanUp(String volumeUuid) {
15935            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15936                    move.dataAppName);
15937            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15938            final int[] userIds = sUserManager.getUserIds();
15939            synchronized (mInstallLock) {
15940                // Clean up both app data and code
15941                // All package moves are frozen until finished
15942                for (int userId : userIds) {
15943                    try {
15944                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15945                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15946                    } catch (InstallerException e) {
15947                        Slog.w(TAG, String.valueOf(e));
15948                    }
15949                }
15950                removeCodePathLI(codeFile);
15951            }
15952            return true;
15953        }
15954
15955        void cleanUpResourcesLI() {
15956            throw new UnsupportedOperationException();
15957        }
15958
15959        boolean doPostDeleteLI(boolean delete) {
15960            throw new UnsupportedOperationException();
15961        }
15962    }
15963
15964    static String getAsecPackageName(String packageCid) {
15965        int idx = packageCid.lastIndexOf("-");
15966        if (idx == -1) {
15967            return packageCid;
15968        }
15969        return packageCid.substring(0, idx);
15970    }
15971
15972    // Utility method used to create code paths based on package name and available index.
15973    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15974        String idxStr = "";
15975        int idx = 1;
15976        // Fall back to default value of idx=1 if prefix is not
15977        // part of oldCodePath
15978        if (oldCodePath != null) {
15979            String subStr = oldCodePath;
15980            // Drop the suffix right away
15981            if (suffix != null && subStr.endsWith(suffix)) {
15982                subStr = subStr.substring(0, subStr.length() - suffix.length());
15983            }
15984            // If oldCodePath already contains prefix find out the
15985            // ending index to either increment or decrement.
15986            int sidx = subStr.lastIndexOf(prefix);
15987            if (sidx != -1) {
15988                subStr = subStr.substring(sidx + prefix.length());
15989                if (subStr != null) {
15990                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15991                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15992                    }
15993                    try {
15994                        idx = Integer.parseInt(subStr);
15995                        if (idx <= 1) {
15996                            idx++;
15997                        } else {
15998                            idx--;
15999                        }
16000                    } catch(NumberFormatException e) {
16001                    }
16002                }
16003            }
16004        }
16005        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16006        return prefix + idxStr;
16007    }
16008
16009    private File getNextCodePath(File targetDir, String packageName) {
16010        File result;
16011        SecureRandom random = new SecureRandom();
16012        byte[] bytes = new byte[16];
16013        do {
16014            random.nextBytes(bytes);
16015            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16016            result = new File(targetDir, packageName + "-" + suffix);
16017        } while (result.exists());
16018        return result;
16019    }
16020
16021    // Utility method that returns the relative package path with respect
16022    // to the installation directory. Like say for /data/data/com.test-1.apk
16023    // string com.test-1 is returned.
16024    static String deriveCodePathName(String codePath) {
16025        if (codePath == null) {
16026            return null;
16027        }
16028        final File codeFile = new File(codePath);
16029        final String name = codeFile.getName();
16030        if (codeFile.isDirectory()) {
16031            return name;
16032        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16033            final int lastDot = name.lastIndexOf('.');
16034            return name.substring(0, lastDot);
16035        } else {
16036            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16037            return null;
16038        }
16039    }
16040
16041    static class PackageInstalledInfo {
16042        String name;
16043        int uid;
16044        // The set of users that originally had this package installed.
16045        int[] origUsers;
16046        // The set of users that now have this package installed.
16047        int[] newUsers;
16048        PackageParser.Package pkg;
16049        int returnCode;
16050        String returnMsg;
16051        String installerPackageName;
16052        PackageRemovedInfo removedInfo;
16053        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16054
16055        public void setError(int code, String msg) {
16056            setReturnCode(code);
16057            setReturnMessage(msg);
16058            Slog.w(TAG, msg);
16059        }
16060
16061        public void setError(String msg, PackageParserException e) {
16062            setReturnCode(e.error);
16063            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16064            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16065            for (int i = 0; i < childCount; i++) {
16066                addedChildPackages.valueAt(i).setError(msg, e);
16067            }
16068            Slog.w(TAG, msg, e);
16069        }
16070
16071        public void setError(String msg, PackageManagerException e) {
16072            returnCode = e.error;
16073            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16074            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16075            for (int i = 0; i < childCount; i++) {
16076                addedChildPackages.valueAt(i).setError(msg, e);
16077            }
16078            Slog.w(TAG, msg, e);
16079        }
16080
16081        public void setReturnCode(int returnCode) {
16082            this.returnCode = returnCode;
16083            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16084            for (int i = 0; i < childCount; i++) {
16085                addedChildPackages.valueAt(i).returnCode = returnCode;
16086            }
16087        }
16088
16089        private void setReturnMessage(String returnMsg) {
16090            this.returnMsg = returnMsg;
16091            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16092            for (int i = 0; i < childCount; i++) {
16093                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16094            }
16095        }
16096
16097        // In some error cases we want to convey more info back to the observer
16098        String origPackage;
16099        String origPermission;
16100    }
16101
16102    /*
16103     * Install a non-existing package.
16104     */
16105    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16106            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16107            String volumeUuid, PackageInstalledInfo res, int installReason) {
16108        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16109
16110        // Remember this for later, in case we need to rollback this install
16111        String pkgName = pkg.packageName;
16112
16113        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16114
16115        synchronized(mPackages) {
16116            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16117            if (renamedPackage != null) {
16118                // A package with the same name is already installed, though
16119                // it has been renamed to an older name.  The package we
16120                // are trying to install should be installed as an update to
16121                // the existing one, but that has not been requested, so bail.
16122                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16123                        + " without first uninstalling package running as "
16124                        + renamedPackage);
16125                return;
16126            }
16127            if (mPackages.containsKey(pkgName)) {
16128                // Don't allow installation over an existing package with the same name.
16129                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16130                        + " without first uninstalling.");
16131                return;
16132            }
16133        }
16134
16135        try {
16136            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16137                    System.currentTimeMillis(), user);
16138
16139            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16140
16141            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16142                prepareAppDataAfterInstallLIF(newPackage);
16143
16144            } else {
16145                // Remove package from internal structures, but keep around any
16146                // data that might have already existed
16147                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16148                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16149            }
16150        } catch (PackageManagerException e) {
16151            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16152        }
16153
16154        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16155    }
16156
16157    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16158        try (DigestInputStream digestStream =
16159                new DigestInputStream(new FileInputStream(file), digest)) {
16160            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16161        }
16162    }
16163
16164    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16165            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16166            PackageInstalledInfo res, int installReason) {
16167        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16168
16169        final PackageParser.Package oldPackage;
16170        final PackageSetting ps;
16171        final String pkgName = pkg.packageName;
16172        final int[] allUsers;
16173        final int[] installedUsers;
16174
16175        synchronized(mPackages) {
16176            oldPackage = mPackages.get(pkgName);
16177            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16178
16179            // don't allow upgrade to target a release SDK from a pre-release SDK
16180            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16181                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16182            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16183                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16184            if (oldTargetsPreRelease
16185                    && !newTargetsPreRelease
16186                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16187                Slog.w(TAG, "Can't install package targeting released sdk");
16188                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16189                return;
16190            }
16191
16192            ps = mSettings.mPackages.get(pkgName);
16193
16194            // verify signatures are valid
16195            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16196            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16197                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16198                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16199                            "New package not signed by keys specified by upgrade-keysets: "
16200                                    + pkgName);
16201                    return;
16202                }
16203            } else {
16204
16205                // default to original signature matching
16206                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16207                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16208                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16209                            "New package has a different signature: " + pkgName);
16210                    return;
16211                }
16212            }
16213
16214            // don't allow a system upgrade unless the upgrade hash matches
16215            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16216                byte[] digestBytes = null;
16217                try {
16218                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16219                    updateDigest(digest, new File(pkg.baseCodePath));
16220                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16221                        for (String path : pkg.splitCodePaths) {
16222                            updateDigest(digest, new File(path));
16223                        }
16224                    }
16225                    digestBytes = digest.digest();
16226                } catch (NoSuchAlgorithmException | IOException e) {
16227                    res.setError(INSTALL_FAILED_INVALID_APK,
16228                            "Could not compute hash: " + pkgName);
16229                    return;
16230                }
16231                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16232                    res.setError(INSTALL_FAILED_INVALID_APK,
16233                            "New package fails restrict-update check: " + pkgName);
16234                    return;
16235                }
16236                // retain upgrade restriction
16237                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16238            }
16239
16240            // Check for shared user id changes
16241            String invalidPackageName =
16242                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16243            if (invalidPackageName != null) {
16244                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16245                        "Package " + invalidPackageName + " tried to change user "
16246                                + oldPackage.mSharedUserId);
16247                return;
16248            }
16249
16250            // check if the new package supports all of the abis which the old package supports
16251            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16252            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16253            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16254                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16255                        "Update to package " + pkgName + " doesn't support multi arch");
16256                return;
16257            }
16258
16259            // In case of rollback, remember per-user/profile install state
16260            allUsers = sUserManager.getUserIds();
16261            installedUsers = ps.queryInstalledUsers(allUsers, true);
16262
16263            // don't allow an upgrade from full to ephemeral
16264            if (isInstantApp) {
16265                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16266                    for (int currentUser : allUsers) {
16267                        if (!ps.getInstantApp(currentUser)) {
16268                            // can't downgrade from full to instant
16269                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16270                                    + " for user: " + currentUser);
16271                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16272                            return;
16273                        }
16274                    }
16275                } else if (!ps.getInstantApp(user.getIdentifier())) {
16276                    // can't downgrade from full to instant
16277                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16278                            + " for user: " + user.getIdentifier());
16279                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16280                    return;
16281                }
16282            }
16283        }
16284
16285        // Update what is removed
16286        res.removedInfo = new PackageRemovedInfo(this);
16287        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16288        res.removedInfo.removedPackage = oldPackage.packageName;
16289        res.removedInfo.installerPackageName = ps.installerPackageName;
16290        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16291        res.removedInfo.isUpdate = true;
16292        res.removedInfo.origUsers = installedUsers;
16293        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16294        for (int i = 0; i < installedUsers.length; i++) {
16295            final int userId = installedUsers[i];
16296            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16297        }
16298
16299        final int childCount = (oldPackage.childPackages != null)
16300                ? oldPackage.childPackages.size() : 0;
16301        for (int i = 0; i < childCount; i++) {
16302            boolean childPackageUpdated = false;
16303            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16304            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16305            if (res.addedChildPackages != null) {
16306                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16307                if (childRes != null) {
16308                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16309                    childRes.removedInfo.removedPackage = childPkg.packageName;
16310                    if (childPs != null) {
16311                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16312                    }
16313                    childRes.removedInfo.isUpdate = true;
16314                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16315                    childPackageUpdated = true;
16316                }
16317            }
16318            if (!childPackageUpdated) {
16319                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16320                childRemovedRes.removedPackage = childPkg.packageName;
16321                if (childPs != null) {
16322                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16323                }
16324                childRemovedRes.isUpdate = false;
16325                childRemovedRes.dataRemoved = true;
16326                synchronized (mPackages) {
16327                    if (childPs != null) {
16328                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16329                    }
16330                }
16331                if (res.removedInfo.removedChildPackages == null) {
16332                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16333                }
16334                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16335            }
16336        }
16337
16338        boolean sysPkg = (isSystemApp(oldPackage));
16339        if (sysPkg) {
16340            // Set the system/privileged/oem/vendor/product flags as needed
16341            final boolean privileged =
16342                    (oldPackage.applicationInfo.privateFlags
16343                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16344            final boolean oem =
16345                    (oldPackage.applicationInfo.privateFlags
16346                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16347            final boolean vendor =
16348                    (oldPackage.applicationInfo.privateFlags
16349                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16350            final boolean product =
16351                    (oldPackage.applicationInfo.privateFlags
16352                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16353            final @ParseFlags int systemParseFlags = parseFlags;
16354            final @ScanFlags int systemScanFlags = scanFlags
16355                    | SCAN_AS_SYSTEM
16356                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16357                    | (oem ? SCAN_AS_OEM : 0)
16358                    | (vendor ? SCAN_AS_VENDOR : 0)
16359                    | (product ? SCAN_AS_PRODUCT : 0);
16360
16361            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16362                    user, allUsers, installerPackageName, res, installReason);
16363        } else {
16364            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16365                    user, allUsers, installerPackageName, res, installReason);
16366        }
16367    }
16368
16369    @Override
16370    public List<String> getPreviousCodePaths(String packageName) {
16371        final int callingUid = Binder.getCallingUid();
16372        final List<String> result = new ArrayList<>();
16373        if (getInstantAppPackageName(callingUid) != null) {
16374            return result;
16375        }
16376        final PackageSetting ps = mSettings.mPackages.get(packageName);
16377        if (ps != null
16378                && ps.oldCodePaths != null
16379                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16380            result.addAll(ps.oldCodePaths);
16381        }
16382        return result;
16383    }
16384
16385    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16386            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16387            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16388            String installerPackageName, PackageInstalledInfo res, int installReason) {
16389        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16390                + deletedPackage);
16391
16392        String pkgName = deletedPackage.packageName;
16393        boolean deletedPkg = true;
16394        boolean addedPkg = false;
16395        boolean updatedSettings = false;
16396        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16397        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16398                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16399
16400        final long origUpdateTime = (pkg.mExtras != null)
16401                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16402
16403        // First delete the existing package while retaining the data directory
16404        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16405                res.removedInfo, true, pkg)) {
16406            // If the existing package wasn't successfully deleted
16407            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16408            deletedPkg = false;
16409        } else {
16410            // Successfully deleted the old package; proceed with replace.
16411
16412            // If deleted package lived in a container, give users a chance to
16413            // relinquish resources before killing.
16414            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16415                if (DEBUG_INSTALL) {
16416                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16417                }
16418                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16419                final ArrayList<String> pkgList = new ArrayList<String>(1);
16420                pkgList.add(deletedPackage.applicationInfo.packageName);
16421                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16422            }
16423
16424            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16425                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16426
16427            try {
16428                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16429                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16430                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16431                        installReason);
16432
16433                // Update the in-memory copy of the previous code paths.
16434                PackageSetting ps = mSettings.mPackages.get(pkgName);
16435                if (!killApp) {
16436                    if (ps.oldCodePaths == null) {
16437                        ps.oldCodePaths = new ArraySet<>();
16438                    }
16439                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16440                    if (deletedPackage.splitCodePaths != null) {
16441                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16442                    }
16443                } else {
16444                    ps.oldCodePaths = null;
16445                }
16446                if (ps.childPackageNames != null) {
16447                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16448                        final String childPkgName = ps.childPackageNames.get(i);
16449                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16450                        childPs.oldCodePaths = ps.oldCodePaths;
16451                    }
16452                }
16453                // set instant app status, but, only if it's explicitly specified
16454                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16455                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16456                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16457                prepareAppDataAfterInstallLIF(newPackage);
16458                addedPkg = true;
16459                mDexManager.notifyPackageUpdated(newPackage.packageName,
16460                        newPackage.baseCodePath, newPackage.splitCodePaths);
16461            } catch (PackageManagerException e) {
16462                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16463            }
16464        }
16465
16466        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16467            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16468
16469            // Revert all internal state mutations and added folders for the failed install
16470            if (addedPkg) {
16471                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16472                        res.removedInfo, true, null);
16473            }
16474
16475            // Restore the old package
16476            if (deletedPkg) {
16477                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16478                File restoreFile = new File(deletedPackage.codePath);
16479                // Parse old package
16480                boolean oldExternal = isExternal(deletedPackage);
16481                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16482                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16483                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16484                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16485                try {
16486                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16487                            null);
16488                } catch (PackageManagerException e) {
16489                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16490                            + e.getMessage());
16491                    return;
16492                }
16493
16494                synchronized (mPackages) {
16495                    // Ensure the installer package name up to date
16496                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16497
16498                    // Update permissions for restored package
16499                    mPermissionManager.updatePermissions(
16500                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16501                            mPermissionCallback);
16502
16503                    mSettings.writeLPr();
16504                }
16505
16506                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16507            }
16508        } else {
16509            synchronized (mPackages) {
16510                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16511                if (ps != null) {
16512                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16513                    if (res.removedInfo.removedChildPackages != null) {
16514                        final int childCount = res.removedInfo.removedChildPackages.size();
16515                        // Iterate in reverse as we may modify the collection
16516                        for (int i = childCount - 1; i >= 0; i--) {
16517                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16518                            if (res.addedChildPackages.containsKey(childPackageName)) {
16519                                res.removedInfo.removedChildPackages.removeAt(i);
16520                            } else {
16521                                PackageRemovedInfo childInfo = res.removedInfo
16522                                        .removedChildPackages.valueAt(i);
16523                                childInfo.removedForAllUsers = mPackages.get(
16524                                        childInfo.removedPackage) == null;
16525                            }
16526                        }
16527                    }
16528                }
16529            }
16530        }
16531    }
16532
16533    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16534            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16535            final @ScanFlags int scanFlags, UserHandle user,
16536            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16537            int installReason) {
16538        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16539                + ", old=" + deletedPackage);
16540
16541        final boolean disabledSystem;
16542
16543        // Remove existing system package
16544        removePackageLI(deletedPackage, true);
16545
16546        synchronized (mPackages) {
16547            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16548        }
16549        if (!disabledSystem) {
16550            // We didn't need to disable the .apk as a current system package,
16551            // which means we are replacing another update that is already
16552            // installed.  We need to make sure to delete the older one's .apk.
16553            res.removedInfo.args = createInstallArgsForExisting(0,
16554                    deletedPackage.applicationInfo.getCodePath(),
16555                    deletedPackage.applicationInfo.getResourcePath(),
16556                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16557        } else {
16558            res.removedInfo.args = null;
16559        }
16560
16561        // Successfully disabled the old package. Now proceed with re-installation
16562        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16563                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16564
16565        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16566        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16567                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16568
16569        PackageParser.Package newPackage = null;
16570        try {
16571            // Add the package to the internal data structures
16572            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16573
16574            // Set the update and install times
16575            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16576            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16577                    System.currentTimeMillis());
16578
16579            // Update the package dynamic state if succeeded
16580            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16581                // Now that the install succeeded make sure we remove data
16582                // directories for any child package the update removed.
16583                final int deletedChildCount = (deletedPackage.childPackages != null)
16584                        ? deletedPackage.childPackages.size() : 0;
16585                final int newChildCount = (newPackage.childPackages != null)
16586                        ? newPackage.childPackages.size() : 0;
16587                for (int i = 0; i < deletedChildCount; i++) {
16588                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16589                    boolean childPackageDeleted = true;
16590                    for (int j = 0; j < newChildCount; j++) {
16591                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16592                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16593                            childPackageDeleted = false;
16594                            break;
16595                        }
16596                    }
16597                    if (childPackageDeleted) {
16598                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16599                                deletedChildPkg.packageName);
16600                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16601                            PackageRemovedInfo removedChildRes = res.removedInfo
16602                                    .removedChildPackages.get(deletedChildPkg.packageName);
16603                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16604                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16605                        }
16606                    }
16607                }
16608
16609                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16610                        installReason);
16611                prepareAppDataAfterInstallLIF(newPackage);
16612
16613                mDexManager.notifyPackageUpdated(newPackage.packageName,
16614                            newPackage.baseCodePath, newPackage.splitCodePaths);
16615            }
16616        } catch (PackageManagerException e) {
16617            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16618            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16619        }
16620
16621        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16622            // Re installation failed. Restore old information
16623            // Remove new pkg information
16624            if (newPackage != null) {
16625                removeInstalledPackageLI(newPackage, true);
16626            }
16627            // Add back the old system package
16628            try {
16629                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16630            } catch (PackageManagerException e) {
16631                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16632            }
16633
16634            synchronized (mPackages) {
16635                if (disabledSystem) {
16636                    enableSystemPackageLPw(deletedPackage);
16637                }
16638
16639                // Ensure the installer package name up to date
16640                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16641
16642                // Update permissions for restored package
16643                mPermissionManager.updatePermissions(
16644                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16645                        mPermissionCallback);
16646
16647                mSettings.writeLPr();
16648            }
16649
16650            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16651                    + " after failed upgrade");
16652        }
16653    }
16654
16655    /**
16656     * Checks whether the parent or any of the child packages have a change shared
16657     * user. For a package to be a valid update the shred users of the parent and
16658     * the children should match. We may later support changing child shared users.
16659     * @param oldPkg The updated package.
16660     * @param newPkg The update package.
16661     * @return The shared user that change between the versions.
16662     */
16663    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16664            PackageParser.Package newPkg) {
16665        // Check parent shared user
16666        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16667            return newPkg.packageName;
16668        }
16669        // Check child shared users
16670        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16671        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16672        for (int i = 0; i < newChildCount; i++) {
16673            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16674            // If this child was present, did it have the same shared user?
16675            for (int j = 0; j < oldChildCount; j++) {
16676                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16677                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16678                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16679                    return newChildPkg.packageName;
16680                }
16681            }
16682        }
16683        return null;
16684    }
16685
16686    private void removeNativeBinariesLI(PackageSetting ps) {
16687        // Remove the lib path for the parent package
16688        if (ps != null) {
16689            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16690            // Remove the lib path for the child packages
16691            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16692            for (int i = 0; i < childCount; i++) {
16693                PackageSetting childPs = null;
16694                synchronized (mPackages) {
16695                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16696                }
16697                if (childPs != null) {
16698                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16699                            .legacyNativeLibraryPathString);
16700                }
16701            }
16702        }
16703    }
16704
16705    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16706        // Enable the parent package
16707        mSettings.enableSystemPackageLPw(pkg.packageName);
16708        // Enable the child packages
16709        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16710        for (int i = 0; i < childCount; i++) {
16711            PackageParser.Package childPkg = pkg.childPackages.get(i);
16712            mSettings.enableSystemPackageLPw(childPkg.packageName);
16713        }
16714    }
16715
16716    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16717            PackageParser.Package newPkg) {
16718        // Disable the parent package (parent always replaced)
16719        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16720        // Disable the child packages
16721        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16722        for (int i = 0; i < childCount; i++) {
16723            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16724            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16725            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16726        }
16727        return disabled;
16728    }
16729
16730    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16731            String installerPackageName) {
16732        // Enable the parent package
16733        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16734        // Enable the child packages
16735        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16736        for (int i = 0; i < childCount; i++) {
16737            PackageParser.Package childPkg = pkg.childPackages.get(i);
16738            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16739        }
16740    }
16741
16742    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16743            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16744        // Update the parent package setting
16745        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16746                res, user, installReason);
16747        // Update the child packages setting
16748        final int childCount = (newPackage.childPackages != null)
16749                ? newPackage.childPackages.size() : 0;
16750        for (int i = 0; i < childCount; i++) {
16751            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16752            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16753            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16754                    childRes.origUsers, childRes, user, installReason);
16755        }
16756    }
16757
16758    private void updateSettingsInternalLI(PackageParser.Package pkg,
16759            String installerPackageName, int[] allUsers, int[] installedForUsers,
16760            PackageInstalledInfo res, UserHandle user, int installReason) {
16761        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16762
16763        final String pkgName = pkg.packageName;
16764
16765        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16766        synchronized (mPackages) {
16767// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16768            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16769                    mPermissionCallback);
16770            // For system-bundled packages, we assume that installing an upgraded version
16771            // of the package implies that the user actually wants to run that new code,
16772            // so we enable the package.
16773            PackageSetting ps = mSettings.mPackages.get(pkgName);
16774            final int userId = user.getIdentifier();
16775            if (ps != null) {
16776                if (isSystemApp(pkg)) {
16777                    if (DEBUG_INSTALL) {
16778                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16779                    }
16780                    // Enable system package for requested users
16781                    if (res.origUsers != null) {
16782                        for (int origUserId : res.origUsers) {
16783                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16784                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16785                                        origUserId, installerPackageName);
16786                            }
16787                        }
16788                    }
16789                    // Also convey the prior install/uninstall state
16790                    if (allUsers != null && installedForUsers != null) {
16791                        for (int currentUserId : allUsers) {
16792                            final boolean installed = ArrayUtils.contains(
16793                                    installedForUsers, currentUserId);
16794                            if (DEBUG_INSTALL) {
16795                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16796                            }
16797                            ps.setInstalled(installed, currentUserId);
16798                        }
16799                        // these install state changes will be persisted in the
16800                        // upcoming call to mSettings.writeLPr().
16801                    }
16802                }
16803                // It's implied that when a user requests installation, they want the app to be
16804                // installed and enabled.
16805                if (userId != UserHandle.USER_ALL) {
16806                    ps.setInstalled(true, userId);
16807                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16808                } else {
16809                    for (int currentUserId : sUserManager.getUserIds()) {
16810                        ps.setInstalled(true, currentUserId);
16811                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16812                                installerPackageName);
16813                    }
16814                }
16815
16816                // When replacing an existing package, preserve the original install reason for all
16817                // users that had the package installed before.
16818                final Set<Integer> previousUserIds = new ArraySet<>();
16819                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16820                    final int installReasonCount = res.removedInfo.installReasons.size();
16821                    for (int i = 0; i < installReasonCount; i++) {
16822                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16823                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16824                        ps.setInstallReason(previousInstallReason, previousUserId);
16825                        previousUserIds.add(previousUserId);
16826                    }
16827                }
16828
16829                // Set install reason for users that are having the package newly installed.
16830                if (userId == UserHandle.USER_ALL) {
16831                    for (int currentUserId : sUserManager.getUserIds()) {
16832                        if (!previousUserIds.contains(currentUserId)) {
16833                            ps.setInstallReason(installReason, currentUserId);
16834                        }
16835                    }
16836                } else if (!previousUserIds.contains(userId)) {
16837                    ps.setInstallReason(installReason, userId);
16838                }
16839                mSettings.writeKernelMappingLPr(ps);
16840            }
16841            res.name = pkgName;
16842            res.uid = pkg.applicationInfo.uid;
16843            res.pkg = pkg;
16844            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16845            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16846            //to update install status
16847            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16848            mSettings.writeLPr();
16849            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16850        }
16851
16852        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16853    }
16854
16855    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16856        try {
16857            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16858            installPackageLI(args, res);
16859        } finally {
16860            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16861        }
16862    }
16863
16864    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16865        final int installFlags = args.installFlags;
16866        final String installerPackageName = args.installerPackageName;
16867        final String volumeUuid = args.volumeUuid;
16868        final File tmpPackageFile = new File(args.getCodePath());
16869        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16870        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16871                || (args.volumeUuid != null));
16872        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16873        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16874        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16875        final boolean virtualPreload =
16876                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16877        boolean replace = false;
16878        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16879        if (args.move != null) {
16880            // moving a complete application; perform an initial scan on the new install location
16881            scanFlags |= SCAN_INITIAL;
16882        }
16883        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16884            scanFlags |= SCAN_DONT_KILL_APP;
16885        }
16886        if (instantApp) {
16887            scanFlags |= SCAN_AS_INSTANT_APP;
16888        }
16889        if (fullApp) {
16890            scanFlags |= SCAN_AS_FULL_APP;
16891        }
16892        if (virtualPreload) {
16893            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16894        }
16895
16896        // Result object to be returned
16897        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16898        res.installerPackageName = installerPackageName;
16899
16900        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16901
16902        // Sanity check
16903        if (instantApp && (forwardLocked || onExternal)) {
16904            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16905                    + " external=" + onExternal);
16906            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16907            return;
16908        }
16909
16910        // Retrieve PackageSettings and parse package
16911        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16912                | PackageParser.PARSE_ENFORCE_CODE
16913                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16914                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16915                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16916        PackageParser pp = new PackageParser();
16917        pp.setSeparateProcesses(mSeparateProcesses);
16918        pp.setDisplayMetrics(mMetrics);
16919        pp.setCallback(mPackageParserCallback);
16920
16921        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16922        final PackageParser.Package pkg;
16923        try {
16924            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16925            DexMetadataHelper.validatePackageDexMetadata(pkg);
16926        } catch (PackageParserException e) {
16927            res.setError("Failed parse during installPackageLI", e);
16928            return;
16929        } finally {
16930            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16931        }
16932
16933        // Instant apps have several additional install-time checks.
16934        if (instantApp) {
16935            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16936                Slog.w(TAG,
16937                        "Instant app package " + pkg.packageName + " does not target at least O");
16938                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16939                        "Instant app package must target at least O");
16940                return;
16941            }
16942            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16943                Slog.w(TAG, "Instant app package " + pkg.packageName
16944                        + " does not target targetSandboxVersion 2");
16945                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16946                        "Instant app package must use targetSandboxVersion 2");
16947                return;
16948            }
16949            if (pkg.mSharedUserId != null) {
16950                Slog.w(TAG, "Instant app package " + pkg.packageName
16951                        + " may not declare sharedUserId.");
16952                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16953                        "Instant app package may not declare a sharedUserId");
16954                return;
16955            }
16956        }
16957
16958        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16959            // Static shared libraries have synthetic package names
16960            renameStaticSharedLibraryPackage(pkg);
16961
16962            // No static shared libs on external storage
16963            if (onExternal) {
16964                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16965                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16966                        "Packages declaring static-shared libs cannot be updated");
16967                return;
16968            }
16969        }
16970
16971        // If we are installing a clustered package add results for the children
16972        if (pkg.childPackages != null) {
16973            synchronized (mPackages) {
16974                final int childCount = pkg.childPackages.size();
16975                for (int i = 0; i < childCount; i++) {
16976                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16977                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16978                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16979                    childRes.pkg = childPkg;
16980                    childRes.name = childPkg.packageName;
16981                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16982                    if (childPs != null) {
16983                        childRes.origUsers = childPs.queryInstalledUsers(
16984                                sUserManager.getUserIds(), true);
16985                    }
16986                    if ((mPackages.containsKey(childPkg.packageName))) {
16987                        childRes.removedInfo = new PackageRemovedInfo(this);
16988                        childRes.removedInfo.removedPackage = childPkg.packageName;
16989                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16990                    }
16991                    if (res.addedChildPackages == null) {
16992                        res.addedChildPackages = new ArrayMap<>();
16993                    }
16994                    res.addedChildPackages.put(childPkg.packageName, childRes);
16995                }
16996            }
16997        }
16998
16999        // If package doesn't declare API override, mark that we have an install
17000        // time CPU ABI override.
17001        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17002            pkg.cpuAbiOverride = args.abiOverride;
17003        }
17004
17005        String pkgName = res.name = pkg.packageName;
17006        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17007            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17008                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17009                return;
17010            }
17011        }
17012
17013        try {
17014            // either use what we've been given or parse directly from the APK
17015            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17016                pkg.setSigningDetails(args.signingDetails);
17017            } else {
17018                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17019            }
17020        } catch (PackageParserException e) {
17021            res.setError("Failed collect during installPackageLI", e);
17022            return;
17023        }
17024
17025        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17026                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17027            Slog.w(TAG, "Instant app package " + pkg.packageName
17028                    + " is not signed with at least APK Signature Scheme v2");
17029            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17030                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17031            return;
17032        }
17033
17034        // Get rid of all references to package scan path via parser.
17035        pp = null;
17036        String oldCodePath = null;
17037        boolean systemApp = false;
17038        synchronized (mPackages) {
17039            // Check if installing already existing package
17040            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17041                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17042                if (pkg.mOriginalPackages != null
17043                        && pkg.mOriginalPackages.contains(oldName)
17044                        && mPackages.containsKey(oldName)) {
17045                    // This package is derived from an original package,
17046                    // and this device has been updating from that original
17047                    // name.  We must continue using the original name, so
17048                    // rename the new package here.
17049                    pkg.setPackageName(oldName);
17050                    pkgName = pkg.packageName;
17051                    replace = true;
17052                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17053                            + oldName + " pkgName=" + pkgName);
17054                } else if (mPackages.containsKey(pkgName)) {
17055                    // This package, under its official name, already exists
17056                    // on the device; we should replace it.
17057                    replace = true;
17058                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17059                }
17060
17061                // Child packages are installed through the parent package
17062                if (pkg.parentPackage != null) {
17063                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17064                            "Package " + pkg.packageName + " is child of package "
17065                                    + pkg.parentPackage.parentPackage + ". Child packages "
17066                                    + "can be updated only through the parent package.");
17067                    return;
17068                }
17069
17070                if (replace) {
17071                    // Prevent apps opting out from runtime permissions
17072                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17073                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17074                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17075                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17076                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17077                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17078                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17079                                        + " doesn't support runtime permissions but the old"
17080                                        + " target SDK " + oldTargetSdk + " does.");
17081                        return;
17082                    }
17083                    // Prevent persistent apps from being updated
17084                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17085                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17086                                "Package " + oldPackage.packageName + " is a persistent app. "
17087                                        + "Persistent apps are not updateable.");
17088                        return;
17089                    }
17090                    // Prevent apps from downgrading their targetSandbox.
17091                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17092                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17093                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17094                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17095                                "Package " + pkg.packageName + " new target sandbox "
17096                                + newTargetSandbox + " is incompatible with the previous value of"
17097                                + oldTargetSandbox + ".");
17098                        return;
17099                    }
17100
17101                    // Prevent installing of child packages
17102                    if (oldPackage.parentPackage != null) {
17103                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17104                                "Package " + pkg.packageName + " is child of package "
17105                                        + oldPackage.parentPackage + ". Child packages "
17106                                        + "can be updated only through the parent package.");
17107                        return;
17108                    }
17109                }
17110            }
17111
17112            PackageSetting ps = mSettings.mPackages.get(pkgName);
17113            if (ps != null) {
17114                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17115
17116                // Static shared libs have same package with different versions where
17117                // we internally use a synthetic package name to allow multiple versions
17118                // of the same package, therefore we need to compare signatures against
17119                // the package setting for the latest library version.
17120                PackageSetting signatureCheckPs = ps;
17121                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17122                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17123                    if (libraryEntry != null) {
17124                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17125                    }
17126                }
17127
17128                // Quick sanity check that we're signed correctly if updating;
17129                // we'll check this again later when scanning, but we want to
17130                // bail early here before tripping over redefined permissions.
17131                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17132                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17133                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17134                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17135                                + pkg.packageName + " upgrade keys do not match the "
17136                                + "previously installed version");
17137                        return;
17138                    }
17139                } else {
17140                    try {
17141                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17142                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17143                        // We don't care about disabledPkgSetting on install for now.
17144                        final boolean compatMatch = verifySignatures(
17145                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17146                                compareRecover);
17147                        // The new KeySets will be re-added later in the scanning process.
17148                        if (compatMatch) {
17149                            synchronized (mPackages) {
17150                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17151                            }
17152                        }
17153                    } catch (PackageManagerException e) {
17154                        res.setError(e.error, e.getMessage());
17155                        return;
17156                    }
17157                }
17158
17159                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17160                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17161                    systemApp = (ps.pkg.applicationInfo.flags &
17162                            ApplicationInfo.FLAG_SYSTEM) != 0;
17163                }
17164                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17165            }
17166
17167            int N = pkg.permissions.size();
17168            for (int i = N-1; i >= 0; i--) {
17169                final PackageParser.Permission perm = pkg.permissions.get(i);
17170                final BasePermission bp =
17171                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17172
17173                // Don't allow anyone but the system to define ephemeral permissions.
17174                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17175                        && !systemApp) {
17176                    Slog.w(TAG, "Non-System package " + pkg.packageName
17177                            + " attempting to delcare ephemeral permission "
17178                            + perm.info.name + "; Removing ephemeral.");
17179                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17180                }
17181
17182                // Check whether the newly-scanned package wants to define an already-defined perm
17183                if (bp != null) {
17184                    // If the defining package is signed with our cert, it's okay.  This
17185                    // also includes the "updating the same package" case, of course.
17186                    // "updating same package" could also involve key-rotation.
17187                    final boolean sigsOk;
17188                    final String sourcePackageName = bp.getSourcePackageName();
17189                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17190                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17191                    if (sourcePackageName.equals(pkg.packageName)
17192                            && (ksms.shouldCheckUpgradeKeySetLocked(
17193                                    sourcePackageSetting, scanFlags))) {
17194                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17195                    } else {
17196
17197                        // in the event of signing certificate rotation, we need to see if the
17198                        // package's certificate has rotated from the current one, or if it is an
17199                        // older certificate with which the current is ok with sharing permissions
17200                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17201                                        pkg.mSigningDetails,
17202                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17203                            sigsOk = true;
17204                        } else if (pkg.mSigningDetails.checkCapability(
17205                                        sourcePackageSetting.signatures.mSigningDetails,
17206                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17207
17208                            // the scanned package checks out, has signing certificate rotation
17209                            // history, and is newer; bring it over
17210                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17211                            sigsOk = true;
17212                        } else {
17213                            sigsOk = false;
17214                        }
17215                    }
17216                    if (!sigsOk) {
17217                        // If the owning package is the system itself, we log but allow
17218                        // install to proceed; we fail the install on all other permission
17219                        // redefinitions.
17220                        if (!sourcePackageName.equals("android")) {
17221                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17222                                    + pkg.packageName + " attempting to redeclare permission "
17223                                    + perm.info.name + " already owned by " + sourcePackageName);
17224                            res.origPermission = perm.info.name;
17225                            res.origPackage = sourcePackageName;
17226                            return;
17227                        } else {
17228                            Slog.w(TAG, "Package " + pkg.packageName
17229                                    + " attempting to redeclare system permission "
17230                                    + perm.info.name + "; ignoring new declaration");
17231                            pkg.permissions.remove(i);
17232                        }
17233                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17234                        // Prevent apps to change protection level to dangerous from any other
17235                        // type as this would allow a privilege escalation where an app adds a
17236                        // normal/signature permission in other app's group and later redefines
17237                        // it as dangerous leading to the group auto-grant.
17238                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17239                                == PermissionInfo.PROTECTION_DANGEROUS) {
17240                            if (bp != null && !bp.isRuntime()) {
17241                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17242                                        + "non-runtime permission " + perm.info.name
17243                                        + " to runtime; keeping old protection level");
17244                                perm.info.protectionLevel = bp.getProtectionLevel();
17245                            }
17246                        }
17247                    }
17248                }
17249            }
17250        }
17251
17252        if (systemApp) {
17253            if (onExternal) {
17254                // Abort update; system app can't be replaced with app on sdcard
17255                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17256                        "Cannot install updates to system apps on sdcard");
17257                return;
17258            } else if (instantApp) {
17259                // Abort update; system app can't be replaced with an instant app
17260                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17261                        "Cannot update a system app with an instant app");
17262                return;
17263            }
17264        }
17265
17266        if (args.move != null) {
17267            // We did an in-place move, so dex is ready to roll
17268            scanFlags |= SCAN_NO_DEX;
17269            scanFlags |= SCAN_MOVE;
17270
17271            synchronized (mPackages) {
17272                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17273                if (ps == null) {
17274                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17275                            "Missing settings for moved package " + pkgName);
17276                }
17277
17278                // We moved the entire application as-is, so bring over the
17279                // previously derived ABI information.
17280                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17281                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17282            }
17283
17284        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17285            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17286            scanFlags |= SCAN_NO_DEX;
17287
17288            try {
17289                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17290                    args.abiOverride : pkg.cpuAbiOverride);
17291                final boolean extractNativeLibs = !pkg.isLibrary();
17292                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17293            } catch (PackageManagerException pme) {
17294                Slog.e(TAG, "Error deriving application ABI", pme);
17295                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17296                return;
17297            }
17298
17299            // Shared libraries for the package need to be updated.
17300            synchronized (mPackages) {
17301                try {
17302                    updateSharedLibrariesLPr(pkg, null);
17303                } catch (PackageManagerException e) {
17304                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17305                }
17306            }
17307        }
17308
17309        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17310            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17311            return;
17312        }
17313
17314        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17315            String apkPath = null;
17316            synchronized (mPackages) {
17317                // Note that if the attacker managed to skip verify setup, for example by tampering
17318                // with the package settings, upon reboot we will do full apk verification when
17319                // verity is not detected.
17320                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17321                if (ps != null && ps.isPrivileged()) {
17322                    apkPath = pkg.baseCodePath;
17323                }
17324            }
17325
17326            if (apkPath != null) {
17327                final VerityUtils.SetupResult result =
17328                        VerityUtils.generateApkVeritySetupData(apkPath);
17329                if (result.isOk()) {
17330                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17331                    FileDescriptor fd = result.getUnownedFileDescriptor();
17332                    try {
17333                        mInstaller.installApkVerity(apkPath, fd);
17334                    } catch (InstallerException e) {
17335                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17336                                "Failed to set up verity: " + e);
17337                        return;
17338                    } finally {
17339                        IoUtils.closeQuietly(fd);
17340                    }
17341                } else if (result.isFailed()) {
17342                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17343                    return;
17344                } else {
17345                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17346                    // reboot.
17347                }
17348            }
17349        }
17350
17351        if (!instantApp) {
17352            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17353        } else {
17354            if (DEBUG_DOMAIN_VERIFICATION) {
17355                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17356            }
17357        }
17358
17359        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17360                "installPackageLI")) {
17361            if (replace) {
17362                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17363                    // Static libs have a synthetic package name containing the version
17364                    // and cannot be updated as an update would get a new package name,
17365                    // unless this is the exact same version code which is useful for
17366                    // development.
17367                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17368                    if (existingPkg != null &&
17369                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17370                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17371                                + "static-shared libs cannot be updated");
17372                        return;
17373                    }
17374                }
17375                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17376                        installerPackageName, res, args.installReason);
17377            } else {
17378                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17379                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17380            }
17381        }
17382
17383        // Prepare the application profiles for the new code paths.
17384        // This needs to be done before invoking dexopt so that any install-time profile
17385        // can be used for optimizations.
17386        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17387
17388        // Check whether we need to dexopt the app.
17389        //
17390        // NOTE: it is IMPORTANT to call dexopt:
17391        //   - after doRename which will sync the package data from PackageParser.Package and its
17392        //     corresponding ApplicationInfo.
17393        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17394        //     uid of the application (pkg.applicationInfo.uid).
17395        //     This update happens in place!
17396        //
17397        // We only need to dexopt if the package meets ALL of the following conditions:
17398        //   1) it is not forward locked.
17399        //   2) it is not on on an external ASEC container.
17400        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17401        //
17402        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17403        // complete, so we skip this step during installation. Instead, we'll take extra time
17404        // the first time the instant app starts. It's preferred to do it this way to provide
17405        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17406        // middle of running an instant app. The default behaviour can be overridden
17407        // via gservices.
17408        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17409                && !forwardLocked
17410                && !pkg.applicationInfo.isExternalAsec()
17411                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17412                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17413
17414        if (performDexopt) {
17415            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17416            // Do not run PackageDexOptimizer through the local performDexOpt
17417            // method because `pkg` may not be in `mPackages` yet.
17418            //
17419            // Also, don't fail application installs if the dexopt step fails.
17420            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17421                    REASON_INSTALL,
17422                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17423                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17424            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17425                    null /* instructionSets */,
17426                    getOrCreateCompilerPackageStats(pkg),
17427                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17428                    dexoptOptions);
17429            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17430        }
17431
17432        // Notify BackgroundDexOptService that the package has been changed.
17433        // If this is an update of a package which used to fail to compile,
17434        // BackgroundDexOptService will remove it from its blacklist.
17435        // TODO: Layering violation
17436        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17437
17438        synchronized (mPackages) {
17439            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17440            if (ps != null) {
17441                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17442                ps.setUpdateAvailable(false /*updateAvailable*/);
17443            }
17444
17445            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17446            for (int i = 0; i < childCount; i++) {
17447                PackageParser.Package childPkg = pkg.childPackages.get(i);
17448                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17449                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17450                if (childPs != null) {
17451                    childRes.newUsers = childPs.queryInstalledUsers(
17452                            sUserManager.getUserIds(), true);
17453                }
17454            }
17455
17456            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17457                updateSequenceNumberLP(ps, res.newUsers);
17458                updateInstantAppInstallerLocked(pkgName);
17459            }
17460        }
17461    }
17462
17463    private void startIntentFilterVerifications(int userId, boolean replacing,
17464            PackageParser.Package pkg) {
17465        if (mIntentFilterVerifierComponent == null) {
17466            Slog.w(TAG, "No IntentFilter verification will not be done as "
17467                    + "there is no IntentFilterVerifier available!");
17468            return;
17469        }
17470
17471        final int verifierUid = getPackageUid(
17472                mIntentFilterVerifierComponent.getPackageName(),
17473                MATCH_DEBUG_TRIAGED_MISSING,
17474                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17475
17476        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17477        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17478        mHandler.sendMessage(msg);
17479
17480        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17481        for (int i = 0; i < childCount; i++) {
17482            PackageParser.Package childPkg = pkg.childPackages.get(i);
17483            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17484            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17485            mHandler.sendMessage(msg);
17486        }
17487    }
17488
17489    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17490            PackageParser.Package pkg) {
17491        int size = pkg.activities.size();
17492        if (size == 0) {
17493            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17494                    "No activity, so no need to verify any IntentFilter!");
17495            return;
17496        }
17497
17498        final boolean hasDomainURLs = hasDomainURLs(pkg);
17499        if (!hasDomainURLs) {
17500            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17501                    "No domain URLs, so no need to verify any IntentFilter!");
17502            return;
17503        }
17504
17505        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17506                + " if any IntentFilter from the " + size
17507                + " Activities needs verification ...");
17508
17509        int count = 0;
17510        final String packageName = pkg.packageName;
17511
17512        synchronized (mPackages) {
17513            // If this is a new install and we see that we've already run verification for this
17514            // package, we have nothing to do: it means the state was restored from backup.
17515            if (!replacing) {
17516                IntentFilterVerificationInfo ivi =
17517                        mSettings.getIntentFilterVerificationLPr(packageName);
17518                if (ivi != null) {
17519                    if (DEBUG_DOMAIN_VERIFICATION) {
17520                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17521                                + ivi.getStatusString());
17522                    }
17523                    return;
17524                }
17525            }
17526
17527            // If any filters need to be verified, then all need to be.
17528            boolean needToVerify = false;
17529            for (PackageParser.Activity a : pkg.activities) {
17530                for (ActivityIntentInfo filter : a.intents) {
17531                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17532                        if (DEBUG_DOMAIN_VERIFICATION) {
17533                            Slog.d(TAG,
17534                                    "Intent filter needs verification, so processing all filters");
17535                        }
17536                        needToVerify = true;
17537                        break;
17538                    }
17539                }
17540            }
17541
17542            if (needToVerify) {
17543                final int verificationId = mIntentFilterVerificationToken++;
17544                for (PackageParser.Activity a : pkg.activities) {
17545                    for (ActivityIntentInfo filter : a.intents) {
17546                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17547                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17548                                    "Verification needed for IntentFilter:" + filter.toString());
17549                            mIntentFilterVerifier.addOneIntentFilterVerification(
17550                                    verifierUid, userId, verificationId, filter, packageName);
17551                            count++;
17552                        }
17553                    }
17554                }
17555            }
17556        }
17557
17558        if (count > 0) {
17559            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17560                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17561                    +  " for userId:" + userId);
17562            mIntentFilterVerifier.startVerifications(userId);
17563        } else {
17564            if (DEBUG_DOMAIN_VERIFICATION) {
17565                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17566            }
17567        }
17568    }
17569
17570    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17571        final ComponentName cn  = filter.activity.getComponentName();
17572        final String packageName = cn.getPackageName();
17573
17574        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17575                packageName);
17576        if (ivi == null) {
17577            return true;
17578        }
17579        int status = ivi.getStatus();
17580        switch (status) {
17581            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17582            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17583                return true;
17584
17585            default:
17586                // Nothing to do
17587                return false;
17588        }
17589    }
17590
17591    private static boolean isMultiArch(ApplicationInfo info) {
17592        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17593    }
17594
17595    private static boolean isExternal(PackageParser.Package pkg) {
17596        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17597    }
17598
17599    private static boolean isExternal(PackageSetting ps) {
17600        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17601    }
17602
17603    private static boolean isSystemApp(PackageParser.Package pkg) {
17604        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17605    }
17606
17607    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17608        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17609    }
17610
17611    private static boolean isOemApp(PackageParser.Package pkg) {
17612        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17613    }
17614
17615    private static boolean isVendorApp(PackageParser.Package pkg) {
17616        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17617    }
17618
17619    private static boolean isProductApp(PackageParser.Package pkg) {
17620        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17621    }
17622
17623    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17624        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17625    }
17626
17627    private static boolean isSystemApp(PackageSetting ps) {
17628        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17629    }
17630
17631    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17632        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17633    }
17634
17635    private int packageFlagsToInstallFlags(PackageSetting ps) {
17636        int installFlags = 0;
17637        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17638            // This existing package was an external ASEC install when we have
17639            // the external flag without a UUID
17640            installFlags |= PackageManager.INSTALL_EXTERNAL;
17641        }
17642        if (ps.isForwardLocked()) {
17643            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17644        }
17645        return installFlags;
17646    }
17647
17648    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17649        if (isExternal(pkg)) {
17650            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17651                return mSettings.getExternalVersion();
17652            } else {
17653                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17654            }
17655        } else {
17656            return mSettings.getInternalVersion();
17657        }
17658    }
17659
17660    private void deleteTempPackageFiles() {
17661        final FilenameFilter filter = new FilenameFilter() {
17662            public boolean accept(File dir, String name) {
17663                return name.startsWith("vmdl") && name.endsWith(".tmp");
17664            }
17665        };
17666        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17667            file.delete();
17668        }
17669    }
17670
17671    @Override
17672    public void deletePackageAsUser(String packageName, int versionCode,
17673            IPackageDeleteObserver observer, int userId, int flags) {
17674        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17675                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17676    }
17677
17678    @Override
17679    public void deletePackageVersioned(VersionedPackage versionedPackage,
17680            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17681        final int callingUid = Binder.getCallingUid();
17682        mContext.enforceCallingOrSelfPermission(
17683                android.Manifest.permission.DELETE_PACKAGES, null);
17684        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17685        Preconditions.checkNotNull(versionedPackage);
17686        Preconditions.checkNotNull(observer);
17687        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17688                PackageManager.VERSION_CODE_HIGHEST,
17689                Long.MAX_VALUE, "versionCode must be >= -1");
17690
17691        final String packageName = versionedPackage.getPackageName();
17692        final long versionCode = versionedPackage.getLongVersionCode();
17693        final String internalPackageName;
17694        synchronized (mPackages) {
17695            // Normalize package name to handle renamed packages and static libs
17696            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17697        }
17698
17699        final int uid = Binder.getCallingUid();
17700        if (!isOrphaned(internalPackageName)
17701                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17702            try {
17703                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17704                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17705                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17706                observer.onUserActionRequired(intent);
17707            } catch (RemoteException re) {
17708            }
17709            return;
17710        }
17711        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17712        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17713        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17714            mContext.enforceCallingOrSelfPermission(
17715                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17716                    "deletePackage for user " + userId);
17717        }
17718
17719        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17720            try {
17721                observer.onPackageDeleted(packageName,
17722                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17723            } catch (RemoteException re) {
17724            }
17725            return;
17726        }
17727
17728        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17729            try {
17730                observer.onPackageDeleted(packageName,
17731                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17732            } catch (RemoteException re) {
17733            }
17734            return;
17735        }
17736
17737        if (DEBUG_REMOVE) {
17738            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17739                    + " deleteAllUsers: " + deleteAllUsers + " version="
17740                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17741                    ? "VERSION_CODE_HIGHEST" : versionCode));
17742        }
17743        // Queue up an async operation since the package deletion may take a little while.
17744        mHandler.post(new Runnable() {
17745            public void run() {
17746                mHandler.removeCallbacks(this);
17747                int returnCode;
17748                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17749                boolean doDeletePackage = true;
17750                if (ps != null) {
17751                    final boolean targetIsInstantApp =
17752                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17753                    doDeletePackage = !targetIsInstantApp
17754                            || canViewInstantApps;
17755                }
17756                if (doDeletePackage) {
17757                    if (!deleteAllUsers) {
17758                        returnCode = deletePackageX(internalPackageName, versionCode,
17759                                userId, deleteFlags);
17760                    } else {
17761                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17762                                internalPackageName, users);
17763                        // If nobody is blocking uninstall, proceed with delete for all users
17764                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17765                            returnCode = deletePackageX(internalPackageName, versionCode,
17766                                    userId, deleteFlags);
17767                        } else {
17768                            // Otherwise uninstall individually for users with blockUninstalls=false
17769                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17770                            for (int userId : users) {
17771                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17772                                    returnCode = deletePackageX(internalPackageName, versionCode,
17773                                            userId, userFlags);
17774                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17775                                        Slog.w(TAG, "Package delete failed for user " + userId
17776                                                + ", returnCode " + returnCode);
17777                                    }
17778                                }
17779                            }
17780                            // The app has only been marked uninstalled for certain users.
17781                            // We still need to report that delete was blocked
17782                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17783                        }
17784                    }
17785                } else {
17786                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17787                }
17788                try {
17789                    observer.onPackageDeleted(packageName, returnCode, null);
17790                } catch (RemoteException e) {
17791                    Log.i(TAG, "Observer no longer exists.");
17792                } //end catch
17793            } //end run
17794        });
17795    }
17796
17797    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17798        if (pkg.staticSharedLibName != null) {
17799            return pkg.manifestPackageName;
17800        }
17801        return pkg.packageName;
17802    }
17803
17804    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17805        // Handle renamed packages
17806        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17807        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17808
17809        // Is this a static library?
17810        LongSparseArray<SharedLibraryEntry> versionedLib =
17811                mStaticLibsByDeclaringPackage.get(packageName);
17812        if (versionedLib == null || versionedLib.size() <= 0) {
17813            return packageName;
17814        }
17815
17816        // Figure out which lib versions the caller can see
17817        LongSparseLongArray versionsCallerCanSee = null;
17818        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17819        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17820                && callingAppId != Process.ROOT_UID) {
17821            versionsCallerCanSee = new LongSparseLongArray();
17822            String libName = versionedLib.valueAt(0).info.getName();
17823            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17824            if (uidPackages != null) {
17825                for (String uidPackage : uidPackages) {
17826                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17827                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17828                    if (libIdx >= 0) {
17829                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17830                        versionsCallerCanSee.append(libVersion, libVersion);
17831                    }
17832                }
17833            }
17834        }
17835
17836        // Caller can see nothing - done
17837        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17838            return packageName;
17839        }
17840
17841        // Find the version the caller can see and the app version code
17842        SharedLibraryEntry highestVersion = null;
17843        final int versionCount = versionedLib.size();
17844        for (int i = 0; i < versionCount; i++) {
17845            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17846            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17847                    libEntry.info.getLongVersion()) < 0) {
17848                continue;
17849            }
17850            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17851            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17852                if (libVersionCode == versionCode) {
17853                    return libEntry.apk;
17854                }
17855            } else if (highestVersion == null) {
17856                highestVersion = libEntry;
17857            } else if (libVersionCode  > highestVersion.info
17858                    .getDeclaringPackage().getLongVersionCode()) {
17859                highestVersion = libEntry;
17860            }
17861        }
17862
17863        if (highestVersion != null) {
17864            return highestVersion.apk;
17865        }
17866
17867        return packageName;
17868    }
17869
17870    boolean isCallerVerifier(int callingUid) {
17871        final int callingUserId = UserHandle.getUserId(callingUid);
17872        return mRequiredVerifierPackage != null &&
17873                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17874    }
17875
17876    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17877        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17878              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17879            return true;
17880        }
17881        final int callingUserId = UserHandle.getUserId(callingUid);
17882        // If the caller installed the pkgName, then allow it to silently uninstall.
17883        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17884            return true;
17885        }
17886
17887        // Allow package verifier to silently uninstall.
17888        if (mRequiredVerifierPackage != null &&
17889                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17890            return true;
17891        }
17892
17893        // Allow package uninstaller to silently uninstall.
17894        if (mRequiredUninstallerPackage != null &&
17895                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17896            return true;
17897        }
17898
17899        // Allow storage manager to silently uninstall.
17900        if (mStorageManagerPackage != null &&
17901                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17902            return true;
17903        }
17904
17905        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17906        // uninstall for device owner provisioning.
17907        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17908                == PERMISSION_GRANTED) {
17909            return true;
17910        }
17911
17912        return false;
17913    }
17914
17915    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17916        int[] result = EMPTY_INT_ARRAY;
17917        for (int userId : userIds) {
17918            if (getBlockUninstallForUser(packageName, userId)) {
17919                result = ArrayUtils.appendInt(result, userId);
17920            }
17921        }
17922        return result;
17923    }
17924
17925    @Override
17926    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17927        final int callingUid = Binder.getCallingUid();
17928        if (getInstantAppPackageName(callingUid) != null
17929                && !isCallerSameApp(packageName, callingUid)) {
17930            return false;
17931        }
17932        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17933    }
17934
17935    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17936        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17937                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17938        try {
17939            if (dpm != null) {
17940                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17941                        /* callingUserOnly =*/ false);
17942                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17943                        : deviceOwnerComponentName.getPackageName();
17944                // Does the package contains the device owner?
17945                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17946                // this check is probably not needed, since DO should be registered as a device
17947                // admin on some user too. (Original bug for this: b/17657954)
17948                if (packageName.equals(deviceOwnerPackageName)) {
17949                    return true;
17950                }
17951                // Does it contain a device admin for any user?
17952                int[] users;
17953                if (userId == UserHandle.USER_ALL) {
17954                    users = sUserManager.getUserIds();
17955                } else {
17956                    users = new int[]{userId};
17957                }
17958                for (int i = 0; i < users.length; ++i) {
17959                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17960                        return true;
17961                    }
17962                }
17963            }
17964        } catch (RemoteException e) {
17965        }
17966        return false;
17967    }
17968
17969    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17970        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17971    }
17972
17973    /**
17974     *  This method is an internal method that could be get invoked either
17975     *  to delete an installed package or to clean up a failed installation.
17976     *  After deleting an installed package, a broadcast is sent to notify any
17977     *  listeners that the package has been removed. For cleaning up a failed
17978     *  installation, the broadcast is not necessary since the package's
17979     *  installation wouldn't have sent the initial broadcast either
17980     *  The key steps in deleting a package are
17981     *  deleting the package information in internal structures like mPackages,
17982     *  deleting the packages base directories through installd
17983     *  updating mSettings to reflect current status
17984     *  persisting settings for later use
17985     *  sending a broadcast if necessary
17986     */
17987    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17988        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17989        final boolean res;
17990
17991        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17992                ? UserHandle.USER_ALL : userId;
17993
17994        if (isPackageDeviceAdmin(packageName, removeUser)) {
17995            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17996            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17997        }
17998
17999        PackageSetting uninstalledPs = null;
18000        PackageParser.Package pkg = null;
18001
18002        // for the uninstall-updates case and restricted profiles, remember the per-
18003        // user handle installed state
18004        int[] allUsers;
18005        synchronized (mPackages) {
18006            uninstalledPs = mSettings.mPackages.get(packageName);
18007            if (uninstalledPs == null) {
18008                Slog.w(TAG, "Not removing non-existent package " + packageName);
18009                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18010            }
18011
18012            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18013                    && uninstalledPs.versionCode != versionCode) {
18014                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18015                        + uninstalledPs.versionCode + " != " + versionCode);
18016                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18017            }
18018
18019            // Static shared libs can be declared by any package, so let us not
18020            // allow removing a package if it provides a lib others depend on.
18021            pkg = mPackages.get(packageName);
18022
18023            allUsers = sUserManager.getUserIds();
18024
18025            if (pkg != null && pkg.staticSharedLibName != null) {
18026                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18027                        pkg.staticSharedLibVersion);
18028                if (libEntry != null) {
18029                    for (int currUserId : allUsers) {
18030                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18031                            continue;
18032                        }
18033                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18034                                libEntry.info, 0, currUserId);
18035                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18036                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18037                                    + " hosting lib " + libEntry.info.getName() + " version "
18038                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18039                                    + " for user " + currUserId);
18040                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18041                        }
18042                    }
18043                }
18044            }
18045
18046            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18047        }
18048
18049        final int freezeUser;
18050        if (isUpdatedSystemApp(uninstalledPs)
18051                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18052            // We're downgrading a system app, which will apply to all users, so
18053            // freeze them all during the downgrade
18054            freezeUser = UserHandle.USER_ALL;
18055        } else {
18056            freezeUser = removeUser;
18057        }
18058
18059        synchronized (mInstallLock) {
18060            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18061            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18062                    deleteFlags, "deletePackageX")) {
18063                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18064                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18065            }
18066            synchronized (mPackages) {
18067                if (res) {
18068                    if (pkg != null) {
18069                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18070                    }
18071                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18072                    updateInstantAppInstallerLocked(packageName);
18073                }
18074            }
18075        }
18076
18077        if (res) {
18078            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18079            info.sendPackageRemovedBroadcasts(killApp);
18080            info.sendSystemPackageUpdatedBroadcasts();
18081            info.sendSystemPackageAppearedBroadcasts();
18082        }
18083        // Force a gc here.
18084        Runtime.getRuntime().gc();
18085        // Delete the resources here after sending the broadcast to let
18086        // other processes clean up before deleting resources.
18087        if (info.args != null) {
18088            synchronized (mInstallLock) {
18089                info.args.doPostDeleteLI(true);
18090            }
18091        }
18092
18093        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18094    }
18095
18096    static class PackageRemovedInfo {
18097        final PackageSender packageSender;
18098        String removedPackage;
18099        String installerPackageName;
18100        int uid = -1;
18101        int removedAppId = -1;
18102        int[] origUsers;
18103        int[] removedUsers = null;
18104        int[] broadcastUsers = null;
18105        int[] instantUserIds = null;
18106        SparseArray<Integer> installReasons;
18107        boolean isRemovedPackageSystemUpdate = false;
18108        boolean isUpdate;
18109        boolean dataRemoved;
18110        boolean removedForAllUsers;
18111        boolean isStaticSharedLib;
18112        // Clean up resources deleted packages.
18113        InstallArgs args = null;
18114        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18115        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18116
18117        PackageRemovedInfo(PackageSender packageSender) {
18118            this.packageSender = packageSender;
18119        }
18120
18121        void sendPackageRemovedBroadcasts(boolean killApp) {
18122            sendPackageRemovedBroadcastInternal(killApp);
18123            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18124            for (int i = 0; i < childCount; i++) {
18125                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18126                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18127            }
18128        }
18129
18130        void sendSystemPackageUpdatedBroadcasts() {
18131            if (isRemovedPackageSystemUpdate) {
18132                sendSystemPackageUpdatedBroadcastsInternal();
18133                final int childCount = (removedChildPackages != null)
18134                        ? removedChildPackages.size() : 0;
18135                for (int i = 0; i < childCount; i++) {
18136                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18137                    if (childInfo.isRemovedPackageSystemUpdate) {
18138                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18139                    }
18140                }
18141            }
18142        }
18143
18144        void sendSystemPackageAppearedBroadcasts() {
18145            final int packageCount = (appearedChildPackages != null)
18146                    ? appearedChildPackages.size() : 0;
18147            for (int i = 0; i < packageCount; i++) {
18148                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18149                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18150                    true /*sendBootCompleted*/, false /*startReceiver*/,
18151                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18152            }
18153        }
18154
18155        private void sendSystemPackageUpdatedBroadcastsInternal() {
18156            Bundle extras = new Bundle(2);
18157            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18158            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18159            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18160                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18161            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18162                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18163            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18164                null, null, 0, removedPackage, null, null, null);
18165            if (installerPackageName != null) {
18166                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18167                        removedPackage, extras, 0 /*flags*/,
18168                        installerPackageName, null, null, null);
18169                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18170                        removedPackage, extras, 0 /*flags*/,
18171                        installerPackageName, null, null, null);
18172            }
18173        }
18174
18175        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18176            // Don't send static shared library removal broadcasts as these
18177            // libs are visible only the the apps that depend on them an one
18178            // cannot remove the library if it has a dependency.
18179            if (isStaticSharedLib) {
18180                return;
18181            }
18182            Bundle extras = new Bundle(2);
18183            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18184            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18185            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18186            if (isUpdate || isRemovedPackageSystemUpdate) {
18187                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18188            }
18189            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18190            if (removedPackage != null) {
18191                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18192                    removedPackage, extras, 0, null /*targetPackage*/, null,
18193                    broadcastUsers, instantUserIds);
18194                if (installerPackageName != null) {
18195                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18196                            removedPackage, extras, 0 /*flags*/,
18197                            installerPackageName, null, broadcastUsers, instantUserIds);
18198                }
18199                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18200                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18201                        removedPackage, extras,
18202                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18203                        null, null, broadcastUsers, instantUserIds);
18204                    packageSender.notifyPackageRemoved(removedPackage);
18205                }
18206            }
18207            if (removedAppId >= 0) {
18208                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18209                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18210                    null, null, broadcastUsers, instantUserIds);
18211            }
18212        }
18213
18214        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18215            removedUsers = userIds;
18216            if (removedUsers == null) {
18217                broadcastUsers = null;
18218                return;
18219            }
18220
18221            broadcastUsers = EMPTY_INT_ARRAY;
18222            instantUserIds = EMPTY_INT_ARRAY;
18223            for (int i = userIds.length - 1; i >= 0; --i) {
18224                final int userId = userIds[i];
18225                if (deletedPackageSetting.getInstantApp(userId)) {
18226                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18227                } else {
18228                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18229                }
18230            }
18231        }
18232    }
18233
18234    /*
18235     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18236     * flag is not set, the data directory is removed as well.
18237     * make sure this flag is set for partially installed apps. If not its meaningless to
18238     * delete a partially installed application.
18239     */
18240    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18241            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18242        String packageName = ps.name;
18243        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18244        // Retrieve object to delete permissions for shared user later on
18245        final PackageParser.Package deletedPkg;
18246        final PackageSetting deletedPs;
18247        // reader
18248        synchronized (mPackages) {
18249            deletedPkg = mPackages.get(packageName);
18250            deletedPs = mSettings.mPackages.get(packageName);
18251            if (outInfo != null) {
18252                outInfo.removedPackage = packageName;
18253                outInfo.installerPackageName = ps.installerPackageName;
18254                outInfo.isStaticSharedLib = deletedPkg != null
18255                        && deletedPkg.staticSharedLibName != null;
18256                outInfo.populateUsers(deletedPs == null ? null
18257                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18258            }
18259        }
18260
18261        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18262
18263        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18264            final PackageParser.Package resolvedPkg;
18265            if (deletedPkg != null) {
18266                resolvedPkg = deletedPkg;
18267            } else {
18268                // We don't have a parsed package when it lives on an ejected
18269                // adopted storage device, so fake something together
18270                resolvedPkg = new PackageParser.Package(ps.name);
18271                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18272            }
18273            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18274                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18275            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18276            if (outInfo != null) {
18277                outInfo.dataRemoved = true;
18278            }
18279            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18280        }
18281
18282        int removedAppId = -1;
18283
18284        // writer
18285        synchronized (mPackages) {
18286            boolean installedStateChanged = false;
18287            if (deletedPs != null) {
18288                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18289                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18290                    clearDefaultBrowserIfNeeded(packageName);
18291                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18292                    removedAppId = mSettings.removePackageLPw(packageName);
18293                    if (outInfo != null) {
18294                        outInfo.removedAppId = removedAppId;
18295                    }
18296                    mPermissionManager.updatePermissions(
18297                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18298                    if (deletedPs.sharedUser != null) {
18299                        // Remove permissions associated with package. Since runtime
18300                        // permissions are per user we have to kill the removed package
18301                        // or packages running under the shared user of the removed
18302                        // package if revoking the permissions requested only by the removed
18303                        // package is successful and this causes a change in gids.
18304                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18305                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18306                                    userId);
18307                            if (userIdToKill == UserHandle.USER_ALL
18308                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18309                                // If gids changed for this user, kill all affected packages.
18310                                mHandler.post(new Runnable() {
18311                                    @Override
18312                                    public void run() {
18313                                        // This has to happen with no lock held.
18314                                        killApplication(deletedPs.name, deletedPs.appId,
18315                                                KILL_APP_REASON_GIDS_CHANGED);
18316                                    }
18317                                });
18318                                break;
18319                            }
18320                        }
18321                    }
18322                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18323                }
18324                // make sure to preserve per-user disabled state if this removal was just
18325                // a downgrade of a system app to the factory package
18326                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18327                    if (DEBUG_REMOVE) {
18328                        Slog.d(TAG, "Propagating install state across downgrade");
18329                    }
18330                    for (int userId : allUserHandles) {
18331                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18332                        if (DEBUG_REMOVE) {
18333                            Slog.d(TAG, "    user " + userId + " => " + installed);
18334                        }
18335                        if (installed != ps.getInstalled(userId)) {
18336                            installedStateChanged = true;
18337                        }
18338                        ps.setInstalled(installed, userId);
18339                    }
18340                }
18341            }
18342            // can downgrade to reader
18343            if (writeSettings) {
18344                // Save settings now
18345                mSettings.writeLPr();
18346            }
18347            if (installedStateChanged) {
18348                mSettings.writeKernelMappingLPr(ps);
18349            }
18350        }
18351        if (removedAppId != -1) {
18352            // A user ID was deleted here. Go through all users and remove it
18353            // from KeyStore.
18354            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18355        }
18356    }
18357
18358    static boolean locationIsPrivileged(String path) {
18359        try {
18360            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18361            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18362            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18363            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18364            return path.startsWith(privilegedAppDir.getCanonicalPath())
18365                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18366                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18367                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18368        } catch (IOException e) {
18369            Slog.e(TAG, "Unable to access code path " + path);
18370        }
18371        return false;
18372    }
18373
18374    static boolean locationIsOem(String path) {
18375        try {
18376            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18377        } catch (IOException e) {
18378            Slog.e(TAG, "Unable to access code path " + path);
18379        }
18380        return false;
18381    }
18382
18383    static boolean locationIsVendor(String path) {
18384        try {
18385            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18386                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18387        } catch (IOException e) {
18388            Slog.e(TAG, "Unable to access code path " + path);
18389        }
18390        return false;
18391    }
18392
18393    static boolean locationIsProduct(String path) {
18394        try {
18395            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18396        } catch (IOException e) {
18397            Slog.e(TAG, "Unable to access code path " + path);
18398        }
18399        return false;
18400    }
18401
18402    /*
18403     * Tries to delete system package.
18404     */
18405    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18406            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18407            boolean writeSettings) {
18408        if (deletedPs.parentPackageName != null) {
18409            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18410            return false;
18411        }
18412
18413        final boolean applyUserRestrictions
18414                = (allUserHandles != null) && (outInfo.origUsers != null);
18415        final PackageSetting disabledPs;
18416        // Confirm if the system package has been updated
18417        // An updated system app can be deleted. This will also have to restore
18418        // the system pkg from system partition
18419        // reader
18420        synchronized (mPackages) {
18421            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18422        }
18423
18424        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18425                + " disabledPs=" + disabledPs);
18426
18427        if (disabledPs == null) {
18428            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18429            return false;
18430        } else if (DEBUG_REMOVE) {
18431            Slog.d(TAG, "Deleting system pkg from data partition");
18432        }
18433
18434        if (DEBUG_REMOVE) {
18435            if (applyUserRestrictions) {
18436                Slog.d(TAG, "Remembering install states:");
18437                for (int userId : allUserHandles) {
18438                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18439                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18440                }
18441            }
18442        }
18443
18444        // Delete the updated package
18445        outInfo.isRemovedPackageSystemUpdate = true;
18446        if (outInfo.removedChildPackages != null) {
18447            final int childCount = (deletedPs.childPackageNames != null)
18448                    ? deletedPs.childPackageNames.size() : 0;
18449            for (int i = 0; i < childCount; i++) {
18450                String childPackageName = deletedPs.childPackageNames.get(i);
18451                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18452                        .contains(childPackageName)) {
18453                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18454                            childPackageName);
18455                    if (childInfo != null) {
18456                        childInfo.isRemovedPackageSystemUpdate = true;
18457                    }
18458                }
18459            }
18460        }
18461
18462        if (disabledPs.versionCode < deletedPs.versionCode) {
18463            // Delete data for downgrades
18464            flags &= ~PackageManager.DELETE_KEEP_DATA;
18465        } else {
18466            // Preserve data by setting flag
18467            flags |= PackageManager.DELETE_KEEP_DATA;
18468        }
18469
18470        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18471                outInfo, writeSettings, disabledPs.pkg);
18472        if (!ret) {
18473            return false;
18474        }
18475
18476        // writer
18477        synchronized (mPackages) {
18478            // NOTE: The system package always needs to be enabled; even if it's for
18479            // a compressed stub. If we don't, installing the system package fails
18480            // during scan [scanning checks the disabled packages]. We will reverse
18481            // this later, after we've "installed" the stub.
18482            // Reinstate the old system package
18483            enableSystemPackageLPw(disabledPs.pkg);
18484            // Remove any native libraries from the upgraded package.
18485            removeNativeBinariesLI(deletedPs);
18486        }
18487
18488        // Install the system package
18489        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18490        try {
18491            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18492                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18493        } catch (PackageManagerException e) {
18494            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18495                    + e.getMessage());
18496            return false;
18497        } finally {
18498            if (disabledPs.pkg.isStub) {
18499                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18500            }
18501        }
18502        return true;
18503    }
18504
18505    /**
18506     * Installs a package that's already on the system partition.
18507     */
18508    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18509            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18510            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18511                    throws PackageManagerException {
18512        @ParseFlags int parseFlags =
18513                mDefParseFlags
18514                | PackageParser.PARSE_MUST_BE_APK
18515                | PackageParser.PARSE_IS_SYSTEM_DIR;
18516        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18517        if (isPrivileged || locationIsPrivileged(codePathString)) {
18518            scanFlags |= SCAN_AS_PRIVILEGED;
18519        }
18520        if (locationIsOem(codePathString)) {
18521            scanFlags |= SCAN_AS_OEM;
18522        }
18523        if (locationIsVendor(codePathString)) {
18524            scanFlags |= SCAN_AS_VENDOR;
18525        }
18526        if (locationIsProduct(codePathString)) {
18527            scanFlags |= SCAN_AS_PRODUCT;
18528        }
18529
18530        final File codePath = new File(codePathString);
18531        final PackageParser.Package pkg =
18532                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18533
18534        try {
18535            // update shared libraries for the newly re-installed system package
18536            updateSharedLibrariesLPr(pkg, null);
18537        } catch (PackageManagerException e) {
18538            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18539        }
18540
18541        prepareAppDataAfterInstallLIF(pkg);
18542
18543        // writer
18544        synchronized (mPackages) {
18545            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18546
18547            // Propagate the permissions state as we do not want to drop on the floor
18548            // runtime permissions. The update permissions method below will take
18549            // care of removing obsolete permissions and grant install permissions.
18550            if (origPermissionState != null) {
18551                ps.getPermissionsState().copyFrom(origPermissionState);
18552            }
18553            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18554                    mPermissionCallback);
18555
18556            final boolean applyUserRestrictions
18557                    = (allUserHandles != null) && (origUserHandles != null);
18558            if (applyUserRestrictions) {
18559                boolean installedStateChanged = false;
18560                if (DEBUG_REMOVE) {
18561                    Slog.d(TAG, "Propagating install state across reinstall");
18562                }
18563                for (int userId : allUserHandles) {
18564                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18565                    if (DEBUG_REMOVE) {
18566                        Slog.d(TAG, "    user " + userId + " => " + installed);
18567                    }
18568                    if (installed != ps.getInstalled(userId)) {
18569                        installedStateChanged = true;
18570                    }
18571                    ps.setInstalled(installed, userId);
18572
18573                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18574                }
18575                // Regardless of writeSettings we need to ensure that this restriction
18576                // state propagation is persisted
18577                mSettings.writeAllUsersPackageRestrictionsLPr();
18578                if (installedStateChanged) {
18579                    mSettings.writeKernelMappingLPr(ps);
18580                }
18581            }
18582            // can downgrade to reader here
18583            if (writeSettings) {
18584                mSettings.writeLPr();
18585            }
18586        }
18587        return pkg;
18588    }
18589
18590    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18591            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18592            PackageRemovedInfo outInfo, boolean writeSettings,
18593            PackageParser.Package replacingPackage) {
18594        synchronized (mPackages) {
18595            if (outInfo != null) {
18596                outInfo.uid = ps.appId;
18597            }
18598
18599            if (outInfo != null && outInfo.removedChildPackages != null) {
18600                final int childCount = (ps.childPackageNames != null)
18601                        ? ps.childPackageNames.size() : 0;
18602                for (int i = 0; i < childCount; i++) {
18603                    String childPackageName = ps.childPackageNames.get(i);
18604                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18605                    if (childPs == null) {
18606                        return false;
18607                    }
18608                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18609                            childPackageName);
18610                    if (childInfo != null) {
18611                        childInfo.uid = childPs.appId;
18612                    }
18613                }
18614            }
18615        }
18616
18617        // Delete package data from internal structures and also remove data if flag is set
18618        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18619
18620        // Delete the child packages data
18621        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18622        for (int i = 0; i < childCount; i++) {
18623            PackageSetting childPs;
18624            synchronized (mPackages) {
18625                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18626            }
18627            if (childPs != null) {
18628                PackageRemovedInfo childOutInfo = (outInfo != null
18629                        && outInfo.removedChildPackages != null)
18630                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18631                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18632                        && (replacingPackage != null
18633                        && !replacingPackage.hasChildPackage(childPs.name))
18634                        ? flags & ~DELETE_KEEP_DATA : flags;
18635                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18636                        deleteFlags, writeSettings);
18637            }
18638        }
18639
18640        // Delete application code and resources only for parent packages
18641        if (ps.parentPackageName == null) {
18642            if (deleteCodeAndResources && (outInfo != null)) {
18643                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18644                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18645                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18646            }
18647        }
18648
18649        return true;
18650    }
18651
18652    @Override
18653    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18654            int userId) {
18655        mContext.enforceCallingOrSelfPermission(
18656                android.Manifest.permission.DELETE_PACKAGES, null);
18657        synchronized (mPackages) {
18658            // Cannot block uninstall of static shared libs as they are
18659            // considered a part of the using app (emulating static linking).
18660            // Also static libs are installed always on internal storage.
18661            PackageParser.Package pkg = mPackages.get(packageName);
18662            if (pkg != null && pkg.staticSharedLibName != null) {
18663                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18664                        + " providing static shared library: " + pkg.staticSharedLibName);
18665                return false;
18666            }
18667            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18668            mSettings.writePackageRestrictionsLPr(userId);
18669        }
18670        return true;
18671    }
18672
18673    @Override
18674    public boolean getBlockUninstallForUser(String packageName, int userId) {
18675        synchronized (mPackages) {
18676            final PackageSetting ps = mSettings.mPackages.get(packageName);
18677            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18678                return false;
18679            }
18680            return mSettings.getBlockUninstallLPr(userId, packageName);
18681        }
18682    }
18683
18684    @Override
18685    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18686        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18687        synchronized (mPackages) {
18688            PackageSetting ps = mSettings.mPackages.get(packageName);
18689            if (ps == null) {
18690                Log.w(TAG, "Package doesn't exist: " + packageName);
18691                return false;
18692            }
18693            if (systemUserApp) {
18694                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18695            } else {
18696                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18697            }
18698            mSettings.writeLPr();
18699        }
18700        return true;
18701    }
18702
18703    /*
18704     * This method handles package deletion in general
18705     */
18706    private boolean deletePackageLIF(String packageName, UserHandle user,
18707            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18708            PackageRemovedInfo outInfo, boolean writeSettings,
18709            PackageParser.Package replacingPackage) {
18710        if (packageName == null) {
18711            Slog.w(TAG, "Attempt to delete null packageName.");
18712            return false;
18713        }
18714
18715        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18716
18717        PackageSetting ps;
18718        synchronized (mPackages) {
18719            ps = mSettings.mPackages.get(packageName);
18720            if (ps == null) {
18721                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18722                return false;
18723            }
18724
18725            if (ps.parentPackageName != null && (!isSystemApp(ps)
18726                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18727                if (DEBUG_REMOVE) {
18728                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18729                            + ((user == null) ? UserHandle.USER_ALL : user));
18730                }
18731                final int removedUserId = (user != null) ? user.getIdentifier()
18732                        : UserHandle.USER_ALL;
18733
18734                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18735                    return false;
18736                }
18737                markPackageUninstalledForUserLPw(ps, user);
18738                scheduleWritePackageRestrictionsLocked(user);
18739                return true;
18740            }
18741        }
18742
18743        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18744        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18745            onSuspendingPackageRemoved(packageName, userId);
18746        }
18747
18748
18749        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18750                && user.getIdentifier() != UserHandle.USER_ALL)) {
18751            // The caller is asking that the package only be deleted for a single
18752            // user.  To do this, we just mark its uninstalled state and delete
18753            // its data. If this is a system app, we only allow this to happen if
18754            // they have set the special DELETE_SYSTEM_APP which requests different
18755            // semantics than normal for uninstalling system apps.
18756            markPackageUninstalledForUserLPw(ps, user);
18757
18758            if (!isSystemApp(ps)) {
18759                // Do not uninstall the APK if an app should be cached
18760                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18761                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18762                    // Other user still have this package installed, so all
18763                    // we need to do is clear this user's data and save that
18764                    // it is uninstalled.
18765                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18766                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18767                        return false;
18768                    }
18769                    scheduleWritePackageRestrictionsLocked(user);
18770                    return true;
18771                } else {
18772                    // We need to set it back to 'installed' so the uninstall
18773                    // broadcasts will be sent correctly.
18774                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18775                    ps.setInstalled(true, user.getIdentifier());
18776                    mSettings.writeKernelMappingLPr(ps);
18777                }
18778            } else {
18779                // This is a system app, so we assume that the
18780                // other users still have this package installed, so all
18781                // we need to do is clear this user's data and save that
18782                // it is uninstalled.
18783                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18784                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18785                    return false;
18786                }
18787                scheduleWritePackageRestrictionsLocked(user);
18788                return true;
18789            }
18790        }
18791
18792        // If we are deleting a composite package for all users, keep track
18793        // of result for each child.
18794        if (ps.childPackageNames != null && outInfo != null) {
18795            synchronized (mPackages) {
18796                final int childCount = ps.childPackageNames.size();
18797                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18798                for (int i = 0; i < childCount; i++) {
18799                    String childPackageName = ps.childPackageNames.get(i);
18800                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18801                    childInfo.removedPackage = childPackageName;
18802                    childInfo.installerPackageName = ps.installerPackageName;
18803                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18804                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18805                    if (childPs != null) {
18806                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18807                    }
18808                }
18809            }
18810        }
18811
18812        boolean ret = false;
18813        if (isSystemApp(ps)) {
18814            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18815            // When an updated system application is deleted we delete the existing resources
18816            // as well and fall back to existing code in system partition
18817            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18818        } else {
18819            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18820            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18821                    outInfo, writeSettings, replacingPackage);
18822        }
18823
18824        // Take a note whether we deleted the package for all users
18825        if (outInfo != null) {
18826            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18827            if (outInfo.removedChildPackages != null) {
18828                synchronized (mPackages) {
18829                    final int childCount = outInfo.removedChildPackages.size();
18830                    for (int i = 0; i < childCount; i++) {
18831                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18832                        if (childInfo != null) {
18833                            childInfo.removedForAllUsers = mPackages.get(
18834                                    childInfo.removedPackage) == null;
18835                        }
18836                    }
18837                }
18838            }
18839            // If we uninstalled an update to a system app there may be some
18840            // child packages that appeared as they are declared in the system
18841            // app but were not declared in the update.
18842            if (isSystemApp(ps)) {
18843                synchronized (mPackages) {
18844                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18845                    final int childCount = (updatedPs.childPackageNames != null)
18846                            ? updatedPs.childPackageNames.size() : 0;
18847                    for (int i = 0; i < childCount; i++) {
18848                        String childPackageName = updatedPs.childPackageNames.get(i);
18849                        if (outInfo.removedChildPackages == null
18850                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18851                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18852                            if (childPs == null) {
18853                                continue;
18854                            }
18855                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18856                            installRes.name = childPackageName;
18857                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18858                            installRes.pkg = mPackages.get(childPackageName);
18859                            installRes.uid = childPs.pkg.applicationInfo.uid;
18860                            if (outInfo.appearedChildPackages == null) {
18861                                outInfo.appearedChildPackages = new ArrayMap<>();
18862                            }
18863                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18864                        }
18865                    }
18866                }
18867            }
18868        }
18869
18870        return ret;
18871    }
18872
18873    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18874        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18875                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18876        for (int nextUserId : userIds) {
18877            if (DEBUG_REMOVE) {
18878                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18879            }
18880            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18881                    false /*installed*/,
18882                    true /*stopped*/,
18883                    true /*notLaunched*/,
18884                    false /*hidden*/,
18885                    false /*suspended*/,
18886                    null, /*suspendingPackage*/
18887                    null, /*suspendedAppExtras*/
18888                    null, /*suspendedLauncherExtras*/
18889                    false /*instantApp*/,
18890                    false /*virtualPreload*/,
18891                    null /*lastDisableAppCaller*/,
18892                    null /*enabledComponents*/,
18893                    null /*disabledComponents*/,
18894                    ps.readUserState(nextUserId).domainVerificationStatus,
18895                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18896                    null /*harmfulAppWarning*/);
18897        }
18898        mSettings.writeKernelMappingLPr(ps);
18899    }
18900
18901    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18902            PackageRemovedInfo outInfo) {
18903        final PackageParser.Package pkg;
18904        synchronized (mPackages) {
18905            pkg = mPackages.get(ps.name);
18906        }
18907
18908        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18909                : new int[] {userId};
18910        for (int nextUserId : userIds) {
18911            if (DEBUG_REMOVE) {
18912                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18913                        + nextUserId);
18914            }
18915
18916            destroyAppDataLIF(pkg, userId,
18917                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18918            destroyAppProfilesLIF(pkg, userId);
18919            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18920            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18921            schedulePackageCleaning(ps.name, nextUserId, false);
18922            synchronized (mPackages) {
18923                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18924                    scheduleWritePackageRestrictionsLocked(nextUserId);
18925                }
18926                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18927            }
18928        }
18929
18930        if (outInfo != null) {
18931            outInfo.removedPackage = ps.name;
18932            outInfo.installerPackageName = ps.installerPackageName;
18933            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18934            outInfo.removedAppId = ps.appId;
18935            outInfo.removedUsers = userIds;
18936            outInfo.broadcastUsers = userIds;
18937        }
18938
18939        return true;
18940    }
18941
18942    private final class ClearStorageConnection implements ServiceConnection {
18943        IMediaContainerService mContainerService;
18944
18945        @Override
18946        public void onServiceConnected(ComponentName name, IBinder service) {
18947            synchronized (this) {
18948                mContainerService = IMediaContainerService.Stub
18949                        .asInterface(Binder.allowBlocking(service));
18950                notifyAll();
18951            }
18952        }
18953
18954        @Override
18955        public void onServiceDisconnected(ComponentName name) {
18956        }
18957    }
18958
18959    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18960        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18961
18962        final boolean mounted;
18963        if (Environment.isExternalStorageEmulated()) {
18964            mounted = true;
18965        } else {
18966            final String status = Environment.getExternalStorageState();
18967
18968            mounted = status.equals(Environment.MEDIA_MOUNTED)
18969                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18970        }
18971
18972        if (!mounted) {
18973            return;
18974        }
18975
18976        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18977        int[] users;
18978        if (userId == UserHandle.USER_ALL) {
18979            users = sUserManager.getUserIds();
18980        } else {
18981            users = new int[] { userId };
18982        }
18983        final ClearStorageConnection conn = new ClearStorageConnection();
18984        if (mContext.bindServiceAsUser(
18985                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18986            try {
18987                for (int curUser : users) {
18988                    long timeout = SystemClock.uptimeMillis() + 5000;
18989                    synchronized (conn) {
18990                        long now;
18991                        while (conn.mContainerService == null &&
18992                                (now = SystemClock.uptimeMillis()) < timeout) {
18993                            try {
18994                                conn.wait(timeout - now);
18995                            } catch (InterruptedException e) {
18996                            }
18997                        }
18998                    }
18999                    if (conn.mContainerService == null) {
19000                        return;
19001                    }
19002
19003                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19004                    clearDirectory(conn.mContainerService,
19005                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19006                    if (allData) {
19007                        clearDirectory(conn.mContainerService,
19008                                userEnv.buildExternalStorageAppDataDirs(packageName));
19009                        clearDirectory(conn.mContainerService,
19010                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19011                    }
19012                }
19013            } finally {
19014                mContext.unbindService(conn);
19015            }
19016        }
19017    }
19018
19019    @Override
19020    public void clearApplicationProfileData(String packageName) {
19021        enforceSystemOrRoot("Only the system can clear all profile data");
19022
19023        final PackageParser.Package pkg;
19024        synchronized (mPackages) {
19025            pkg = mPackages.get(packageName);
19026        }
19027
19028        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19029            synchronized (mInstallLock) {
19030                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19031            }
19032        }
19033    }
19034
19035    @Override
19036    public void clearApplicationUserData(final String packageName,
19037            final IPackageDataObserver observer, final int userId) {
19038        mContext.enforceCallingOrSelfPermission(
19039                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19040
19041        final int callingUid = Binder.getCallingUid();
19042        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19043                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19044
19045        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19046        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19047        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19048            throw new SecurityException("Cannot clear data for a protected package: "
19049                    + packageName);
19050        }
19051        // Queue up an async operation since the package deletion may take a little while.
19052        mHandler.post(new Runnable() {
19053            public void run() {
19054                mHandler.removeCallbacks(this);
19055                final boolean succeeded;
19056                if (!filterApp) {
19057                    try (PackageFreezer freezer = freezePackage(packageName,
19058                            "clearApplicationUserData")) {
19059                        synchronized (mInstallLock) {
19060                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19061                        }
19062                        clearExternalStorageDataSync(packageName, userId, true);
19063                        synchronized (mPackages) {
19064                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19065                                    packageName, userId);
19066                        }
19067                    }
19068                    if (succeeded) {
19069                        // invoke DeviceStorageMonitor's update method to clear any notifications
19070                        DeviceStorageMonitorInternal dsm = LocalServices
19071                                .getService(DeviceStorageMonitorInternal.class);
19072                        if (dsm != null) {
19073                            dsm.checkMemory();
19074                        }
19075                    }
19076                } else {
19077                    succeeded = false;
19078                }
19079                if (observer != null) {
19080                    try {
19081                        observer.onRemoveCompleted(packageName, succeeded);
19082                    } catch (RemoteException e) {
19083                        Log.i(TAG, "Observer no longer exists.");
19084                    }
19085                } //end if observer
19086            } //end run
19087        });
19088    }
19089
19090    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19091        if (packageName == null) {
19092            Slog.w(TAG, "Attempt to delete null packageName.");
19093            return false;
19094        }
19095
19096        // Try finding details about the requested package
19097        PackageParser.Package pkg;
19098        synchronized (mPackages) {
19099            pkg = mPackages.get(packageName);
19100            if (pkg == null) {
19101                final PackageSetting ps = mSettings.mPackages.get(packageName);
19102                if (ps != null) {
19103                    pkg = ps.pkg;
19104                }
19105            }
19106
19107            if (pkg == null) {
19108                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19109                return false;
19110            }
19111
19112            PackageSetting ps = (PackageSetting) pkg.mExtras;
19113            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19114        }
19115
19116        clearAppDataLIF(pkg, userId,
19117                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19118
19119        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19120        removeKeystoreDataIfNeeded(userId, appId);
19121
19122        UserManagerInternal umInternal = getUserManagerInternal();
19123        final int flags;
19124        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19125            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19126        } else if (umInternal.isUserRunning(userId)) {
19127            flags = StorageManager.FLAG_STORAGE_DE;
19128        } else {
19129            flags = 0;
19130        }
19131        prepareAppDataContentsLIF(pkg, userId, flags);
19132
19133        return true;
19134    }
19135
19136    /**
19137     * Reverts user permission state changes (permissions and flags) in
19138     * all packages for a given user.
19139     *
19140     * @param userId The device user for which to do a reset.
19141     */
19142    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19143        final int packageCount = mPackages.size();
19144        for (int i = 0; i < packageCount; i++) {
19145            PackageParser.Package pkg = mPackages.valueAt(i);
19146            PackageSetting ps = (PackageSetting) pkg.mExtras;
19147            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19148        }
19149    }
19150
19151    private void resetNetworkPolicies(int userId) {
19152        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19153    }
19154
19155    /**
19156     * Reverts user permission state changes (permissions and flags).
19157     *
19158     * @param ps The package for which to reset.
19159     * @param userId The device user for which to do a reset.
19160     */
19161    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19162            final PackageSetting ps, final int userId) {
19163        if (ps.pkg == null) {
19164            return;
19165        }
19166
19167        // These are flags that can change base on user actions.
19168        final int userSettableMask = FLAG_PERMISSION_USER_SET
19169                | FLAG_PERMISSION_USER_FIXED
19170                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19171                | FLAG_PERMISSION_REVIEW_REQUIRED;
19172
19173        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19174                | FLAG_PERMISSION_POLICY_FIXED;
19175
19176        boolean writeInstallPermissions = false;
19177        boolean writeRuntimePermissions = false;
19178
19179        final int permissionCount = ps.pkg.requestedPermissions.size();
19180        for (int i = 0; i < permissionCount; i++) {
19181            final String permName = ps.pkg.requestedPermissions.get(i);
19182            final BasePermission bp =
19183                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19184            if (bp == null) {
19185                continue;
19186            }
19187
19188            // If shared user we just reset the state to which only this app contributed.
19189            if (ps.sharedUser != null) {
19190                boolean used = false;
19191                final int packageCount = ps.sharedUser.packages.size();
19192                for (int j = 0; j < packageCount; j++) {
19193                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19194                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19195                            && pkg.pkg.requestedPermissions.contains(permName)) {
19196                        used = true;
19197                        break;
19198                    }
19199                }
19200                if (used) {
19201                    continue;
19202                }
19203            }
19204
19205            final PermissionsState permissionsState = ps.getPermissionsState();
19206
19207            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19208
19209            // Always clear the user settable flags.
19210            final boolean hasInstallState =
19211                    permissionsState.getInstallPermissionState(permName) != null;
19212            // If permission review is enabled and this is a legacy app, mark the
19213            // permission as requiring a review as this is the initial state.
19214            int flags = 0;
19215            if (mSettings.mPermissions.mPermissionReviewRequired
19216                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19217                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19218            }
19219            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19220                if (hasInstallState) {
19221                    writeInstallPermissions = true;
19222                } else {
19223                    writeRuntimePermissions = true;
19224                }
19225            }
19226
19227            // Below is only runtime permission handling.
19228            if (!bp.isRuntime()) {
19229                continue;
19230            }
19231
19232            // Never clobber system or policy.
19233            if ((oldFlags & policyOrSystemFlags) != 0) {
19234                continue;
19235            }
19236
19237            // If this permission was granted by default, make sure it is.
19238            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19239                if (permissionsState.grantRuntimePermission(bp, userId)
19240                        != PERMISSION_OPERATION_FAILURE) {
19241                    writeRuntimePermissions = true;
19242                }
19243            // If permission review is enabled the permissions for a legacy apps
19244            // are represented as constantly granted runtime ones, so don't revoke.
19245            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19246                // Otherwise, reset the permission.
19247                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19248                switch (revokeResult) {
19249                    case PERMISSION_OPERATION_SUCCESS:
19250                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19251                        writeRuntimePermissions = true;
19252                        final int appId = ps.appId;
19253                        mHandler.post(new Runnable() {
19254                            @Override
19255                            public void run() {
19256                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19257                            }
19258                        });
19259                    } break;
19260                }
19261            }
19262        }
19263
19264        // Synchronously write as we are taking permissions away.
19265        if (writeRuntimePermissions) {
19266            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19267        }
19268
19269        // Synchronously write as we are taking permissions away.
19270        if (writeInstallPermissions) {
19271            mSettings.writeLPr();
19272        }
19273    }
19274
19275    /**
19276     * Remove entries from the keystore daemon. Will only remove it if the
19277     * {@code appId} is valid.
19278     */
19279    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19280        if (appId < 0) {
19281            return;
19282        }
19283
19284        final KeyStore keyStore = KeyStore.getInstance();
19285        if (keyStore != null) {
19286            if (userId == UserHandle.USER_ALL) {
19287                for (final int individual : sUserManager.getUserIds()) {
19288                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19289                }
19290            } else {
19291                keyStore.clearUid(UserHandle.getUid(userId, appId));
19292            }
19293        } else {
19294            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19295        }
19296    }
19297
19298    @Override
19299    public void deleteApplicationCacheFiles(final String packageName,
19300            final IPackageDataObserver observer) {
19301        final int userId = UserHandle.getCallingUserId();
19302        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19303    }
19304
19305    @Override
19306    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19307            final IPackageDataObserver observer) {
19308        final int callingUid = Binder.getCallingUid();
19309        if (mContext.checkCallingOrSelfPermission(
19310                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19311                != PackageManager.PERMISSION_GRANTED) {
19312            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19313            if (mContext.checkCallingOrSelfPermission(
19314                    android.Manifest.permission.DELETE_CACHE_FILES)
19315                    == PackageManager.PERMISSION_GRANTED) {
19316                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19317                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19318                        ", silently ignoring");
19319                return;
19320            }
19321            mContext.enforceCallingOrSelfPermission(
19322                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19323        }
19324        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19325                /* requireFullPermission= */ true, /* checkShell= */ false,
19326                "delete application cache files");
19327        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19328                android.Manifest.permission.ACCESS_INSTANT_APPS);
19329
19330        final PackageParser.Package pkg;
19331        synchronized (mPackages) {
19332            pkg = mPackages.get(packageName);
19333        }
19334
19335        // Queue up an async operation since the package deletion may take a little while.
19336        mHandler.post(new Runnable() {
19337            public void run() {
19338                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19339                boolean doClearData = true;
19340                if (ps != null) {
19341                    final boolean targetIsInstantApp =
19342                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19343                    doClearData = !targetIsInstantApp
19344                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19345                }
19346                if (doClearData) {
19347                    synchronized (mInstallLock) {
19348                        final int flags = StorageManager.FLAG_STORAGE_DE
19349                                | StorageManager.FLAG_STORAGE_CE;
19350                        // We're only clearing cache files, so we don't care if the
19351                        // app is unfrozen and still able to run
19352                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19353                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19354                    }
19355                    clearExternalStorageDataSync(packageName, userId, false);
19356                }
19357                if (observer != null) {
19358                    try {
19359                        observer.onRemoveCompleted(packageName, true);
19360                    } catch (RemoteException e) {
19361                        Log.i(TAG, "Observer no longer exists.");
19362                    }
19363                }
19364            }
19365        });
19366    }
19367
19368    @Override
19369    public void getPackageSizeInfo(final String packageName, int userHandle,
19370            final IPackageStatsObserver observer) {
19371        throw new UnsupportedOperationException(
19372                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19373    }
19374
19375    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19376        final PackageSetting ps;
19377        synchronized (mPackages) {
19378            ps = mSettings.mPackages.get(packageName);
19379            if (ps == null) {
19380                Slog.w(TAG, "Failed to find settings for " + packageName);
19381                return false;
19382            }
19383        }
19384
19385        final String[] packageNames = { packageName };
19386        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19387        final String[] codePaths = { ps.codePathString };
19388
19389        try {
19390            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19391                    ps.appId, ceDataInodes, codePaths, stats);
19392
19393            // For now, ignore code size of packages on system partition
19394            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19395                stats.codeSize = 0;
19396            }
19397
19398            // External clients expect these to be tracked separately
19399            stats.dataSize -= stats.cacheSize;
19400
19401        } catch (InstallerException e) {
19402            Slog.w(TAG, String.valueOf(e));
19403            return false;
19404        }
19405
19406        return true;
19407    }
19408
19409    private int getUidTargetSdkVersionLockedLPr(int uid) {
19410        Object obj = mSettings.getUserIdLPr(uid);
19411        if (obj instanceof SharedUserSetting) {
19412            final SharedUserSetting sus = (SharedUserSetting) obj;
19413            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19414            final Iterator<PackageSetting> it = sus.packages.iterator();
19415            while (it.hasNext()) {
19416                final PackageSetting ps = it.next();
19417                if (ps.pkg != null) {
19418                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19419                    if (v < vers) vers = v;
19420                }
19421            }
19422            return vers;
19423        } else if (obj instanceof PackageSetting) {
19424            final PackageSetting ps = (PackageSetting) obj;
19425            if (ps.pkg != null) {
19426                return ps.pkg.applicationInfo.targetSdkVersion;
19427            }
19428        }
19429        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19430    }
19431
19432    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19433        final PackageParser.Package p = mPackages.get(packageName);
19434        if (p != null) {
19435            return p.applicationInfo.targetSdkVersion;
19436        }
19437        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19438    }
19439
19440    @Override
19441    public void addPreferredActivity(IntentFilter filter, int match,
19442            ComponentName[] set, ComponentName activity, int userId) {
19443        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19444                "Adding preferred");
19445    }
19446
19447    private void addPreferredActivityInternal(IntentFilter filter, int match,
19448            ComponentName[] set, ComponentName activity, boolean always, int userId,
19449            String opname) {
19450        // writer
19451        int callingUid = Binder.getCallingUid();
19452        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19453                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19454        if (filter.countActions() == 0) {
19455            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19456            return;
19457        }
19458        synchronized (mPackages) {
19459            if (mContext.checkCallingOrSelfPermission(
19460                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19461                    != PackageManager.PERMISSION_GRANTED) {
19462                if (getUidTargetSdkVersionLockedLPr(callingUid)
19463                        < Build.VERSION_CODES.FROYO) {
19464                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19465                            + callingUid);
19466                    return;
19467                }
19468                mContext.enforceCallingOrSelfPermission(
19469                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19470            }
19471
19472            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19473            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19474                    + userId + ":");
19475            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19476            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19477            scheduleWritePackageRestrictionsLocked(userId);
19478            postPreferredActivityChangedBroadcast(userId);
19479        }
19480    }
19481
19482    private void postPreferredActivityChangedBroadcast(int userId) {
19483        mHandler.post(() -> {
19484            final IActivityManager am = ActivityManager.getService();
19485            if (am == null) {
19486                return;
19487            }
19488
19489            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19490            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19491            try {
19492                am.broadcastIntent(null, intent, null, null,
19493                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19494                        null, false, false, userId);
19495            } catch (RemoteException e) {
19496            }
19497        });
19498    }
19499
19500    @Override
19501    public void replacePreferredActivity(IntentFilter filter, int match,
19502            ComponentName[] set, ComponentName activity, int userId) {
19503        if (filter.countActions() != 1) {
19504            throw new IllegalArgumentException(
19505                    "replacePreferredActivity expects filter to have only 1 action.");
19506        }
19507        if (filter.countDataAuthorities() != 0
19508                || filter.countDataPaths() != 0
19509                || filter.countDataSchemes() > 1
19510                || filter.countDataTypes() != 0) {
19511            throw new IllegalArgumentException(
19512                    "replacePreferredActivity expects filter to have no data authorities, " +
19513                    "paths, or types; and at most one scheme.");
19514        }
19515
19516        final int callingUid = Binder.getCallingUid();
19517        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19518                true /* requireFullPermission */, false /* checkShell */,
19519                "replace preferred activity");
19520        synchronized (mPackages) {
19521            if (mContext.checkCallingOrSelfPermission(
19522                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19523                    != PackageManager.PERMISSION_GRANTED) {
19524                if (getUidTargetSdkVersionLockedLPr(callingUid)
19525                        < Build.VERSION_CODES.FROYO) {
19526                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19527                            + Binder.getCallingUid());
19528                    return;
19529                }
19530                mContext.enforceCallingOrSelfPermission(
19531                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19532            }
19533
19534            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19535            if (pir != null) {
19536                // Get all of the existing entries that exactly match this filter.
19537                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19538                if (existing != null && existing.size() == 1) {
19539                    PreferredActivity cur = existing.get(0);
19540                    if (DEBUG_PREFERRED) {
19541                        Slog.i(TAG, "Checking replace of preferred:");
19542                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19543                        if (!cur.mPref.mAlways) {
19544                            Slog.i(TAG, "  -- CUR; not mAlways!");
19545                        } else {
19546                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19547                            Slog.i(TAG, "  -- CUR: mSet="
19548                                    + Arrays.toString(cur.mPref.mSetComponents));
19549                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19550                            Slog.i(TAG, "  -- NEW: mMatch="
19551                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19552                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19553                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19554                        }
19555                    }
19556                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19557                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19558                            && cur.mPref.sameSet(set)) {
19559                        // Setting the preferred activity to what it happens to be already
19560                        if (DEBUG_PREFERRED) {
19561                            Slog.i(TAG, "Replacing with same preferred activity "
19562                                    + cur.mPref.mShortComponent + " for user "
19563                                    + userId + ":");
19564                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19565                        }
19566                        return;
19567                    }
19568                }
19569
19570                if (existing != null) {
19571                    if (DEBUG_PREFERRED) {
19572                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19573                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19574                    }
19575                    for (int i = 0; i < existing.size(); i++) {
19576                        PreferredActivity pa = existing.get(i);
19577                        if (DEBUG_PREFERRED) {
19578                            Slog.i(TAG, "Removing existing preferred activity "
19579                                    + pa.mPref.mComponent + ":");
19580                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19581                        }
19582                        pir.removeFilter(pa);
19583                    }
19584                }
19585            }
19586            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19587                    "Replacing preferred");
19588        }
19589    }
19590
19591    @Override
19592    public void clearPackagePreferredActivities(String packageName) {
19593        final int callingUid = Binder.getCallingUid();
19594        if (getInstantAppPackageName(callingUid) != null) {
19595            return;
19596        }
19597        // writer
19598        synchronized (mPackages) {
19599            PackageParser.Package pkg = mPackages.get(packageName);
19600            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19601                if (mContext.checkCallingOrSelfPermission(
19602                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19603                        != PackageManager.PERMISSION_GRANTED) {
19604                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19605                            < Build.VERSION_CODES.FROYO) {
19606                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19607                                + callingUid);
19608                        return;
19609                    }
19610                    mContext.enforceCallingOrSelfPermission(
19611                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19612                }
19613            }
19614            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19615            if (ps != null
19616                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19617                return;
19618            }
19619            int user = UserHandle.getCallingUserId();
19620            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19621                scheduleWritePackageRestrictionsLocked(user);
19622            }
19623        }
19624    }
19625
19626    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19627    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19628        ArrayList<PreferredActivity> removed = null;
19629        boolean changed = false;
19630        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19631            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19632            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19633            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19634                continue;
19635            }
19636            Iterator<PreferredActivity> it = pir.filterIterator();
19637            while (it.hasNext()) {
19638                PreferredActivity pa = it.next();
19639                // Mark entry for removal only if it matches the package name
19640                // and the entry is of type "always".
19641                if (packageName == null ||
19642                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19643                                && pa.mPref.mAlways)) {
19644                    if (removed == null) {
19645                        removed = new ArrayList<PreferredActivity>();
19646                    }
19647                    removed.add(pa);
19648                }
19649            }
19650            if (removed != null) {
19651                for (int j=0; j<removed.size(); j++) {
19652                    PreferredActivity pa = removed.get(j);
19653                    pir.removeFilter(pa);
19654                }
19655                changed = true;
19656            }
19657        }
19658        if (changed) {
19659            postPreferredActivityChangedBroadcast(userId);
19660        }
19661        return changed;
19662    }
19663
19664    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19665    private void clearIntentFilterVerificationsLPw(int userId) {
19666        final int packageCount = mPackages.size();
19667        for (int i = 0; i < packageCount; i++) {
19668            PackageParser.Package pkg = mPackages.valueAt(i);
19669            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19670        }
19671    }
19672
19673    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19674    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19675        if (userId == UserHandle.USER_ALL) {
19676            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19677                    sUserManager.getUserIds())) {
19678                for (int oneUserId : sUserManager.getUserIds()) {
19679                    scheduleWritePackageRestrictionsLocked(oneUserId);
19680                }
19681            }
19682        } else {
19683            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19684                scheduleWritePackageRestrictionsLocked(userId);
19685            }
19686        }
19687    }
19688
19689    /** Clears state for all users, and touches intent filter verification policy */
19690    void clearDefaultBrowserIfNeeded(String packageName) {
19691        for (int oneUserId : sUserManager.getUserIds()) {
19692            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19693        }
19694    }
19695
19696    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19697        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19698        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19699            if (packageName.equals(defaultBrowserPackageName)) {
19700                setDefaultBrowserPackageName(null, userId);
19701            }
19702        }
19703    }
19704
19705    @Override
19706    public void resetApplicationPreferences(int userId) {
19707        mContext.enforceCallingOrSelfPermission(
19708                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19709        final long identity = Binder.clearCallingIdentity();
19710        // writer
19711        try {
19712            synchronized (mPackages) {
19713                clearPackagePreferredActivitiesLPw(null, userId);
19714                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19715                // TODO: We have to reset the default SMS and Phone. This requires
19716                // significant refactoring to keep all default apps in the package
19717                // manager (cleaner but more work) or have the services provide
19718                // callbacks to the package manager to request a default app reset.
19719                applyFactoryDefaultBrowserLPw(userId);
19720                clearIntentFilterVerificationsLPw(userId);
19721                primeDomainVerificationsLPw(userId);
19722                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19723                scheduleWritePackageRestrictionsLocked(userId);
19724            }
19725            resetNetworkPolicies(userId);
19726        } finally {
19727            Binder.restoreCallingIdentity(identity);
19728        }
19729    }
19730
19731    @Override
19732    public int getPreferredActivities(List<IntentFilter> outFilters,
19733            List<ComponentName> outActivities, String packageName) {
19734        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19735            return 0;
19736        }
19737        int num = 0;
19738        final int userId = UserHandle.getCallingUserId();
19739        // reader
19740        synchronized (mPackages) {
19741            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19742            if (pir != null) {
19743                final Iterator<PreferredActivity> it = pir.filterIterator();
19744                while (it.hasNext()) {
19745                    final PreferredActivity pa = it.next();
19746                    if (packageName == null
19747                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19748                                    && pa.mPref.mAlways)) {
19749                        if (outFilters != null) {
19750                            outFilters.add(new IntentFilter(pa));
19751                        }
19752                        if (outActivities != null) {
19753                            outActivities.add(pa.mPref.mComponent);
19754                        }
19755                    }
19756                }
19757            }
19758        }
19759
19760        return num;
19761    }
19762
19763    @Override
19764    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19765            int userId) {
19766        int callingUid = Binder.getCallingUid();
19767        if (callingUid != Process.SYSTEM_UID) {
19768            throw new SecurityException(
19769                    "addPersistentPreferredActivity can only be run by the system");
19770        }
19771        if (filter.countActions() == 0) {
19772            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19773            return;
19774        }
19775        synchronized (mPackages) {
19776            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19777                    ":");
19778            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19779            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19780                    new PersistentPreferredActivity(filter, activity));
19781            scheduleWritePackageRestrictionsLocked(userId);
19782            postPreferredActivityChangedBroadcast(userId);
19783        }
19784    }
19785
19786    @Override
19787    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19788        int callingUid = Binder.getCallingUid();
19789        if (callingUid != Process.SYSTEM_UID) {
19790            throw new SecurityException(
19791                    "clearPackagePersistentPreferredActivities can only be run by the system");
19792        }
19793        ArrayList<PersistentPreferredActivity> removed = null;
19794        boolean changed = false;
19795        synchronized (mPackages) {
19796            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19797                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19798                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19799                        .valueAt(i);
19800                if (userId != thisUserId) {
19801                    continue;
19802                }
19803                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19804                while (it.hasNext()) {
19805                    PersistentPreferredActivity ppa = it.next();
19806                    // Mark entry for removal only if it matches the package name.
19807                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19808                        if (removed == null) {
19809                            removed = new ArrayList<PersistentPreferredActivity>();
19810                        }
19811                        removed.add(ppa);
19812                    }
19813                }
19814                if (removed != null) {
19815                    for (int j=0; j<removed.size(); j++) {
19816                        PersistentPreferredActivity ppa = removed.get(j);
19817                        ppir.removeFilter(ppa);
19818                    }
19819                    changed = true;
19820                }
19821            }
19822
19823            if (changed) {
19824                scheduleWritePackageRestrictionsLocked(userId);
19825                postPreferredActivityChangedBroadcast(userId);
19826            }
19827        }
19828    }
19829
19830    /**
19831     * Common machinery for picking apart a restored XML blob and passing
19832     * it to a caller-supplied functor to be applied to the running system.
19833     */
19834    private void restoreFromXml(XmlPullParser parser, int userId,
19835            String expectedStartTag, BlobXmlRestorer functor)
19836            throws IOException, XmlPullParserException {
19837        int type;
19838        while ((type = parser.next()) != XmlPullParser.START_TAG
19839                && type != XmlPullParser.END_DOCUMENT) {
19840        }
19841        if (type != XmlPullParser.START_TAG) {
19842            // oops didn't find a start tag?!
19843            if (DEBUG_BACKUP) {
19844                Slog.e(TAG, "Didn't find start tag during restore");
19845            }
19846            return;
19847        }
19848Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19849        // this is supposed to be TAG_PREFERRED_BACKUP
19850        if (!expectedStartTag.equals(parser.getName())) {
19851            if (DEBUG_BACKUP) {
19852                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19853            }
19854            return;
19855        }
19856
19857        // skip interfering stuff, then we're aligned with the backing implementation
19858        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19859Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19860        functor.apply(parser, userId);
19861    }
19862
19863    private interface BlobXmlRestorer {
19864        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19865    }
19866
19867    /**
19868     * Non-Binder method, support for the backup/restore mechanism: write the
19869     * full set of preferred activities in its canonical XML format.  Returns the
19870     * XML output as a byte array, or null if there is none.
19871     */
19872    @Override
19873    public byte[] getPreferredActivityBackup(int userId) {
19874        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19875            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19876        }
19877
19878        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19879        try {
19880            final XmlSerializer serializer = new FastXmlSerializer();
19881            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19882            serializer.startDocument(null, true);
19883            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19884
19885            synchronized (mPackages) {
19886                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19887            }
19888
19889            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19890            serializer.endDocument();
19891            serializer.flush();
19892        } catch (Exception e) {
19893            if (DEBUG_BACKUP) {
19894                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19895            }
19896            return null;
19897        }
19898
19899        return dataStream.toByteArray();
19900    }
19901
19902    @Override
19903    public void restorePreferredActivities(byte[] backup, int userId) {
19904        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19905            throw new SecurityException("Only the system may call restorePreferredActivities()");
19906        }
19907
19908        try {
19909            final XmlPullParser parser = Xml.newPullParser();
19910            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19911            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19912                    new BlobXmlRestorer() {
19913                        @Override
19914                        public void apply(XmlPullParser parser, int userId)
19915                                throws XmlPullParserException, IOException {
19916                            synchronized (mPackages) {
19917                                mSettings.readPreferredActivitiesLPw(parser, userId);
19918                            }
19919                        }
19920                    } );
19921        } catch (Exception e) {
19922            if (DEBUG_BACKUP) {
19923                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19924            }
19925        }
19926    }
19927
19928    /**
19929     * Non-Binder method, support for the backup/restore mechanism: write the
19930     * default browser (etc) settings in its canonical XML format.  Returns the default
19931     * browser XML representation as a byte array, or null if there is none.
19932     */
19933    @Override
19934    public byte[] getDefaultAppsBackup(int userId) {
19935        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19936            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19937        }
19938
19939        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19940        try {
19941            final XmlSerializer serializer = new FastXmlSerializer();
19942            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19943            serializer.startDocument(null, true);
19944            serializer.startTag(null, TAG_DEFAULT_APPS);
19945
19946            synchronized (mPackages) {
19947                mSettings.writeDefaultAppsLPr(serializer, userId);
19948            }
19949
19950            serializer.endTag(null, TAG_DEFAULT_APPS);
19951            serializer.endDocument();
19952            serializer.flush();
19953        } catch (Exception e) {
19954            if (DEBUG_BACKUP) {
19955                Slog.e(TAG, "Unable to write default apps for backup", e);
19956            }
19957            return null;
19958        }
19959
19960        return dataStream.toByteArray();
19961    }
19962
19963    @Override
19964    public void restoreDefaultApps(byte[] backup, int userId) {
19965        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19966            throw new SecurityException("Only the system may call restoreDefaultApps()");
19967        }
19968
19969        try {
19970            final XmlPullParser parser = Xml.newPullParser();
19971            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19972            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19973                    new BlobXmlRestorer() {
19974                        @Override
19975                        public void apply(XmlPullParser parser, int userId)
19976                                throws XmlPullParserException, IOException {
19977                            synchronized (mPackages) {
19978                                mSettings.readDefaultAppsLPw(parser, userId);
19979                            }
19980                        }
19981                    } );
19982        } catch (Exception e) {
19983            if (DEBUG_BACKUP) {
19984                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19985            }
19986        }
19987    }
19988
19989    @Override
19990    public byte[] getIntentFilterVerificationBackup(int userId) {
19991        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19992            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19993        }
19994
19995        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19996        try {
19997            final XmlSerializer serializer = new FastXmlSerializer();
19998            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19999            serializer.startDocument(null, true);
20000            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20001
20002            synchronized (mPackages) {
20003                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20004            }
20005
20006            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20007            serializer.endDocument();
20008            serializer.flush();
20009        } catch (Exception e) {
20010            if (DEBUG_BACKUP) {
20011                Slog.e(TAG, "Unable to write default apps for backup", e);
20012            }
20013            return null;
20014        }
20015
20016        return dataStream.toByteArray();
20017    }
20018
20019    @Override
20020    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20021        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20022            throw new SecurityException("Only the system may call restorePreferredActivities()");
20023        }
20024
20025        try {
20026            final XmlPullParser parser = Xml.newPullParser();
20027            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20028            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20029                    new BlobXmlRestorer() {
20030                        @Override
20031                        public void apply(XmlPullParser parser, int userId)
20032                                throws XmlPullParserException, IOException {
20033                            synchronized (mPackages) {
20034                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20035                                mSettings.writeLPr();
20036                            }
20037                        }
20038                    } );
20039        } catch (Exception e) {
20040            if (DEBUG_BACKUP) {
20041                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20042            }
20043        }
20044    }
20045
20046    @Override
20047    public byte[] getPermissionGrantBackup(int userId) {
20048        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20049            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20050        }
20051
20052        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20053        try {
20054            final XmlSerializer serializer = new FastXmlSerializer();
20055            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20056            serializer.startDocument(null, true);
20057            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20058
20059            synchronized (mPackages) {
20060                serializeRuntimePermissionGrantsLPr(serializer, userId);
20061            }
20062
20063            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20064            serializer.endDocument();
20065            serializer.flush();
20066        } catch (Exception e) {
20067            if (DEBUG_BACKUP) {
20068                Slog.e(TAG, "Unable to write default apps for backup", e);
20069            }
20070            return null;
20071        }
20072
20073        return dataStream.toByteArray();
20074    }
20075
20076    @Override
20077    public void restorePermissionGrants(byte[] backup, int userId) {
20078        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20079            throw new SecurityException("Only the system may call restorePermissionGrants()");
20080        }
20081
20082        try {
20083            final XmlPullParser parser = Xml.newPullParser();
20084            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20085            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20086                    new BlobXmlRestorer() {
20087                        @Override
20088                        public void apply(XmlPullParser parser, int userId)
20089                                throws XmlPullParserException, IOException {
20090                            synchronized (mPackages) {
20091                                processRestoredPermissionGrantsLPr(parser, userId);
20092                            }
20093                        }
20094                    } );
20095        } catch (Exception e) {
20096            if (DEBUG_BACKUP) {
20097                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20098            }
20099        }
20100    }
20101
20102    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20103            throws IOException {
20104        serializer.startTag(null, TAG_ALL_GRANTS);
20105
20106        final int N = mSettings.mPackages.size();
20107        for (int i = 0; i < N; i++) {
20108            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20109            boolean pkgGrantsKnown = false;
20110
20111            PermissionsState packagePerms = ps.getPermissionsState();
20112
20113            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20114                final int grantFlags = state.getFlags();
20115                // only look at grants that are not system/policy fixed
20116                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20117                    final boolean isGranted = state.isGranted();
20118                    // And only back up the user-twiddled state bits
20119                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20120                        final String packageName = mSettings.mPackages.keyAt(i);
20121                        if (!pkgGrantsKnown) {
20122                            serializer.startTag(null, TAG_GRANT);
20123                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20124                            pkgGrantsKnown = true;
20125                        }
20126
20127                        final boolean userSet =
20128                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20129                        final boolean userFixed =
20130                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20131                        final boolean revoke =
20132                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20133
20134                        serializer.startTag(null, TAG_PERMISSION);
20135                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20136                        if (isGranted) {
20137                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20138                        }
20139                        if (userSet) {
20140                            serializer.attribute(null, ATTR_USER_SET, "true");
20141                        }
20142                        if (userFixed) {
20143                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20144                        }
20145                        if (revoke) {
20146                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20147                        }
20148                        serializer.endTag(null, TAG_PERMISSION);
20149                    }
20150                }
20151            }
20152
20153            if (pkgGrantsKnown) {
20154                serializer.endTag(null, TAG_GRANT);
20155            }
20156        }
20157
20158        serializer.endTag(null, TAG_ALL_GRANTS);
20159    }
20160
20161    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20162            throws XmlPullParserException, IOException {
20163        String pkgName = null;
20164        int outerDepth = parser.getDepth();
20165        int type;
20166        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20167                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20168            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20169                continue;
20170            }
20171
20172            final String tagName = parser.getName();
20173            if (tagName.equals(TAG_GRANT)) {
20174                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20175                if (DEBUG_BACKUP) {
20176                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20177                }
20178            } else if (tagName.equals(TAG_PERMISSION)) {
20179
20180                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20181                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20182
20183                int newFlagSet = 0;
20184                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20185                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20186                }
20187                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20188                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20189                }
20190                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20191                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20192                }
20193                if (DEBUG_BACKUP) {
20194                    Slog.v(TAG, "  + Restoring grant:"
20195                            + " pkg=" + pkgName
20196                            + " perm=" + permName
20197                            + " granted=" + isGranted
20198                            + " bits=0x" + Integer.toHexString(newFlagSet));
20199                }
20200                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20201                if (ps != null) {
20202                    // Already installed so we apply the grant immediately
20203                    if (DEBUG_BACKUP) {
20204                        Slog.v(TAG, "        + already installed; applying");
20205                    }
20206                    PermissionsState perms = ps.getPermissionsState();
20207                    BasePermission bp =
20208                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20209                    if (bp != null) {
20210                        if (isGranted) {
20211                            perms.grantRuntimePermission(bp, userId);
20212                        }
20213                        if (newFlagSet != 0) {
20214                            perms.updatePermissionFlags(
20215                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20216                        }
20217                    }
20218                } else {
20219                    // Need to wait for post-restore install to apply the grant
20220                    if (DEBUG_BACKUP) {
20221                        Slog.v(TAG, "        - not yet installed; saving for later");
20222                    }
20223                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20224                            isGranted, newFlagSet, userId);
20225                }
20226            } else {
20227                PackageManagerService.reportSettingsProblem(Log.WARN,
20228                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20229                XmlUtils.skipCurrentTag(parser);
20230            }
20231        }
20232
20233        scheduleWriteSettingsLocked();
20234        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20235    }
20236
20237    @Override
20238    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20239            int sourceUserId, int targetUserId, int flags) {
20240        mContext.enforceCallingOrSelfPermission(
20241                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20242        int callingUid = Binder.getCallingUid();
20243        enforceOwnerRights(ownerPackage, callingUid);
20244        PackageManagerServiceUtils.enforceShellRestriction(
20245                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20246        if (intentFilter.countActions() == 0) {
20247            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20248            return;
20249        }
20250        synchronized (mPackages) {
20251            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20252                    ownerPackage, targetUserId, flags);
20253            CrossProfileIntentResolver resolver =
20254                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20255            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20256            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20257            if (existing != null) {
20258                int size = existing.size();
20259                for (int i = 0; i < size; i++) {
20260                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20261                        return;
20262                    }
20263                }
20264            }
20265            resolver.addFilter(newFilter);
20266            scheduleWritePackageRestrictionsLocked(sourceUserId);
20267        }
20268    }
20269
20270    @Override
20271    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20272        mContext.enforceCallingOrSelfPermission(
20273                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20274        final int callingUid = Binder.getCallingUid();
20275        enforceOwnerRights(ownerPackage, callingUid);
20276        PackageManagerServiceUtils.enforceShellRestriction(
20277                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20278        synchronized (mPackages) {
20279            CrossProfileIntentResolver resolver =
20280                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20281            ArraySet<CrossProfileIntentFilter> set =
20282                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20283            for (CrossProfileIntentFilter filter : set) {
20284                if (filter.getOwnerPackage().equals(ownerPackage)) {
20285                    resolver.removeFilter(filter);
20286                }
20287            }
20288            scheduleWritePackageRestrictionsLocked(sourceUserId);
20289        }
20290    }
20291
20292    // Enforcing that callingUid is owning pkg on userId
20293    private void enforceOwnerRights(String pkg, int callingUid) {
20294        // The system owns everything.
20295        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20296            return;
20297        }
20298        final int callingUserId = UserHandle.getUserId(callingUid);
20299        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20300        if (pi == null) {
20301            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20302                    + callingUserId);
20303        }
20304        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20305            throw new SecurityException("Calling uid " + callingUid
20306                    + " does not own package " + pkg);
20307        }
20308    }
20309
20310    @Override
20311    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20312        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20313            return null;
20314        }
20315        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20316    }
20317
20318    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20319        UserManagerService ums = UserManagerService.getInstance();
20320        if (ums != null) {
20321            final UserInfo parent = ums.getProfileParent(userId);
20322            final int launcherUid = (parent != null) ? parent.id : userId;
20323            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20324            if (launcherComponent != null) {
20325                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20326                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20327                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20328                        .setPackage(launcherComponent.getPackageName());
20329                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20330            }
20331        }
20332    }
20333
20334    /**
20335     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20336     * then reports the most likely home activity or null if there are more than one.
20337     */
20338    private ComponentName getDefaultHomeActivity(int userId) {
20339        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20340        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20341        if (cn != null) {
20342            return cn;
20343        }
20344
20345        // Find the launcher with the highest priority and return that component if there are no
20346        // other home activity with the same priority.
20347        int lastPriority = Integer.MIN_VALUE;
20348        ComponentName lastComponent = null;
20349        final int size = allHomeCandidates.size();
20350        for (int i = 0; i < size; i++) {
20351            final ResolveInfo ri = allHomeCandidates.get(i);
20352            if (ri.priority > lastPriority) {
20353                lastComponent = ri.activityInfo.getComponentName();
20354                lastPriority = ri.priority;
20355            } else if (ri.priority == lastPriority) {
20356                // Two components found with same priority.
20357                lastComponent = null;
20358            }
20359        }
20360        return lastComponent;
20361    }
20362
20363    private Intent getHomeIntent() {
20364        Intent intent = new Intent(Intent.ACTION_MAIN);
20365        intent.addCategory(Intent.CATEGORY_HOME);
20366        intent.addCategory(Intent.CATEGORY_DEFAULT);
20367        return intent;
20368    }
20369
20370    private IntentFilter getHomeFilter() {
20371        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20372        filter.addCategory(Intent.CATEGORY_HOME);
20373        filter.addCategory(Intent.CATEGORY_DEFAULT);
20374        return filter;
20375    }
20376
20377    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20378            int userId) {
20379        Intent intent  = getHomeIntent();
20380        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20381                PackageManager.GET_META_DATA, userId);
20382        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20383                true, false, false, userId);
20384
20385        allHomeCandidates.clear();
20386        if (list != null) {
20387            for (ResolveInfo ri : list) {
20388                allHomeCandidates.add(ri);
20389            }
20390        }
20391        return (preferred == null || preferred.activityInfo == null)
20392                ? null
20393                : new ComponentName(preferred.activityInfo.packageName,
20394                        preferred.activityInfo.name);
20395    }
20396
20397    @Override
20398    public void setHomeActivity(ComponentName comp, int userId) {
20399        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20400            return;
20401        }
20402        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20403        getHomeActivitiesAsUser(homeActivities, userId);
20404
20405        boolean found = false;
20406
20407        final int size = homeActivities.size();
20408        final ComponentName[] set = new ComponentName[size];
20409        for (int i = 0; i < size; i++) {
20410            final ResolveInfo candidate = homeActivities.get(i);
20411            final ActivityInfo info = candidate.activityInfo;
20412            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20413            set[i] = activityName;
20414            if (!found && activityName.equals(comp)) {
20415                found = true;
20416            }
20417        }
20418        if (!found) {
20419            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20420                    + userId);
20421        }
20422        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20423                set, comp, userId);
20424    }
20425
20426    private @Nullable String getSetupWizardPackageName() {
20427        final Intent intent = new Intent(Intent.ACTION_MAIN);
20428        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20429
20430        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20431                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20432                        | MATCH_DISABLED_COMPONENTS,
20433                UserHandle.myUserId());
20434        if (matches.size() == 1) {
20435            return matches.get(0).getComponentInfo().packageName;
20436        } else {
20437            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20438                    + ": matches=" + matches);
20439            return null;
20440        }
20441    }
20442
20443    private @Nullable String getStorageManagerPackageName() {
20444        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20445
20446        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20447                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20448                        | MATCH_DISABLED_COMPONENTS,
20449                UserHandle.myUserId());
20450        if (matches.size() == 1) {
20451            return matches.get(0).getComponentInfo().packageName;
20452        } else {
20453            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20454                    + matches.size() + ": matches=" + matches);
20455            return null;
20456        }
20457    }
20458
20459    @Override
20460    public String getSystemTextClassifierPackageName() {
20461        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20462    }
20463
20464    @Override
20465    public void setApplicationEnabledSetting(String appPackageName,
20466            int newState, int flags, int userId, String callingPackage) {
20467        if (!sUserManager.exists(userId)) return;
20468        if (callingPackage == null) {
20469            callingPackage = Integer.toString(Binder.getCallingUid());
20470        }
20471        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20472    }
20473
20474    @Override
20475    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20476        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20477        synchronized (mPackages) {
20478            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20479            if (pkgSetting != null) {
20480                pkgSetting.setUpdateAvailable(updateAvailable);
20481            }
20482        }
20483    }
20484
20485    @Override
20486    public void setComponentEnabledSetting(ComponentName componentName,
20487            int newState, int flags, int userId) {
20488        if (!sUserManager.exists(userId)) return;
20489        setEnabledSetting(componentName.getPackageName(),
20490                componentName.getClassName(), newState, flags, userId, null);
20491    }
20492
20493    private void setEnabledSetting(final String packageName, String className, int newState,
20494            final int flags, int userId, String callingPackage) {
20495        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20496              || newState == COMPONENT_ENABLED_STATE_ENABLED
20497              || newState == COMPONENT_ENABLED_STATE_DISABLED
20498              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20499              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20500            throw new IllegalArgumentException("Invalid new component state: "
20501                    + newState);
20502        }
20503        PackageSetting pkgSetting;
20504        final int callingUid = Binder.getCallingUid();
20505        final int permission;
20506        if (callingUid == Process.SYSTEM_UID) {
20507            permission = PackageManager.PERMISSION_GRANTED;
20508        } else {
20509            permission = mContext.checkCallingOrSelfPermission(
20510                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20511        }
20512        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20513                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20514        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20515        boolean sendNow = false;
20516        boolean isApp = (className == null);
20517        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20518        String componentName = isApp ? packageName : className;
20519        int packageUid = -1;
20520        ArrayList<String> components;
20521
20522        // reader
20523        synchronized (mPackages) {
20524            pkgSetting = mSettings.mPackages.get(packageName);
20525            if (pkgSetting == null) {
20526                if (!isCallerInstantApp) {
20527                    if (className == null) {
20528                        throw new IllegalArgumentException("Unknown package: " + packageName);
20529                    }
20530                    throw new IllegalArgumentException(
20531                            "Unknown component: " + packageName + "/" + className);
20532                } else {
20533                    // throw SecurityException to prevent leaking package information
20534                    throw new SecurityException(
20535                            "Attempt to change component state; "
20536                            + "pid=" + Binder.getCallingPid()
20537                            + ", uid=" + callingUid
20538                            + (className == null
20539                                    ? ", package=" + packageName
20540                                    : ", component=" + packageName + "/" + className));
20541                }
20542            }
20543        }
20544
20545        // Limit who can change which apps
20546        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20547            // Don't allow apps that don't have permission to modify other apps
20548            if (!allowedByPermission
20549                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20550                throw new SecurityException(
20551                        "Attempt to change component state; "
20552                        + "pid=" + Binder.getCallingPid()
20553                        + ", uid=" + callingUid
20554                        + (className == null
20555                                ? ", package=" + packageName
20556                                : ", component=" + packageName + "/" + className));
20557            }
20558            // Don't allow changing protected packages.
20559            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20560                throw new SecurityException("Cannot disable a protected package: " + packageName);
20561            }
20562        }
20563
20564        synchronized (mPackages) {
20565            if (callingUid == Process.SHELL_UID
20566                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20567                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20568                // unless it is a test package.
20569                int oldState = pkgSetting.getEnabled(userId);
20570                if (className == null
20571                        &&
20572                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20573                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20574                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20575                        &&
20576                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20577                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20578                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20579                    // ok
20580                } else {
20581                    throw new SecurityException(
20582                            "Shell cannot change component state for " + packageName + "/"
20583                                    + className + " to " + newState);
20584                }
20585            }
20586        }
20587        if (className == null) {
20588            // We're dealing with an application/package level state change
20589            synchronized (mPackages) {
20590                if (pkgSetting.getEnabled(userId) == newState) {
20591                    // Nothing to do
20592                    return;
20593                }
20594            }
20595            // If we're enabling a system stub, there's a little more work to do.
20596            // Prior to enabling the package, we need to decompress the APK(s) to the
20597            // data partition and then replace the version on the system partition.
20598            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20599            final boolean isSystemStub = deletedPkg.isStub
20600                    && deletedPkg.isSystem();
20601            if (isSystemStub
20602                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20603                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20604                final File codePath = decompressPackage(deletedPkg);
20605                if (codePath == null) {
20606                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20607                    return;
20608                }
20609                // TODO remove direct parsing of the package object during internal cleanup
20610                // of scan package
20611                // We need to call parse directly here for no other reason than we need
20612                // the new package in order to disable the old one [we use the information
20613                // for some internal optimization to optionally create a new package setting
20614                // object on replace]. However, we can't get the package from the scan
20615                // because the scan modifies live structures and we need to remove the
20616                // old [system] package from the system before a scan can be attempted.
20617                // Once scan is indempotent we can remove this parse and use the package
20618                // object we scanned, prior to adding it to package settings.
20619                final PackageParser pp = new PackageParser();
20620                pp.setSeparateProcesses(mSeparateProcesses);
20621                pp.setDisplayMetrics(mMetrics);
20622                pp.setCallback(mPackageParserCallback);
20623                final PackageParser.Package tmpPkg;
20624                try {
20625                    final @ParseFlags int parseFlags = mDefParseFlags
20626                            | PackageParser.PARSE_MUST_BE_APK
20627                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20628                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20629                } catch (PackageParserException e) {
20630                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20631                    return;
20632                }
20633                synchronized (mInstallLock) {
20634                    // Disable the stub and remove any package entries
20635                    removePackageLI(deletedPkg, true);
20636                    synchronized (mPackages) {
20637                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20638                    }
20639                    final PackageParser.Package pkg;
20640                    try (PackageFreezer freezer =
20641                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20642                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20643                                | PackageParser.PARSE_ENFORCE_CODE;
20644                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20645                                0 /*currentTime*/, null /*user*/);
20646                        prepareAppDataAfterInstallLIF(pkg);
20647                        synchronized (mPackages) {
20648                            try {
20649                                updateSharedLibrariesLPr(pkg, null);
20650                            } catch (PackageManagerException e) {
20651                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20652                            }
20653                            mPermissionManager.updatePermissions(
20654                                    pkg.packageName, pkg, true, mPackages.values(),
20655                                    mPermissionCallback);
20656                            mSettings.writeLPr();
20657                        }
20658                    } catch (PackageManagerException e) {
20659                        // Whoops! Something went wrong; try to roll back to the stub
20660                        Slog.w(TAG, "Failed to install compressed system package:"
20661                                + pkgSetting.name, e);
20662                        // Remove the failed install
20663                        removeCodePathLI(codePath);
20664
20665                        // Install the system package
20666                        try (PackageFreezer freezer =
20667                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20668                            synchronized (mPackages) {
20669                                // NOTE: The system package always needs to be enabled; even
20670                                // if it's for a compressed stub. If we don't, installing the
20671                                // system package fails during scan [scanning checks the disabled
20672                                // packages]. We will reverse this later, after we've "installed"
20673                                // the stub.
20674                                // This leaves us in a fragile state; the stub should never be
20675                                // enabled, so, cross your fingers and hope nothing goes wrong
20676                                // until we can disable the package later.
20677                                enableSystemPackageLPw(deletedPkg);
20678                            }
20679                            installPackageFromSystemLIF(deletedPkg.codePath,
20680                                    false /*isPrivileged*/, null /*allUserHandles*/,
20681                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20682                                    true /*writeSettings*/);
20683                        } catch (PackageManagerException pme) {
20684                            Slog.w(TAG, "Failed to restore system package:"
20685                                    + deletedPkg.packageName, pme);
20686                        } finally {
20687                            synchronized (mPackages) {
20688                                mSettings.disableSystemPackageLPw(
20689                                        deletedPkg.packageName, true /*replaced*/);
20690                                mSettings.writeLPr();
20691                            }
20692                        }
20693                        return;
20694                    }
20695                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20696                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20697                    mDexManager.notifyPackageUpdated(pkg.packageName,
20698                            pkg.baseCodePath, pkg.splitCodePaths);
20699                }
20700            }
20701            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20702                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20703                // Don't care about who enables an app.
20704                callingPackage = null;
20705            }
20706            synchronized (mPackages) {
20707                pkgSetting.setEnabled(newState, userId, callingPackage);
20708            }
20709        } else {
20710            synchronized (mPackages) {
20711                // We're dealing with a component level state change
20712                // First, verify that this is a valid class name.
20713                PackageParser.Package pkg = pkgSetting.pkg;
20714                if (pkg == null || !pkg.hasComponentClassName(className)) {
20715                    if (pkg != null &&
20716                            pkg.applicationInfo.targetSdkVersion >=
20717                                    Build.VERSION_CODES.JELLY_BEAN) {
20718                        throw new IllegalArgumentException("Component class " + className
20719                                + " does not exist in " + packageName);
20720                    } else {
20721                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20722                                + className + " does not exist in " + packageName);
20723                    }
20724                }
20725                switch (newState) {
20726                    case COMPONENT_ENABLED_STATE_ENABLED:
20727                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20728                            return;
20729                        }
20730                        break;
20731                    case COMPONENT_ENABLED_STATE_DISABLED:
20732                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20733                            return;
20734                        }
20735                        break;
20736                    case COMPONENT_ENABLED_STATE_DEFAULT:
20737                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20738                            return;
20739                        }
20740                        break;
20741                    default:
20742                        Slog.e(TAG, "Invalid new component state: " + newState);
20743                        return;
20744                }
20745            }
20746        }
20747        synchronized (mPackages) {
20748            scheduleWritePackageRestrictionsLocked(userId);
20749            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20750            final long callingId = Binder.clearCallingIdentity();
20751            try {
20752                updateInstantAppInstallerLocked(packageName);
20753            } finally {
20754                Binder.restoreCallingIdentity(callingId);
20755            }
20756            components = mPendingBroadcasts.get(userId, packageName);
20757            final boolean newPackage = components == null;
20758            if (newPackage) {
20759                components = new ArrayList<String>();
20760            }
20761            if (!components.contains(componentName)) {
20762                components.add(componentName);
20763            }
20764            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20765                sendNow = true;
20766                // Purge entry from pending broadcast list if another one exists already
20767                // since we are sending one right away.
20768                mPendingBroadcasts.remove(userId, packageName);
20769            } else {
20770                if (newPackage) {
20771                    mPendingBroadcasts.put(userId, packageName, components);
20772                }
20773                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20774                    // Schedule a message
20775                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20776                }
20777            }
20778        }
20779
20780        long callingId = Binder.clearCallingIdentity();
20781        try {
20782            if (sendNow) {
20783                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20784                sendPackageChangedBroadcast(packageName,
20785                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20786            }
20787        } finally {
20788            Binder.restoreCallingIdentity(callingId);
20789        }
20790    }
20791
20792    @Override
20793    public void flushPackageRestrictionsAsUser(int userId) {
20794        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20795            return;
20796        }
20797        if (!sUserManager.exists(userId)) {
20798            return;
20799        }
20800        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20801                false /* checkShell */, "flushPackageRestrictions");
20802        synchronized (mPackages) {
20803            mSettings.writePackageRestrictionsLPr(userId);
20804            mDirtyUsers.remove(userId);
20805            if (mDirtyUsers.isEmpty()) {
20806                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20807            }
20808        }
20809    }
20810
20811    private void sendPackageChangedBroadcast(String packageName,
20812            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20813        if (DEBUG_INSTALL)
20814            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20815                    + componentNames);
20816        Bundle extras = new Bundle(4);
20817        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20818        String nameList[] = new String[componentNames.size()];
20819        componentNames.toArray(nameList);
20820        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20821        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20822        extras.putInt(Intent.EXTRA_UID, packageUid);
20823        // If this is not reporting a change of the overall package, then only send it
20824        // to registered receivers.  We don't want to launch a swath of apps for every
20825        // little component state change.
20826        final int flags = !componentNames.contains(packageName)
20827                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20828        final int userId = UserHandle.getUserId(packageUid);
20829        final boolean isInstantApp = isInstantApp(packageName, userId);
20830        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20831        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20832        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20833                userIds, instantUserIds);
20834    }
20835
20836    @Override
20837    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20838        if (!sUserManager.exists(userId)) return;
20839        final int callingUid = Binder.getCallingUid();
20840        if (getInstantAppPackageName(callingUid) != null) {
20841            return;
20842        }
20843        final int permission = mContext.checkCallingOrSelfPermission(
20844                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20845        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20846        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20847                true /* requireFullPermission */, true /* checkShell */, "stop package");
20848        // writer
20849        synchronized (mPackages) {
20850            final PackageSetting ps = mSettings.mPackages.get(packageName);
20851            if (!filterAppAccessLPr(ps, callingUid, userId)
20852                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20853                            allowedByPermission, callingUid, userId)) {
20854                scheduleWritePackageRestrictionsLocked(userId);
20855            }
20856        }
20857    }
20858
20859    @Override
20860    public String getInstallerPackageName(String packageName) {
20861        final int callingUid = Binder.getCallingUid();
20862        synchronized (mPackages) {
20863            final PackageSetting ps = mSettings.mPackages.get(packageName);
20864            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20865                return null;
20866            }
20867            return mSettings.getInstallerPackageNameLPr(packageName);
20868        }
20869    }
20870
20871    public boolean isOrphaned(String packageName) {
20872        // reader
20873        synchronized (mPackages) {
20874            return mSettings.isOrphaned(packageName);
20875        }
20876    }
20877
20878    @Override
20879    public int getApplicationEnabledSetting(String packageName, int userId) {
20880        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20881        int callingUid = Binder.getCallingUid();
20882        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20883                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20884        // reader
20885        synchronized (mPackages) {
20886            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20887                return COMPONENT_ENABLED_STATE_DISABLED;
20888            }
20889            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20890        }
20891    }
20892
20893    @Override
20894    public int getComponentEnabledSetting(ComponentName component, int userId) {
20895        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20896        int callingUid = Binder.getCallingUid();
20897        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20898                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20899        synchronized (mPackages) {
20900            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20901                    component, TYPE_UNKNOWN, userId)) {
20902                return COMPONENT_ENABLED_STATE_DISABLED;
20903            }
20904            return mSettings.getComponentEnabledSettingLPr(component, userId);
20905        }
20906    }
20907
20908    @Override
20909    public void enterSafeMode() {
20910        enforceSystemOrRoot("Only the system can request entering safe mode");
20911
20912        if (!mSystemReady) {
20913            mSafeMode = true;
20914        }
20915    }
20916
20917    @Override
20918    public void systemReady() {
20919        enforceSystemOrRoot("Only the system can claim the system is ready");
20920
20921        mSystemReady = true;
20922        final ContentResolver resolver = mContext.getContentResolver();
20923        ContentObserver co = new ContentObserver(mHandler) {
20924            @Override
20925            public void onChange(boolean selfChange) {
20926                mWebInstantAppsDisabled =
20927                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20928                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20929            }
20930        };
20931        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20932                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20933                false, co, UserHandle.USER_SYSTEM);
20934        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20935                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20936        co.onChange(true);
20937
20938        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20939        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20940        // it is done.
20941        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20942            @Override
20943            public void onChange(boolean selfChange) {
20944                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20945                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20946                        oobEnabled == 1 ? "true" : "false");
20947            }
20948        };
20949        mContext.getContentResolver().registerContentObserver(
20950                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20951                UserHandle.USER_SYSTEM);
20952        // At boot, restore the value from the setting, which persists across reboot.
20953        privAppOobObserver.onChange(true);
20954
20955        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20956        // disabled after already being started.
20957        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20958                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20959
20960        // Read the compatibilty setting when the system is ready.
20961        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20962                mContext.getContentResolver(),
20963                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20964        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20965        if (DEBUG_SETTINGS) {
20966            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20967        }
20968
20969        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20970
20971        synchronized (mPackages) {
20972            // Verify that all of the preferred activity components actually
20973            // exist.  It is possible for applications to be updated and at
20974            // that point remove a previously declared activity component that
20975            // had been set as a preferred activity.  We try to clean this up
20976            // the next time we encounter that preferred activity, but it is
20977            // possible for the user flow to never be able to return to that
20978            // situation so here we do a sanity check to make sure we haven't
20979            // left any junk around.
20980            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20981            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20982                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20983                removed.clear();
20984                for (PreferredActivity pa : pir.filterSet()) {
20985                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20986                        removed.add(pa);
20987                    }
20988                }
20989                if (removed.size() > 0) {
20990                    for (int r=0; r<removed.size(); r++) {
20991                        PreferredActivity pa = removed.get(r);
20992                        Slog.w(TAG, "Removing dangling preferred activity: "
20993                                + pa.mPref.mComponent);
20994                        pir.removeFilter(pa);
20995                    }
20996                    mSettings.writePackageRestrictionsLPr(
20997                            mSettings.mPreferredActivities.keyAt(i));
20998                }
20999            }
21000
21001            for (int userId : UserManagerService.getInstance().getUserIds()) {
21002                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21003                    grantPermissionsUserIds = ArrayUtils.appendInt(
21004                            grantPermissionsUserIds, userId);
21005                }
21006            }
21007        }
21008        sUserManager.systemReady();
21009        // If we upgraded grant all default permissions before kicking off.
21010        for (int userId : grantPermissionsUserIds) {
21011            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21012        }
21013
21014        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21015            // If we did not grant default permissions, we preload from this the
21016            // default permission exceptions lazily to ensure we don't hit the
21017            // disk on a new user creation.
21018            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21019        }
21020
21021        // Now that we've scanned all packages, and granted any default
21022        // permissions, ensure permissions are updated. Beware of dragons if you
21023        // try optimizing this.
21024        synchronized (mPackages) {
21025            mPermissionManager.updateAllPermissions(
21026                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21027                    mPermissionCallback);
21028        }
21029
21030        // Kick off any messages waiting for system ready
21031        if (mPostSystemReadyMessages != null) {
21032            for (Message msg : mPostSystemReadyMessages) {
21033                msg.sendToTarget();
21034            }
21035            mPostSystemReadyMessages = null;
21036        }
21037
21038        // Watch for external volumes that come and go over time
21039        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21040        storage.registerListener(mStorageListener);
21041
21042        mInstallerService.systemReady();
21043        mPackageDexOptimizer.systemReady();
21044
21045        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21046                StorageManagerInternal.class);
21047        StorageManagerInternal.addExternalStoragePolicy(
21048                new StorageManagerInternal.ExternalStorageMountPolicy() {
21049            @Override
21050            public int getMountMode(int uid, String packageName) {
21051                if (Process.isIsolated(uid)) {
21052                    return Zygote.MOUNT_EXTERNAL_NONE;
21053                }
21054                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21055                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21056                }
21057                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21058                    return Zygote.MOUNT_EXTERNAL_READ;
21059                }
21060                return Zygote.MOUNT_EXTERNAL_WRITE;
21061            }
21062
21063            @Override
21064            public boolean hasExternalStorage(int uid, String packageName) {
21065                return true;
21066            }
21067        });
21068
21069        // Now that we're mostly running, clean up stale users and apps
21070        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21071        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21072
21073        mPermissionManager.systemReady();
21074
21075        if (mInstantAppResolverConnection != null) {
21076            mContext.registerReceiver(new BroadcastReceiver() {
21077                @Override
21078                public void onReceive(Context context, Intent intent) {
21079                    mInstantAppResolverConnection.optimisticBind();
21080                    mContext.unregisterReceiver(this);
21081                }
21082            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21083        }
21084    }
21085
21086    public void waitForAppDataPrepared() {
21087        if (mPrepareAppDataFuture == null) {
21088            return;
21089        }
21090        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21091        mPrepareAppDataFuture = null;
21092    }
21093
21094    @Override
21095    public boolean isSafeMode() {
21096        // allow instant applications
21097        return mSafeMode;
21098    }
21099
21100    @Override
21101    public boolean hasSystemUidErrors() {
21102        // allow instant applications
21103        return mHasSystemUidErrors;
21104    }
21105
21106    static String arrayToString(int[] array) {
21107        StringBuffer buf = new StringBuffer(128);
21108        buf.append('[');
21109        if (array != null) {
21110            for (int i=0; i<array.length; i++) {
21111                if (i > 0) buf.append(", ");
21112                buf.append(array[i]);
21113            }
21114        }
21115        buf.append(']');
21116        return buf.toString();
21117    }
21118
21119    @Override
21120    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21121            FileDescriptor err, String[] args, ShellCallback callback,
21122            ResultReceiver resultReceiver) {
21123        (new PackageManagerShellCommand(this)).exec(
21124                this, in, out, err, args, callback, resultReceiver);
21125    }
21126
21127    @Override
21128    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21129        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21130
21131        DumpState dumpState = new DumpState();
21132        boolean fullPreferred = false;
21133        boolean checkin = false;
21134
21135        String packageName = null;
21136        ArraySet<String> permissionNames = null;
21137
21138        int opti = 0;
21139        while (opti < args.length) {
21140            String opt = args[opti];
21141            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21142                break;
21143            }
21144            opti++;
21145
21146            if ("-a".equals(opt)) {
21147                // Right now we only know how to print all.
21148            } else if ("-h".equals(opt)) {
21149                pw.println("Package manager dump options:");
21150                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21151                pw.println("    --checkin: dump for a checkin");
21152                pw.println("    -f: print details of intent filters");
21153                pw.println("    -h: print this help");
21154                pw.println("  cmd may be one of:");
21155                pw.println("    l[ibraries]: list known shared libraries");
21156                pw.println("    f[eatures]: list device features");
21157                pw.println("    k[eysets]: print known keysets");
21158                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21159                pw.println("    perm[issions]: dump permissions");
21160                pw.println("    permission [name ...]: dump declaration and use of given permission");
21161                pw.println("    pref[erred]: print preferred package settings");
21162                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21163                pw.println("    prov[iders]: dump content providers");
21164                pw.println("    p[ackages]: dump installed packages");
21165                pw.println("    s[hared-users]: dump shared user IDs");
21166                pw.println("    m[essages]: print collected runtime messages");
21167                pw.println("    v[erifiers]: print package verifier info");
21168                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21169                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21170                pw.println("    version: print database version info");
21171                pw.println("    write: write current settings now");
21172                pw.println("    installs: details about install sessions");
21173                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21174                pw.println("    dexopt: dump dexopt state");
21175                pw.println("    compiler-stats: dump compiler statistics");
21176                pw.println("    service-permissions: dump permissions required by services");
21177                pw.println("    <package.name>: info about given package");
21178                return;
21179            } else if ("--checkin".equals(opt)) {
21180                checkin = true;
21181            } else if ("-f".equals(opt)) {
21182                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21183            } else if ("--proto".equals(opt)) {
21184                dumpProto(fd);
21185                return;
21186            } else {
21187                pw.println("Unknown argument: " + opt + "; use -h for help");
21188            }
21189        }
21190
21191        // Is the caller requesting to dump a particular piece of data?
21192        if (opti < args.length) {
21193            String cmd = args[opti];
21194            opti++;
21195            // Is this a package name?
21196            if ("android".equals(cmd) || cmd.contains(".")) {
21197                packageName = cmd;
21198                // When dumping a single package, we always dump all of its
21199                // filter information since the amount of data will be reasonable.
21200                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21201            } else if ("check-permission".equals(cmd)) {
21202                if (opti >= args.length) {
21203                    pw.println("Error: check-permission missing permission argument");
21204                    return;
21205                }
21206                String perm = args[opti];
21207                opti++;
21208                if (opti >= args.length) {
21209                    pw.println("Error: check-permission missing package argument");
21210                    return;
21211                }
21212
21213                String pkg = args[opti];
21214                opti++;
21215                int user = UserHandle.getUserId(Binder.getCallingUid());
21216                if (opti < args.length) {
21217                    try {
21218                        user = Integer.parseInt(args[opti]);
21219                    } catch (NumberFormatException e) {
21220                        pw.println("Error: check-permission user argument is not a number: "
21221                                + args[opti]);
21222                        return;
21223                    }
21224                }
21225
21226                // Normalize package name to handle renamed packages and static libs
21227                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21228
21229                pw.println(checkPermission(perm, pkg, user));
21230                return;
21231            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21232                dumpState.setDump(DumpState.DUMP_LIBS);
21233            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21234                dumpState.setDump(DumpState.DUMP_FEATURES);
21235            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21236                if (opti >= args.length) {
21237                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21238                            | DumpState.DUMP_SERVICE_RESOLVERS
21239                            | DumpState.DUMP_RECEIVER_RESOLVERS
21240                            | DumpState.DUMP_CONTENT_RESOLVERS);
21241                } else {
21242                    while (opti < args.length) {
21243                        String name = args[opti];
21244                        if ("a".equals(name) || "activity".equals(name)) {
21245                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21246                        } else if ("s".equals(name) || "service".equals(name)) {
21247                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21248                        } else if ("r".equals(name) || "receiver".equals(name)) {
21249                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21250                        } else if ("c".equals(name) || "content".equals(name)) {
21251                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21252                        } else {
21253                            pw.println("Error: unknown resolver table type: " + name);
21254                            return;
21255                        }
21256                        opti++;
21257                    }
21258                }
21259            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21260                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21261            } else if ("permission".equals(cmd)) {
21262                if (opti >= args.length) {
21263                    pw.println("Error: permission requires permission name");
21264                    return;
21265                }
21266                permissionNames = new ArraySet<>();
21267                while (opti < args.length) {
21268                    permissionNames.add(args[opti]);
21269                    opti++;
21270                }
21271                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21272                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21273            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21274                dumpState.setDump(DumpState.DUMP_PREFERRED);
21275            } else if ("preferred-xml".equals(cmd)) {
21276                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21277                if (opti < args.length && "--full".equals(args[opti])) {
21278                    fullPreferred = true;
21279                    opti++;
21280                }
21281            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21282                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21283            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21284                dumpState.setDump(DumpState.DUMP_PACKAGES);
21285            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21286                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21287            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21288                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21289            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21290                dumpState.setDump(DumpState.DUMP_MESSAGES);
21291            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21292                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21293            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21294                    || "intent-filter-verifiers".equals(cmd)) {
21295                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21296            } else if ("version".equals(cmd)) {
21297                dumpState.setDump(DumpState.DUMP_VERSION);
21298            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21299                dumpState.setDump(DumpState.DUMP_KEYSETS);
21300            } else if ("installs".equals(cmd)) {
21301                dumpState.setDump(DumpState.DUMP_INSTALLS);
21302            } else if ("frozen".equals(cmd)) {
21303                dumpState.setDump(DumpState.DUMP_FROZEN);
21304            } else if ("volumes".equals(cmd)) {
21305                dumpState.setDump(DumpState.DUMP_VOLUMES);
21306            } else if ("dexopt".equals(cmd)) {
21307                dumpState.setDump(DumpState.DUMP_DEXOPT);
21308            } else if ("compiler-stats".equals(cmd)) {
21309                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21310            } else if ("changes".equals(cmd)) {
21311                dumpState.setDump(DumpState.DUMP_CHANGES);
21312            } else if ("service-permissions".equals(cmd)) {
21313                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21314            } else if ("write".equals(cmd)) {
21315                synchronized (mPackages) {
21316                    mSettings.writeLPr();
21317                    pw.println("Settings written.");
21318                    return;
21319                }
21320            }
21321        }
21322
21323        if (checkin) {
21324            pw.println("vers,1");
21325        }
21326
21327        // reader
21328        synchronized (mPackages) {
21329            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21330                if (!checkin) {
21331                    if (dumpState.onTitlePrinted())
21332                        pw.println();
21333                    pw.println("Database versions:");
21334                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21335                }
21336            }
21337
21338            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21339                if (!checkin) {
21340                    if (dumpState.onTitlePrinted())
21341                        pw.println();
21342                    pw.println("Verifiers:");
21343                    pw.print("  Required: ");
21344                    pw.print(mRequiredVerifierPackage);
21345                    pw.print(" (uid=");
21346                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21347                            UserHandle.USER_SYSTEM));
21348                    pw.println(")");
21349                } else if (mRequiredVerifierPackage != null) {
21350                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21351                    pw.print(",");
21352                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21353                            UserHandle.USER_SYSTEM));
21354                }
21355            }
21356
21357            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21358                    packageName == null) {
21359                if (mIntentFilterVerifierComponent != null) {
21360                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21361                    if (!checkin) {
21362                        if (dumpState.onTitlePrinted())
21363                            pw.println();
21364                        pw.println("Intent Filter Verifier:");
21365                        pw.print("  Using: ");
21366                        pw.print(verifierPackageName);
21367                        pw.print(" (uid=");
21368                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21369                                UserHandle.USER_SYSTEM));
21370                        pw.println(")");
21371                    } else if (verifierPackageName != null) {
21372                        pw.print("ifv,"); pw.print(verifierPackageName);
21373                        pw.print(",");
21374                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21375                                UserHandle.USER_SYSTEM));
21376                    }
21377                } else {
21378                    pw.println();
21379                    pw.println("No Intent Filter Verifier available!");
21380                }
21381            }
21382
21383            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21384                boolean printedHeader = false;
21385                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21386                while (it.hasNext()) {
21387                    String libName = it.next();
21388                    LongSparseArray<SharedLibraryEntry> versionedLib
21389                            = mSharedLibraries.get(libName);
21390                    if (versionedLib == null) {
21391                        continue;
21392                    }
21393                    final int versionCount = versionedLib.size();
21394                    for (int i = 0; i < versionCount; i++) {
21395                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21396                        if (!checkin) {
21397                            if (!printedHeader) {
21398                                if (dumpState.onTitlePrinted())
21399                                    pw.println();
21400                                pw.println("Libraries:");
21401                                printedHeader = true;
21402                            }
21403                            pw.print("  ");
21404                        } else {
21405                            pw.print("lib,");
21406                        }
21407                        pw.print(libEntry.info.getName());
21408                        if (libEntry.info.isStatic()) {
21409                            pw.print(" version=" + libEntry.info.getLongVersion());
21410                        }
21411                        if (!checkin) {
21412                            pw.print(" -> ");
21413                        }
21414                        if (libEntry.path != null) {
21415                            pw.print(" (jar) ");
21416                            pw.print(libEntry.path);
21417                        } else {
21418                            pw.print(" (apk) ");
21419                            pw.print(libEntry.apk);
21420                        }
21421                        pw.println();
21422                    }
21423                }
21424            }
21425
21426            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21427                if (dumpState.onTitlePrinted())
21428                    pw.println();
21429                if (!checkin) {
21430                    pw.println("Features:");
21431                }
21432
21433                synchronized (mAvailableFeatures) {
21434                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21435                        if (checkin) {
21436                            pw.print("feat,");
21437                            pw.print(feat.name);
21438                            pw.print(",");
21439                            pw.println(feat.version);
21440                        } else {
21441                            pw.print("  ");
21442                            pw.print(feat.name);
21443                            if (feat.version > 0) {
21444                                pw.print(" version=");
21445                                pw.print(feat.version);
21446                            }
21447                            pw.println();
21448                        }
21449                    }
21450                }
21451            }
21452
21453            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21454                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21455                        : "Activity Resolver Table:", "  ", packageName,
21456                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21457                    dumpState.setTitlePrinted(true);
21458                }
21459            }
21460            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21461                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21462                        : "Receiver Resolver Table:", "  ", packageName,
21463                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21464                    dumpState.setTitlePrinted(true);
21465                }
21466            }
21467            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21468                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21469                        : "Service Resolver Table:", "  ", packageName,
21470                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21471                    dumpState.setTitlePrinted(true);
21472                }
21473            }
21474            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21475                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21476                        : "Provider Resolver Table:", "  ", packageName,
21477                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21478                    dumpState.setTitlePrinted(true);
21479                }
21480            }
21481
21482            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21483                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21484                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21485                    int user = mSettings.mPreferredActivities.keyAt(i);
21486                    if (pir.dump(pw,
21487                            dumpState.getTitlePrinted()
21488                                ? "\nPreferred Activities User " + user + ":"
21489                                : "Preferred Activities User " + user + ":", "  ",
21490                            packageName, true, false)) {
21491                        dumpState.setTitlePrinted(true);
21492                    }
21493                }
21494            }
21495
21496            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21497                pw.flush();
21498                FileOutputStream fout = new FileOutputStream(fd);
21499                BufferedOutputStream str = new BufferedOutputStream(fout);
21500                XmlSerializer serializer = new FastXmlSerializer();
21501                try {
21502                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21503                    serializer.startDocument(null, true);
21504                    serializer.setFeature(
21505                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21506                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21507                    serializer.endDocument();
21508                    serializer.flush();
21509                } catch (IllegalArgumentException e) {
21510                    pw.println("Failed writing: " + e);
21511                } catch (IllegalStateException e) {
21512                    pw.println("Failed writing: " + e);
21513                } catch (IOException e) {
21514                    pw.println("Failed writing: " + e);
21515                }
21516            }
21517
21518            if (!checkin
21519                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21520                    && packageName == null) {
21521                pw.println();
21522                int count = mSettings.mPackages.size();
21523                if (count == 0) {
21524                    pw.println("No applications!");
21525                    pw.println();
21526                } else {
21527                    final String prefix = "  ";
21528                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21529                    if (allPackageSettings.size() == 0) {
21530                        pw.println("No domain preferred apps!");
21531                        pw.println();
21532                    } else {
21533                        pw.println("App verification status:");
21534                        pw.println();
21535                        count = 0;
21536                        for (PackageSetting ps : allPackageSettings) {
21537                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21538                            if (ivi == null || ivi.getPackageName() == null) continue;
21539                            pw.println(prefix + "Package: " + ivi.getPackageName());
21540                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21541                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21542                            pw.println();
21543                            count++;
21544                        }
21545                        if (count == 0) {
21546                            pw.println(prefix + "No app verification established.");
21547                            pw.println();
21548                        }
21549                        for (int userId : sUserManager.getUserIds()) {
21550                            pw.println("App linkages for user " + userId + ":");
21551                            pw.println();
21552                            count = 0;
21553                            for (PackageSetting ps : allPackageSettings) {
21554                                final long status = ps.getDomainVerificationStatusForUser(userId);
21555                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21556                                        && !DEBUG_DOMAIN_VERIFICATION) {
21557                                    continue;
21558                                }
21559                                pw.println(prefix + "Package: " + ps.name);
21560                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21561                                String statusStr = IntentFilterVerificationInfo.
21562                                        getStatusStringFromValue(status);
21563                                pw.println(prefix + "Status:  " + statusStr);
21564                                pw.println();
21565                                count++;
21566                            }
21567                            if (count == 0) {
21568                                pw.println(prefix + "No configured app linkages.");
21569                                pw.println();
21570                            }
21571                        }
21572                    }
21573                }
21574            }
21575
21576            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21577                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21578            }
21579
21580            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21581                boolean printedSomething = false;
21582                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21583                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21584                        continue;
21585                    }
21586                    if (!printedSomething) {
21587                        if (dumpState.onTitlePrinted())
21588                            pw.println();
21589                        pw.println("Registered ContentProviders:");
21590                        printedSomething = true;
21591                    }
21592                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21593                    pw.print("    "); pw.println(p.toString());
21594                }
21595                printedSomething = false;
21596                for (Map.Entry<String, PackageParser.Provider> entry :
21597                        mProvidersByAuthority.entrySet()) {
21598                    PackageParser.Provider p = entry.getValue();
21599                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21600                        continue;
21601                    }
21602                    if (!printedSomething) {
21603                        if (dumpState.onTitlePrinted())
21604                            pw.println();
21605                        pw.println("ContentProvider Authorities:");
21606                        printedSomething = true;
21607                    }
21608                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21609                    pw.print("    "); pw.println(p.toString());
21610                    if (p.info != null && p.info.applicationInfo != null) {
21611                        final String appInfo = p.info.applicationInfo.toString();
21612                        pw.print("      applicationInfo="); pw.println(appInfo);
21613                    }
21614                }
21615            }
21616
21617            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21618                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21619            }
21620
21621            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21622                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21623            }
21624
21625            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21626                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21627            }
21628
21629            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21630                if (dumpState.onTitlePrinted()) pw.println();
21631                pw.println("Package Changes:");
21632                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21633                final int K = mChangedPackages.size();
21634                for (int i = 0; i < K; i++) {
21635                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21636                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21637                    final int N = changes.size();
21638                    if (N == 0) {
21639                        pw.print("    "); pw.println("No packages changed");
21640                    } else {
21641                        for (int j = 0; j < N; j++) {
21642                            final String pkgName = changes.valueAt(j);
21643                            final int sequenceNumber = changes.keyAt(j);
21644                            pw.print("    ");
21645                            pw.print("seq=");
21646                            pw.print(sequenceNumber);
21647                            pw.print(", package=");
21648                            pw.println(pkgName);
21649                        }
21650                    }
21651                }
21652            }
21653
21654            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21655                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21656            }
21657
21658            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21659                // XXX should handle packageName != null by dumping only install data that
21660                // the given package is involved with.
21661                if (dumpState.onTitlePrinted()) pw.println();
21662
21663                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21664                ipw.println();
21665                ipw.println("Frozen packages:");
21666                ipw.increaseIndent();
21667                if (mFrozenPackages.size() == 0) {
21668                    ipw.println("(none)");
21669                } else {
21670                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21671                        ipw.println(mFrozenPackages.valueAt(i));
21672                    }
21673                }
21674                ipw.decreaseIndent();
21675            }
21676
21677            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21678                if (dumpState.onTitlePrinted()) pw.println();
21679
21680                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21681                ipw.println();
21682                ipw.println("Loaded volumes:");
21683                ipw.increaseIndent();
21684                if (mLoadedVolumes.size() == 0) {
21685                    ipw.println("(none)");
21686                } else {
21687                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21688                        ipw.println(mLoadedVolumes.valueAt(i));
21689                    }
21690                }
21691                ipw.decreaseIndent();
21692            }
21693
21694            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21695                    && packageName == null) {
21696                if (dumpState.onTitlePrinted()) pw.println();
21697                pw.println("Service permissions:");
21698
21699                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21700                while (filterIterator.hasNext()) {
21701                    final ServiceIntentInfo info = filterIterator.next();
21702                    final ServiceInfo serviceInfo = info.service.info;
21703                    final String permission = serviceInfo.permission;
21704                    if (permission != null) {
21705                        pw.print("    ");
21706                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21707                        pw.print(": ");
21708                        pw.println(permission);
21709                    }
21710                }
21711            }
21712
21713            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21714                if (dumpState.onTitlePrinted()) pw.println();
21715                dumpDexoptStateLPr(pw, packageName);
21716            }
21717
21718            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21719                if (dumpState.onTitlePrinted()) pw.println();
21720                dumpCompilerStatsLPr(pw, packageName);
21721            }
21722
21723            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21724                if (dumpState.onTitlePrinted()) pw.println();
21725                mSettings.dumpReadMessagesLPr(pw, dumpState);
21726
21727                pw.println();
21728                pw.println("Package warning messages:");
21729                dumpCriticalInfo(pw, null);
21730            }
21731
21732            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21733                dumpCriticalInfo(pw, "msg,");
21734            }
21735        }
21736
21737        // PackageInstaller should be called outside of mPackages lock
21738        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21739            // XXX should handle packageName != null by dumping only install data that
21740            // the given package is involved with.
21741            if (dumpState.onTitlePrinted()) pw.println();
21742            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21743        }
21744    }
21745
21746    private void dumpProto(FileDescriptor fd) {
21747        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21748
21749        synchronized (mPackages) {
21750            final long requiredVerifierPackageToken =
21751                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21752            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21753            proto.write(
21754                    PackageServiceDumpProto.PackageShortProto.UID,
21755                    getPackageUid(
21756                            mRequiredVerifierPackage,
21757                            MATCH_DEBUG_TRIAGED_MISSING,
21758                            UserHandle.USER_SYSTEM));
21759            proto.end(requiredVerifierPackageToken);
21760
21761            if (mIntentFilterVerifierComponent != null) {
21762                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21763                final long verifierPackageToken =
21764                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21765                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21766                proto.write(
21767                        PackageServiceDumpProto.PackageShortProto.UID,
21768                        getPackageUid(
21769                                verifierPackageName,
21770                                MATCH_DEBUG_TRIAGED_MISSING,
21771                                UserHandle.USER_SYSTEM));
21772                proto.end(verifierPackageToken);
21773            }
21774
21775            dumpSharedLibrariesProto(proto);
21776            dumpFeaturesProto(proto);
21777            mSettings.dumpPackagesProto(proto);
21778            mSettings.dumpSharedUsersProto(proto);
21779            dumpCriticalInfo(proto);
21780        }
21781        proto.flush();
21782    }
21783
21784    private void dumpFeaturesProto(ProtoOutputStream proto) {
21785        synchronized (mAvailableFeatures) {
21786            final int count = mAvailableFeatures.size();
21787            for (int i = 0; i < count; i++) {
21788                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21789            }
21790        }
21791    }
21792
21793    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21794        final int count = mSharedLibraries.size();
21795        for (int i = 0; i < count; i++) {
21796            final String libName = mSharedLibraries.keyAt(i);
21797            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21798            if (versionedLib == null) {
21799                continue;
21800            }
21801            final int versionCount = versionedLib.size();
21802            for (int j = 0; j < versionCount; j++) {
21803                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21804                final long sharedLibraryToken =
21805                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21806                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21807                final boolean isJar = (libEntry.path != null);
21808                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21809                if (isJar) {
21810                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21811                } else {
21812                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21813                }
21814                proto.end(sharedLibraryToken);
21815            }
21816        }
21817    }
21818
21819    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21820        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21821        ipw.println();
21822        ipw.println("Dexopt state:");
21823        ipw.increaseIndent();
21824        Collection<PackageParser.Package> packages = null;
21825        if (packageName != null) {
21826            PackageParser.Package targetPackage = mPackages.get(packageName);
21827            if (targetPackage != null) {
21828                packages = Collections.singletonList(targetPackage);
21829            } else {
21830                ipw.println("Unable to find package: " + packageName);
21831                return;
21832            }
21833        } else {
21834            packages = mPackages.values();
21835        }
21836
21837        for (PackageParser.Package pkg : packages) {
21838            ipw.println("[" + pkg.packageName + "]");
21839            ipw.increaseIndent();
21840            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21841                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21842            ipw.decreaseIndent();
21843        }
21844    }
21845
21846    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21847        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21848        ipw.println();
21849        ipw.println("Compiler stats:");
21850        ipw.increaseIndent();
21851        Collection<PackageParser.Package> packages = null;
21852        if (packageName != null) {
21853            PackageParser.Package targetPackage = mPackages.get(packageName);
21854            if (targetPackage != null) {
21855                packages = Collections.singletonList(targetPackage);
21856            } else {
21857                ipw.println("Unable to find package: " + packageName);
21858                return;
21859            }
21860        } else {
21861            packages = mPackages.values();
21862        }
21863
21864        for (PackageParser.Package pkg : packages) {
21865            ipw.println("[" + pkg.packageName + "]");
21866            ipw.increaseIndent();
21867
21868            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21869            if (stats == null) {
21870                ipw.println("(No recorded stats)");
21871            } else {
21872                stats.dump(ipw);
21873            }
21874            ipw.decreaseIndent();
21875        }
21876    }
21877
21878    private String dumpDomainString(String packageName) {
21879        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21880                .getList();
21881        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21882
21883        ArraySet<String> result = new ArraySet<>();
21884        if (iviList.size() > 0) {
21885            for (IntentFilterVerificationInfo ivi : iviList) {
21886                for (String host : ivi.getDomains()) {
21887                    result.add(host);
21888                }
21889            }
21890        }
21891        if (filters != null && filters.size() > 0) {
21892            for (IntentFilter filter : filters) {
21893                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21894                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21895                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21896                    result.addAll(filter.getHostsList());
21897                }
21898            }
21899        }
21900
21901        StringBuilder sb = new StringBuilder(result.size() * 16);
21902        for (String domain : result) {
21903            if (sb.length() > 0) sb.append(" ");
21904            sb.append(domain);
21905        }
21906        return sb.toString();
21907    }
21908
21909    // ------- apps on sdcard specific code -------
21910    static final boolean DEBUG_SD_INSTALL = false;
21911
21912    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21913
21914    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21915
21916    private boolean mMediaMounted = false;
21917
21918    static String getEncryptKey() {
21919        try {
21920            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21921                    SD_ENCRYPTION_KEYSTORE_NAME);
21922            if (sdEncKey == null) {
21923                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21924                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21925                if (sdEncKey == null) {
21926                    Slog.e(TAG, "Failed to create encryption keys");
21927                    return null;
21928                }
21929            }
21930            return sdEncKey;
21931        } catch (NoSuchAlgorithmException nsae) {
21932            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21933            return null;
21934        } catch (IOException ioe) {
21935            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21936            return null;
21937        }
21938    }
21939
21940    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21941            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21942        final int size = infos.size();
21943        final String[] packageNames = new String[size];
21944        final int[] packageUids = new int[size];
21945        for (int i = 0; i < size; i++) {
21946            final ApplicationInfo info = infos.get(i);
21947            packageNames[i] = info.packageName;
21948            packageUids[i] = info.uid;
21949        }
21950        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21951                finishedReceiver);
21952    }
21953
21954    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21955            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21956        sendResourcesChangedBroadcast(mediaStatus, replacing,
21957                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21958    }
21959
21960    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21961            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21962        int size = pkgList.length;
21963        if (size > 0) {
21964            // Send broadcasts here
21965            Bundle extras = new Bundle();
21966            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21967            if (uidArr != null) {
21968                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21969            }
21970            if (replacing) {
21971                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21972            }
21973            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21974                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21975            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21976        }
21977    }
21978
21979    private void loadPrivatePackages(final VolumeInfo vol) {
21980        mHandler.post(new Runnable() {
21981            @Override
21982            public void run() {
21983                loadPrivatePackagesInner(vol);
21984            }
21985        });
21986    }
21987
21988    private void loadPrivatePackagesInner(VolumeInfo vol) {
21989        final String volumeUuid = vol.fsUuid;
21990        if (TextUtils.isEmpty(volumeUuid)) {
21991            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21992            return;
21993        }
21994
21995        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21996        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21997        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21998
21999        final VersionInfo ver;
22000        final List<PackageSetting> packages;
22001        synchronized (mPackages) {
22002            ver = mSettings.findOrCreateVersion(volumeUuid);
22003            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22004        }
22005
22006        for (PackageSetting ps : packages) {
22007            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22008            synchronized (mInstallLock) {
22009                final PackageParser.Package pkg;
22010                try {
22011                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22012                    loaded.add(pkg.applicationInfo);
22013
22014                } catch (PackageManagerException e) {
22015                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22016                }
22017
22018                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22019                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22020                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22021                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22022                }
22023            }
22024        }
22025
22026        // Reconcile app data for all started/unlocked users
22027        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22028        final UserManager um = mContext.getSystemService(UserManager.class);
22029        UserManagerInternal umInternal = getUserManagerInternal();
22030        for (UserInfo user : um.getUsers()) {
22031            final int flags;
22032            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22033                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22034            } else if (umInternal.isUserRunning(user.id)) {
22035                flags = StorageManager.FLAG_STORAGE_DE;
22036            } else {
22037                continue;
22038            }
22039
22040            try {
22041                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22042                synchronized (mInstallLock) {
22043                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22044                }
22045            } catch (IllegalStateException e) {
22046                // Device was probably ejected, and we'll process that event momentarily
22047                Slog.w(TAG, "Failed to prepare storage: " + e);
22048            }
22049        }
22050
22051        synchronized (mPackages) {
22052            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22053            if (sdkUpdated) {
22054                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22055                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22056            }
22057            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22058                    mPermissionCallback);
22059
22060            // Yay, everything is now upgraded
22061            ver.forceCurrent();
22062
22063            mSettings.writeLPr();
22064        }
22065
22066        for (PackageFreezer freezer : freezers) {
22067            freezer.close();
22068        }
22069
22070        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22071        sendResourcesChangedBroadcast(true, false, loaded, null);
22072        mLoadedVolumes.add(vol.getId());
22073    }
22074
22075    private void unloadPrivatePackages(final VolumeInfo vol) {
22076        mHandler.post(new Runnable() {
22077            @Override
22078            public void run() {
22079                unloadPrivatePackagesInner(vol);
22080            }
22081        });
22082    }
22083
22084    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22085        final String volumeUuid = vol.fsUuid;
22086        if (TextUtils.isEmpty(volumeUuid)) {
22087            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22088            return;
22089        }
22090
22091        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22092        synchronized (mInstallLock) {
22093        synchronized (mPackages) {
22094            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22095            for (PackageSetting ps : packages) {
22096                if (ps.pkg == null) continue;
22097
22098                final ApplicationInfo info = ps.pkg.applicationInfo;
22099                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22100                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22101
22102                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22103                        "unloadPrivatePackagesInner")) {
22104                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22105                            false, null)) {
22106                        unloaded.add(info);
22107                    } else {
22108                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22109                    }
22110                }
22111
22112                // Try very hard to release any references to this package
22113                // so we don't risk the system server being killed due to
22114                // open FDs
22115                AttributeCache.instance().removePackage(ps.name);
22116            }
22117
22118            mSettings.writeLPr();
22119        }
22120        }
22121
22122        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22123        sendResourcesChangedBroadcast(false, false, unloaded, null);
22124        mLoadedVolumes.remove(vol.getId());
22125
22126        // Try very hard to release any references to this path so we don't risk
22127        // the system server being killed due to open FDs
22128        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22129
22130        for (int i = 0; i < 3; i++) {
22131            System.gc();
22132            System.runFinalization();
22133        }
22134    }
22135
22136    private void assertPackageKnown(String volumeUuid, String packageName)
22137            throws PackageManagerException {
22138        synchronized (mPackages) {
22139            // Normalize package name to handle renamed packages
22140            packageName = normalizePackageNameLPr(packageName);
22141
22142            final PackageSetting ps = mSettings.mPackages.get(packageName);
22143            if (ps == null) {
22144                throw new PackageManagerException("Package " + packageName + " is unknown");
22145            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22146                throw new PackageManagerException(
22147                        "Package " + packageName + " found on unknown volume " + volumeUuid
22148                                + "; expected volume " + ps.volumeUuid);
22149            }
22150        }
22151    }
22152
22153    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22154            throws PackageManagerException {
22155        synchronized (mPackages) {
22156            // Normalize package name to handle renamed packages
22157            packageName = normalizePackageNameLPr(packageName);
22158
22159            final PackageSetting ps = mSettings.mPackages.get(packageName);
22160            if (ps == null) {
22161                throw new PackageManagerException("Package " + packageName + " is unknown");
22162            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22163                throw new PackageManagerException(
22164                        "Package " + packageName + " found on unknown volume " + volumeUuid
22165                                + "; expected volume " + ps.volumeUuid);
22166            } else if (!ps.getInstalled(userId)) {
22167                throw new PackageManagerException(
22168                        "Package " + packageName + " not installed for user " + userId);
22169            }
22170        }
22171    }
22172
22173    private List<String> collectAbsoluteCodePaths() {
22174        synchronized (mPackages) {
22175            List<String> codePaths = new ArrayList<>();
22176            final int packageCount = mSettings.mPackages.size();
22177            for (int i = 0; i < packageCount; i++) {
22178                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22179                codePaths.add(ps.codePath.getAbsolutePath());
22180            }
22181            return codePaths;
22182        }
22183    }
22184
22185    /**
22186     * Examine all apps present on given mounted volume, and destroy apps that
22187     * aren't expected, either due to uninstallation or reinstallation on
22188     * another volume.
22189     */
22190    private void reconcileApps(String volumeUuid) {
22191        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22192        List<File> filesToDelete = null;
22193
22194        final File[] files = FileUtils.listFilesOrEmpty(
22195                Environment.getDataAppDirectory(volumeUuid));
22196        for (File file : files) {
22197            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22198                    && !PackageInstallerService.isStageName(file.getName());
22199            if (!isPackage) {
22200                // Ignore entries which are not packages
22201                continue;
22202            }
22203
22204            String absolutePath = file.getAbsolutePath();
22205
22206            boolean pathValid = false;
22207            final int absoluteCodePathCount = absoluteCodePaths.size();
22208            for (int i = 0; i < absoluteCodePathCount; i++) {
22209                String absoluteCodePath = absoluteCodePaths.get(i);
22210                if (absolutePath.startsWith(absoluteCodePath)) {
22211                    pathValid = true;
22212                    break;
22213                }
22214            }
22215
22216            if (!pathValid) {
22217                if (filesToDelete == null) {
22218                    filesToDelete = new ArrayList<>();
22219                }
22220                filesToDelete.add(file);
22221            }
22222        }
22223
22224        if (filesToDelete != null) {
22225            final int fileToDeleteCount = filesToDelete.size();
22226            for (int i = 0; i < fileToDeleteCount; i++) {
22227                File fileToDelete = filesToDelete.get(i);
22228                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22229                synchronized (mInstallLock) {
22230                    removeCodePathLI(fileToDelete);
22231                }
22232            }
22233        }
22234    }
22235
22236    /**
22237     * Reconcile all app data for the given user.
22238     * <p>
22239     * Verifies that directories exist and that ownership and labeling is
22240     * correct for all installed apps on all mounted volumes.
22241     */
22242    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22243        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22244        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22245            final String volumeUuid = vol.getFsUuid();
22246            synchronized (mInstallLock) {
22247                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22248            }
22249        }
22250    }
22251
22252    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22253            boolean migrateAppData) {
22254        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22255    }
22256
22257    /**
22258     * Reconcile all app data on given mounted volume.
22259     * <p>
22260     * Destroys app data that isn't expected, either due to uninstallation or
22261     * reinstallation on another volume.
22262     * <p>
22263     * Verifies that directories exist and that ownership and labeling is
22264     * correct for all installed apps.
22265     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22266     */
22267    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22268            boolean migrateAppData, boolean onlyCoreApps) {
22269        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22270                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22271        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22272
22273        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22274        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22275
22276        // First look for stale data that doesn't belong, and check if things
22277        // have changed since we did our last restorecon
22278        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22279            if (StorageManager.isFileEncryptedNativeOrEmulated()
22280                    && !StorageManager.isUserKeyUnlocked(userId)) {
22281                throw new RuntimeException(
22282                        "Yikes, someone asked us to reconcile CE storage while " + userId
22283                                + " was still locked; this would have caused massive data loss!");
22284            }
22285
22286            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22287            for (File file : files) {
22288                final String packageName = file.getName();
22289                try {
22290                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22291                } catch (PackageManagerException e) {
22292                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22293                    try {
22294                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22295                                StorageManager.FLAG_STORAGE_CE, 0);
22296                    } catch (InstallerException e2) {
22297                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22298                    }
22299                }
22300            }
22301        }
22302        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22303            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22304            for (File file : files) {
22305                final String packageName = file.getName();
22306                try {
22307                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22308                } catch (PackageManagerException e) {
22309                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22310                    try {
22311                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22312                                StorageManager.FLAG_STORAGE_DE, 0);
22313                    } catch (InstallerException e2) {
22314                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22315                    }
22316                }
22317            }
22318        }
22319
22320        // Ensure that data directories are ready to roll for all packages
22321        // installed for this volume and user
22322        final List<PackageSetting> packages;
22323        synchronized (mPackages) {
22324            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22325        }
22326        int preparedCount = 0;
22327        for (PackageSetting ps : packages) {
22328            final String packageName = ps.name;
22329            if (ps.pkg == null) {
22330                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22331                // TODO: might be due to legacy ASEC apps; we should circle back
22332                // and reconcile again once they're scanned
22333                continue;
22334            }
22335            // Skip non-core apps if requested
22336            if (onlyCoreApps && !ps.pkg.coreApp) {
22337                result.add(packageName);
22338                continue;
22339            }
22340
22341            if (ps.getInstalled(userId)) {
22342                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22343                preparedCount++;
22344            }
22345        }
22346
22347        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22348        return result;
22349    }
22350
22351    /**
22352     * Prepare app data for the given app just after it was installed or
22353     * upgraded. This method carefully only touches users that it's installed
22354     * for, and it forces a restorecon to handle any seinfo changes.
22355     * <p>
22356     * Verifies that directories exist and that ownership and labeling is
22357     * correct for all installed apps. If there is an ownership mismatch, it
22358     * will try recovering system apps by wiping data; third-party app data is
22359     * left intact.
22360     * <p>
22361     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22362     */
22363    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22364        final PackageSetting ps;
22365        synchronized (mPackages) {
22366            ps = mSettings.mPackages.get(pkg.packageName);
22367            mSettings.writeKernelMappingLPr(ps);
22368        }
22369
22370        final UserManager um = mContext.getSystemService(UserManager.class);
22371        UserManagerInternal umInternal = getUserManagerInternal();
22372        for (UserInfo user : um.getUsers()) {
22373            final int flags;
22374            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22375                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22376            } else if (umInternal.isUserRunning(user.id)) {
22377                flags = StorageManager.FLAG_STORAGE_DE;
22378            } else {
22379                continue;
22380            }
22381
22382            if (ps.getInstalled(user.id)) {
22383                // TODO: when user data is locked, mark that we're still dirty
22384                prepareAppDataLIF(pkg, user.id, flags);
22385            }
22386        }
22387    }
22388
22389    /**
22390     * Prepare app data for the given app.
22391     * <p>
22392     * Verifies that directories exist and that ownership and labeling is
22393     * correct for all installed apps. If there is an ownership mismatch, this
22394     * will try recovering system apps by wiping data; third-party app data is
22395     * left intact.
22396     */
22397    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22398        if (pkg == null) {
22399            Slog.wtf(TAG, "Package was null!", new Throwable());
22400            return;
22401        }
22402        prepareAppDataLeafLIF(pkg, userId, flags);
22403        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22404        for (int i = 0; i < childCount; i++) {
22405            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22406        }
22407    }
22408
22409    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22410            boolean maybeMigrateAppData) {
22411        prepareAppDataLIF(pkg, userId, flags);
22412
22413        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22414            // We may have just shuffled around app data directories, so
22415            // prepare them one more time
22416            prepareAppDataLIF(pkg, userId, flags);
22417        }
22418    }
22419
22420    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22421        if (DEBUG_APP_DATA) {
22422            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22423                    + Integer.toHexString(flags));
22424        }
22425
22426        final String volumeUuid = pkg.volumeUuid;
22427        final String packageName = pkg.packageName;
22428        final ApplicationInfo app = pkg.applicationInfo;
22429        final int appId = UserHandle.getAppId(app.uid);
22430
22431        Preconditions.checkNotNull(app.seInfo);
22432
22433        long ceDataInode = -1;
22434        try {
22435            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22436                    appId, app.seInfo, app.targetSdkVersion);
22437        } catch (InstallerException e) {
22438            if (app.isSystemApp()) {
22439                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22440                        + ", but trying to recover: " + e);
22441                destroyAppDataLeafLIF(pkg, userId, flags);
22442                try {
22443                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22444                            appId, app.seInfo, app.targetSdkVersion);
22445                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22446                } catch (InstallerException e2) {
22447                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22448                }
22449            } else {
22450                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22451            }
22452        }
22453        // Prepare the application profiles only for upgrades and first boot (so that we don't
22454        // repeat the same operation at each boot).
22455        // We only have to cover the upgrade and first boot here because for app installs we
22456        // prepare the profiles before invoking dexopt (in installPackageLI).
22457        //
22458        // We also have to cover non system users because we do not call the usual install package
22459        // methods for them.
22460        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22461            mArtManagerService.prepareAppProfiles(pkg, userId);
22462        }
22463
22464        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22465            // TODO: mark this structure as dirty so we persist it!
22466            synchronized (mPackages) {
22467                final PackageSetting ps = mSettings.mPackages.get(packageName);
22468                if (ps != null) {
22469                    ps.setCeDataInode(ceDataInode, userId);
22470                }
22471            }
22472        }
22473
22474        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22475    }
22476
22477    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22478        if (pkg == null) {
22479            Slog.wtf(TAG, "Package was null!", new Throwable());
22480            return;
22481        }
22482        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22483        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22484        for (int i = 0; i < childCount; i++) {
22485            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22486        }
22487    }
22488
22489    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22490        final String volumeUuid = pkg.volumeUuid;
22491        final String packageName = pkg.packageName;
22492        final ApplicationInfo app = pkg.applicationInfo;
22493
22494        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22495            // Create a native library symlink only if we have native libraries
22496            // and if the native libraries are 32 bit libraries. We do not provide
22497            // this symlink for 64 bit libraries.
22498            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22499                final String nativeLibPath = app.nativeLibraryDir;
22500                try {
22501                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22502                            nativeLibPath, userId);
22503                } catch (InstallerException e) {
22504                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22505                }
22506            }
22507        }
22508    }
22509
22510    /**
22511     * For system apps on non-FBE devices, this method migrates any existing
22512     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22513     * requested by the app.
22514     */
22515    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22516        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22517                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22518            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22519                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22520            try {
22521                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22522                        storageTarget);
22523            } catch (InstallerException e) {
22524                logCriticalInfo(Log.WARN,
22525                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22526            }
22527            return true;
22528        } else {
22529            return false;
22530        }
22531    }
22532
22533    public PackageFreezer freezePackage(String packageName, String killReason) {
22534        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22535    }
22536
22537    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22538        return new PackageFreezer(packageName, userId, killReason);
22539    }
22540
22541    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22542            String killReason) {
22543        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22544    }
22545
22546    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22547            String killReason) {
22548        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22549            return new PackageFreezer();
22550        } else {
22551            return freezePackage(packageName, userId, killReason);
22552        }
22553    }
22554
22555    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22556            String killReason) {
22557        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22558    }
22559
22560    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22561            String killReason) {
22562        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22563            return new PackageFreezer();
22564        } else {
22565            return freezePackage(packageName, userId, killReason);
22566        }
22567    }
22568
22569    /**
22570     * Class that freezes and kills the given package upon creation, and
22571     * unfreezes it upon closing. This is typically used when doing surgery on
22572     * app code/data to prevent the app from running while you're working.
22573     */
22574    private class PackageFreezer implements AutoCloseable {
22575        private final String mPackageName;
22576        private final PackageFreezer[] mChildren;
22577
22578        private final boolean mWeFroze;
22579
22580        private final AtomicBoolean mClosed = new AtomicBoolean();
22581        private final CloseGuard mCloseGuard = CloseGuard.get();
22582
22583        /**
22584         * Create and return a stub freezer that doesn't actually do anything,
22585         * typically used when someone requested
22586         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22587         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22588         */
22589        public PackageFreezer() {
22590            mPackageName = null;
22591            mChildren = null;
22592            mWeFroze = false;
22593            mCloseGuard.open("close");
22594        }
22595
22596        public PackageFreezer(String packageName, int userId, String killReason) {
22597            synchronized (mPackages) {
22598                mPackageName = packageName;
22599                mWeFroze = mFrozenPackages.add(mPackageName);
22600
22601                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22602                if (ps != null) {
22603                    killApplication(ps.name, ps.appId, userId, killReason);
22604                }
22605
22606                final PackageParser.Package p = mPackages.get(packageName);
22607                if (p != null && p.childPackages != null) {
22608                    final int N = p.childPackages.size();
22609                    mChildren = new PackageFreezer[N];
22610                    for (int i = 0; i < N; i++) {
22611                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22612                                userId, killReason);
22613                    }
22614                } else {
22615                    mChildren = null;
22616                }
22617            }
22618            mCloseGuard.open("close");
22619        }
22620
22621        @Override
22622        protected void finalize() throws Throwable {
22623            try {
22624                if (mCloseGuard != null) {
22625                    mCloseGuard.warnIfOpen();
22626                }
22627
22628                close();
22629            } finally {
22630                super.finalize();
22631            }
22632        }
22633
22634        @Override
22635        public void close() {
22636            mCloseGuard.close();
22637            if (mClosed.compareAndSet(false, true)) {
22638                synchronized (mPackages) {
22639                    if (mWeFroze) {
22640                        mFrozenPackages.remove(mPackageName);
22641                    }
22642
22643                    if (mChildren != null) {
22644                        for (PackageFreezer freezer : mChildren) {
22645                            freezer.close();
22646                        }
22647                    }
22648                }
22649            }
22650        }
22651    }
22652
22653    /**
22654     * Verify that given package is currently frozen.
22655     */
22656    private void checkPackageFrozen(String packageName) {
22657        synchronized (mPackages) {
22658            if (!mFrozenPackages.contains(packageName)) {
22659                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22660            }
22661        }
22662    }
22663
22664    @Override
22665    public int movePackage(final String packageName, final String volumeUuid) {
22666        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22667
22668        final int callingUid = Binder.getCallingUid();
22669        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22670        final int moveId = mNextMoveId.getAndIncrement();
22671        mHandler.post(new Runnable() {
22672            @Override
22673            public void run() {
22674                try {
22675                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22676                } catch (PackageManagerException e) {
22677                    Slog.w(TAG, "Failed to move " + packageName, e);
22678                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22679                }
22680            }
22681        });
22682        return moveId;
22683    }
22684
22685    private void movePackageInternal(final String packageName, final String volumeUuid,
22686            final int moveId, final int callingUid, UserHandle user)
22687                    throws PackageManagerException {
22688        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22689        final PackageManager pm = mContext.getPackageManager();
22690
22691        final boolean currentAsec;
22692        final String currentVolumeUuid;
22693        final File codeFile;
22694        final String installerPackageName;
22695        final String packageAbiOverride;
22696        final int appId;
22697        final String seinfo;
22698        final String label;
22699        final int targetSdkVersion;
22700        final PackageFreezer freezer;
22701        final int[] installedUserIds;
22702
22703        // reader
22704        synchronized (mPackages) {
22705            final PackageParser.Package pkg = mPackages.get(packageName);
22706            final PackageSetting ps = mSettings.mPackages.get(packageName);
22707            if (pkg == null
22708                    || ps == null
22709                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22710                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22711            }
22712            if (pkg.applicationInfo.isSystemApp()) {
22713                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22714                        "Cannot move system application");
22715            }
22716
22717            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22718            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22719                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22720            if (isInternalStorage && !allow3rdPartyOnInternal) {
22721                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22722                        "3rd party apps are not allowed on internal storage");
22723            }
22724
22725            if (pkg.applicationInfo.isExternalAsec()) {
22726                currentAsec = true;
22727                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22728            } else if (pkg.applicationInfo.isForwardLocked()) {
22729                currentAsec = true;
22730                currentVolumeUuid = "forward_locked";
22731            } else {
22732                currentAsec = false;
22733                currentVolumeUuid = ps.volumeUuid;
22734
22735                final File probe = new File(pkg.codePath);
22736                final File probeOat = new File(probe, "oat");
22737                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22738                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22739                            "Move only supported for modern cluster style installs");
22740                }
22741            }
22742
22743            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22744                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22745                        "Package already moved to " + volumeUuid);
22746            }
22747            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22748                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22749                        "Device admin cannot be moved");
22750            }
22751
22752            if (mFrozenPackages.contains(packageName)) {
22753                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22754                        "Failed to move already frozen package");
22755            }
22756
22757            codeFile = new File(pkg.codePath);
22758            installerPackageName = ps.installerPackageName;
22759            packageAbiOverride = ps.cpuAbiOverrideString;
22760            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22761            seinfo = pkg.applicationInfo.seInfo;
22762            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22763            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22764            freezer = freezePackage(packageName, "movePackageInternal");
22765            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22766        }
22767
22768        final Bundle extras = new Bundle();
22769        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22770        extras.putString(Intent.EXTRA_TITLE, label);
22771        mMoveCallbacks.notifyCreated(moveId, extras);
22772
22773        int installFlags;
22774        final boolean moveCompleteApp;
22775        final File measurePath;
22776
22777        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22778            installFlags = INSTALL_INTERNAL;
22779            moveCompleteApp = !currentAsec;
22780            measurePath = Environment.getDataAppDirectory(volumeUuid);
22781        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22782            installFlags = INSTALL_EXTERNAL;
22783            moveCompleteApp = false;
22784            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22785        } else {
22786            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22787            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22788                    || !volume.isMountedWritable()) {
22789                freezer.close();
22790                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22791                        "Move location not mounted private volume");
22792            }
22793
22794            Preconditions.checkState(!currentAsec);
22795
22796            installFlags = INSTALL_INTERNAL;
22797            moveCompleteApp = true;
22798            measurePath = Environment.getDataAppDirectory(volumeUuid);
22799        }
22800
22801        // If we're moving app data around, we need all the users unlocked
22802        if (moveCompleteApp) {
22803            for (int userId : installedUserIds) {
22804                if (StorageManager.isFileEncryptedNativeOrEmulated()
22805                        && !StorageManager.isUserKeyUnlocked(userId)) {
22806                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22807                            "User " + userId + " must be unlocked");
22808                }
22809            }
22810        }
22811
22812        final PackageStats stats = new PackageStats(null, -1);
22813        synchronized (mInstaller) {
22814            for (int userId : installedUserIds) {
22815                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22816                    freezer.close();
22817                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22818                            "Failed to measure package size");
22819                }
22820            }
22821        }
22822
22823        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22824                + stats.dataSize);
22825
22826        final long startFreeBytes = measurePath.getUsableSpace();
22827        final long sizeBytes;
22828        if (moveCompleteApp) {
22829            sizeBytes = stats.codeSize + stats.dataSize;
22830        } else {
22831            sizeBytes = stats.codeSize;
22832        }
22833
22834        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22835            freezer.close();
22836            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22837                    "Not enough free space to move");
22838        }
22839
22840        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22841
22842        final CountDownLatch installedLatch = new CountDownLatch(1);
22843        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22844            @Override
22845            public void onUserActionRequired(Intent intent) throws RemoteException {
22846                throw new IllegalStateException();
22847            }
22848
22849            @Override
22850            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22851                    Bundle extras) throws RemoteException {
22852                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22853                        + PackageManager.installStatusToString(returnCode, msg));
22854
22855                installedLatch.countDown();
22856                freezer.close();
22857
22858                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22859                switch (status) {
22860                    case PackageInstaller.STATUS_SUCCESS:
22861                        mMoveCallbacks.notifyStatusChanged(moveId,
22862                                PackageManager.MOVE_SUCCEEDED);
22863                        break;
22864                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22865                        mMoveCallbacks.notifyStatusChanged(moveId,
22866                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22867                        break;
22868                    default:
22869                        mMoveCallbacks.notifyStatusChanged(moveId,
22870                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22871                        break;
22872                }
22873            }
22874        };
22875
22876        final MoveInfo move;
22877        if (moveCompleteApp) {
22878            // Kick off a thread to report progress estimates
22879            new Thread() {
22880                @Override
22881                public void run() {
22882                    while (true) {
22883                        try {
22884                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22885                                break;
22886                            }
22887                        } catch (InterruptedException ignored) {
22888                        }
22889
22890                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22891                        final int progress = 10 + (int) MathUtils.constrain(
22892                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22893                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22894                    }
22895                }
22896            }.start();
22897
22898            final String dataAppName = codeFile.getName();
22899            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22900                    dataAppName, appId, seinfo, targetSdkVersion);
22901        } else {
22902            move = null;
22903        }
22904
22905        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22906
22907        final Message msg = mHandler.obtainMessage(INIT_COPY);
22908        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22909        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22910                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22911                packageAbiOverride, null /*grantedPermissions*/,
22912                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22913        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22914        msg.obj = params;
22915
22916        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22917                System.identityHashCode(msg.obj));
22918        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22919                System.identityHashCode(msg.obj));
22920
22921        mHandler.sendMessage(msg);
22922    }
22923
22924    @Override
22925    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22926        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22927
22928        final int realMoveId = mNextMoveId.getAndIncrement();
22929        final Bundle extras = new Bundle();
22930        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22931        mMoveCallbacks.notifyCreated(realMoveId, extras);
22932
22933        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22934            @Override
22935            public void onCreated(int moveId, Bundle extras) {
22936                // Ignored
22937            }
22938
22939            @Override
22940            public void onStatusChanged(int moveId, int status, long estMillis) {
22941                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22942            }
22943        };
22944
22945        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22946        storage.setPrimaryStorageUuid(volumeUuid, callback);
22947        return realMoveId;
22948    }
22949
22950    @Override
22951    public int getMoveStatus(int moveId) {
22952        mContext.enforceCallingOrSelfPermission(
22953                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22954        return mMoveCallbacks.mLastStatus.get(moveId);
22955    }
22956
22957    @Override
22958    public void registerMoveCallback(IPackageMoveObserver callback) {
22959        mContext.enforceCallingOrSelfPermission(
22960                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22961        mMoveCallbacks.register(callback);
22962    }
22963
22964    @Override
22965    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22966        mContext.enforceCallingOrSelfPermission(
22967                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22968        mMoveCallbacks.unregister(callback);
22969    }
22970
22971    @Override
22972    public boolean setInstallLocation(int loc) {
22973        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22974                null);
22975        if (getInstallLocation() == loc) {
22976            return true;
22977        }
22978        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22979                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22980            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22981                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22982            return true;
22983        }
22984        return false;
22985   }
22986
22987    @Override
22988    public int getInstallLocation() {
22989        // allow instant app access
22990        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22991                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22992                PackageHelper.APP_INSTALL_AUTO);
22993    }
22994
22995    /** Called by UserManagerService */
22996    void cleanUpUser(UserManagerService userManager, int userHandle) {
22997        synchronized (mPackages) {
22998            mDirtyUsers.remove(userHandle);
22999            mUserNeedsBadging.delete(userHandle);
23000            mSettings.removeUserLPw(userHandle);
23001            mPendingBroadcasts.remove(userHandle);
23002            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23003            removeUnusedPackagesLPw(userManager, userHandle);
23004        }
23005    }
23006
23007    /**
23008     * We're removing userHandle and would like to remove any downloaded packages
23009     * that are no longer in use by any other user.
23010     * @param userHandle the user being removed
23011     */
23012    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23013        final boolean DEBUG_CLEAN_APKS = false;
23014        int [] users = userManager.getUserIds();
23015        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23016        while (psit.hasNext()) {
23017            PackageSetting ps = psit.next();
23018            if (ps.pkg == null) {
23019                continue;
23020            }
23021            final String packageName = ps.pkg.packageName;
23022            // Skip over if system app
23023            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23024                continue;
23025            }
23026            if (DEBUG_CLEAN_APKS) {
23027                Slog.i(TAG, "Checking package " + packageName);
23028            }
23029            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23030            if (keep) {
23031                if (DEBUG_CLEAN_APKS) {
23032                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23033                }
23034            } else {
23035                for (int i = 0; i < users.length; i++) {
23036                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23037                        keep = true;
23038                        if (DEBUG_CLEAN_APKS) {
23039                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23040                                    + users[i]);
23041                        }
23042                        break;
23043                    }
23044                }
23045            }
23046            if (!keep) {
23047                if (DEBUG_CLEAN_APKS) {
23048                    Slog.i(TAG, "  Removing package " + packageName);
23049                }
23050                mHandler.post(new Runnable() {
23051                    public void run() {
23052                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23053                                userHandle, 0);
23054                    } //end run
23055                });
23056            }
23057        }
23058    }
23059
23060    /** Called by UserManagerService */
23061    void createNewUser(int userId, String[] disallowedPackages) {
23062        synchronized (mInstallLock) {
23063            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23064        }
23065        synchronized (mPackages) {
23066            scheduleWritePackageRestrictionsLocked(userId);
23067            scheduleWritePackageListLocked(userId);
23068            applyFactoryDefaultBrowserLPw(userId);
23069            primeDomainVerificationsLPw(userId);
23070        }
23071    }
23072
23073    void onNewUserCreated(final int userId) {
23074        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23075        synchronized(mPackages) {
23076            // If permission review for legacy apps is required, we represent
23077            // dagerous permissions for such apps as always granted runtime
23078            // permissions to keep per user flag state whether review is needed.
23079            // Hence, if a new user is added we have to propagate dangerous
23080            // permission grants for these legacy apps.
23081            if (mSettings.mPermissions.mPermissionReviewRequired) {
23082// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23083                mPermissionManager.updateAllPermissions(
23084                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23085                        mPermissionCallback);
23086            }
23087        }
23088    }
23089
23090    @Override
23091    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23092        mContext.enforceCallingOrSelfPermission(
23093                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23094                "Only package verification agents can read the verifier device identity");
23095
23096        synchronized (mPackages) {
23097            return mSettings.getVerifierDeviceIdentityLPw();
23098        }
23099    }
23100
23101    @Override
23102    public void setPermissionEnforced(String permission, boolean enforced) {
23103        // TODO: Now that we no longer change GID for storage, this should to away.
23104        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23105                "setPermissionEnforced");
23106        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23107            synchronized (mPackages) {
23108                if (mSettings.mReadExternalStorageEnforced == null
23109                        || mSettings.mReadExternalStorageEnforced != enforced) {
23110                    mSettings.mReadExternalStorageEnforced =
23111                            enforced ? Boolean.TRUE : Boolean.FALSE;
23112                    mSettings.writeLPr();
23113                }
23114            }
23115            // kill any non-foreground processes so we restart them and
23116            // grant/revoke the GID.
23117            final IActivityManager am = ActivityManager.getService();
23118            if (am != null) {
23119                final long token = Binder.clearCallingIdentity();
23120                try {
23121                    am.killProcessesBelowForeground("setPermissionEnforcement");
23122                } catch (RemoteException e) {
23123                } finally {
23124                    Binder.restoreCallingIdentity(token);
23125                }
23126            }
23127        } else {
23128            throw new IllegalArgumentException("No selective enforcement for " + permission);
23129        }
23130    }
23131
23132    @Override
23133    @Deprecated
23134    public boolean isPermissionEnforced(String permission) {
23135        // allow instant applications
23136        return true;
23137    }
23138
23139    @Override
23140    public boolean isStorageLow() {
23141        // allow instant applications
23142        final long token = Binder.clearCallingIdentity();
23143        try {
23144            final DeviceStorageMonitorInternal
23145                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23146            if (dsm != null) {
23147                return dsm.isMemoryLow();
23148            } else {
23149                return false;
23150            }
23151        } finally {
23152            Binder.restoreCallingIdentity(token);
23153        }
23154    }
23155
23156    @Override
23157    public IPackageInstaller getPackageInstaller() {
23158        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23159            return null;
23160        }
23161        return mInstallerService;
23162    }
23163
23164    @Override
23165    public IArtManager getArtManager() {
23166        return mArtManagerService;
23167    }
23168
23169    private boolean userNeedsBadging(int userId) {
23170        int index = mUserNeedsBadging.indexOfKey(userId);
23171        if (index < 0) {
23172            final UserInfo userInfo;
23173            final long token = Binder.clearCallingIdentity();
23174            try {
23175                userInfo = sUserManager.getUserInfo(userId);
23176            } finally {
23177                Binder.restoreCallingIdentity(token);
23178            }
23179            final boolean b;
23180            if (userInfo != null && userInfo.isManagedProfile()) {
23181                b = true;
23182            } else {
23183                b = false;
23184            }
23185            mUserNeedsBadging.put(userId, b);
23186            return b;
23187        }
23188        return mUserNeedsBadging.valueAt(index);
23189    }
23190
23191    @Override
23192    public KeySet getKeySetByAlias(String packageName, String alias) {
23193        if (packageName == null || alias == null) {
23194            return null;
23195        }
23196        synchronized(mPackages) {
23197            final PackageParser.Package pkg = mPackages.get(packageName);
23198            if (pkg == null) {
23199                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23200                throw new IllegalArgumentException("Unknown package: " + packageName);
23201            }
23202            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23203            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23204                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23205                throw new IllegalArgumentException("Unknown package: " + packageName);
23206            }
23207            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23208            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23209        }
23210    }
23211
23212    @Override
23213    public KeySet getSigningKeySet(String packageName) {
23214        if (packageName == null) {
23215            return null;
23216        }
23217        synchronized(mPackages) {
23218            final int callingUid = Binder.getCallingUid();
23219            final int callingUserId = UserHandle.getUserId(callingUid);
23220            final PackageParser.Package pkg = mPackages.get(packageName);
23221            if (pkg == null) {
23222                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23223                throw new IllegalArgumentException("Unknown package: " + packageName);
23224            }
23225            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23226            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23227                // filter and pretend the package doesn't exist
23228                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23229                        + ", uid:" + callingUid);
23230                throw new IllegalArgumentException("Unknown package: " + packageName);
23231            }
23232            if (pkg.applicationInfo.uid != callingUid
23233                    && Process.SYSTEM_UID != callingUid) {
23234                throw new SecurityException("May not access signing KeySet of other apps.");
23235            }
23236            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23237            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23238        }
23239    }
23240
23241    @Override
23242    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23243        final int callingUid = Binder.getCallingUid();
23244        if (getInstantAppPackageName(callingUid) != null) {
23245            return false;
23246        }
23247        if (packageName == null || ks == null) {
23248            return false;
23249        }
23250        synchronized(mPackages) {
23251            final PackageParser.Package pkg = mPackages.get(packageName);
23252            if (pkg == null
23253                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23254                            UserHandle.getUserId(callingUid))) {
23255                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23256                throw new IllegalArgumentException("Unknown package: " + packageName);
23257            }
23258            IBinder ksh = ks.getToken();
23259            if (ksh instanceof KeySetHandle) {
23260                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23261                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23262            }
23263            return false;
23264        }
23265    }
23266
23267    @Override
23268    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23269        final int callingUid = Binder.getCallingUid();
23270        if (getInstantAppPackageName(callingUid) != null) {
23271            return false;
23272        }
23273        if (packageName == null || ks == null) {
23274            return false;
23275        }
23276        synchronized(mPackages) {
23277            final PackageParser.Package pkg = mPackages.get(packageName);
23278            if (pkg == null
23279                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23280                            UserHandle.getUserId(callingUid))) {
23281                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23282                throw new IllegalArgumentException("Unknown package: " + packageName);
23283            }
23284            IBinder ksh = ks.getToken();
23285            if (ksh instanceof KeySetHandle) {
23286                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23287                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23288            }
23289            return false;
23290        }
23291    }
23292
23293    private void deletePackageIfUnusedLPr(final String packageName) {
23294        PackageSetting ps = mSettings.mPackages.get(packageName);
23295        if (ps == null) {
23296            return;
23297        }
23298        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23299            // TODO Implement atomic delete if package is unused
23300            // It is currently possible that the package will be deleted even if it is installed
23301            // after this method returns.
23302            mHandler.post(new Runnable() {
23303                public void run() {
23304                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23305                            0, PackageManager.DELETE_ALL_USERS);
23306                }
23307            });
23308        }
23309    }
23310
23311    /**
23312     * Check and throw if the given before/after packages would be considered a
23313     * downgrade.
23314     */
23315    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23316            throws PackageManagerException {
23317        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23318            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23319                    "Update version code " + after.versionCode + " is older than current "
23320                    + before.getLongVersionCode());
23321        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23322            if (after.baseRevisionCode < before.baseRevisionCode) {
23323                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23324                        "Update base revision code " + after.baseRevisionCode
23325                        + " is older than current " + before.baseRevisionCode);
23326            }
23327
23328            if (!ArrayUtils.isEmpty(after.splitNames)) {
23329                for (int i = 0; i < after.splitNames.length; i++) {
23330                    final String splitName = after.splitNames[i];
23331                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23332                    if (j != -1) {
23333                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23334                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23335                                    "Update split " + splitName + " revision code "
23336                                    + after.splitRevisionCodes[i] + " is older than current "
23337                                    + before.splitRevisionCodes[j]);
23338                        }
23339                    }
23340                }
23341            }
23342        }
23343    }
23344
23345    private static class MoveCallbacks extends Handler {
23346        private static final int MSG_CREATED = 1;
23347        private static final int MSG_STATUS_CHANGED = 2;
23348
23349        private final RemoteCallbackList<IPackageMoveObserver>
23350                mCallbacks = new RemoteCallbackList<>();
23351
23352        private final SparseIntArray mLastStatus = new SparseIntArray();
23353
23354        public MoveCallbacks(Looper looper) {
23355            super(looper);
23356        }
23357
23358        public void register(IPackageMoveObserver callback) {
23359            mCallbacks.register(callback);
23360        }
23361
23362        public void unregister(IPackageMoveObserver callback) {
23363            mCallbacks.unregister(callback);
23364        }
23365
23366        @Override
23367        public void handleMessage(Message msg) {
23368            final SomeArgs args = (SomeArgs) msg.obj;
23369            final int n = mCallbacks.beginBroadcast();
23370            for (int i = 0; i < n; i++) {
23371                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23372                try {
23373                    invokeCallback(callback, msg.what, args);
23374                } catch (RemoteException ignored) {
23375                }
23376            }
23377            mCallbacks.finishBroadcast();
23378            args.recycle();
23379        }
23380
23381        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23382                throws RemoteException {
23383            switch (what) {
23384                case MSG_CREATED: {
23385                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23386                    break;
23387                }
23388                case MSG_STATUS_CHANGED: {
23389                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23390                    break;
23391                }
23392            }
23393        }
23394
23395        private void notifyCreated(int moveId, Bundle extras) {
23396            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23397
23398            final SomeArgs args = SomeArgs.obtain();
23399            args.argi1 = moveId;
23400            args.arg2 = extras;
23401            obtainMessage(MSG_CREATED, args).sendToTarget();
23402        }
23403
23404        private void notifyStatusChanged(int moveId, int status) {
23405            notifyStatusChanged(moveId, status, -1);
23406        }
23407
23408        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23409            Slog.v(TAG, "Move " + moveId + " status " + status);
23410
23411            final SomeArgs args = SomeArgs.obtain();
23412            args.argi1 = moveId;
23413            args.argi2 = status;
23414            args.arg3 = estMillis;
23415            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23416
23417            synchronized (mLastStatus) {
23418                mLastStatus.put(moveId, status);
23419            }
23420        }
23421    }
23422
23423    private final static class OnPermissionChangeListeners extends Handler {
23424        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23425
23426        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23427                new RemoteCallbackList<>();
23428
23429        public OnPermissionChangeListeners(Looper looper) {
23430            super(looper);
23431        }
23432
23433        @Override
23434        public void handleMessage(Message msg) {
23435            switch (msg.what) {
23436                case MSG_ON_PERMISSIONS_CHANGED: {
23437                    final int uid = msg.arg1;
23438                    handleOnPermissionsChanged(uid);
23439                } break;
23440            }
23441        }
23442
23443        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23444            mPermissionListeners.register(listener);
23445
23446        }
23447
23448        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23449            mPermissionListeners.unregister(listener);
23450        }
23451
23452        public void onPermissionsChanged(int uid) {
23453            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23454                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23455            }
23456        }
23457
23458        private void handleOnPermissionsChanged(int uid) {
23459            final int count = mPermissionListeners.beginBroadcast();
23460            try {
23461                for (int i = 0; i < count; i++) {
23462                    IOnPermissionsChangeListener callback = mPermissionListeners
23463                            .getBroadcastItem(i);
23464                    try {
23465                        callback.onPermissionsChanged(uid);
23466                    } catch (RemoteException e) {
23467                        Log.e(TAG, "Permission listener is dead", e);
23468                    }
23469                }
23470            } finally {
23471                mPermissionListeners.finishBroadcast();
23472            }
23473        }
23474    }
23475
23476    private class PackageManagerNative extends IPackageManagerNative.Stub {
23477        @Override
23478        public String[] getNamesForUids(int[] uids) throws RemoteException {
23479            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23480            // massage results so they can be parsed by the native binder
23481            for (int i = results.length - 1; i >= 0; --i) {
23482                if (results[i] == null) {
23483                    results[i] = "";
23484                }
23485            }
23486            return results;
23487        }
23488
23489        // NB: this differentiates between preloads and sideloads
23490        @Override
23491        public String getInstallerForPackage(String packageName) throws RemoteException {
23492            final String installerName = getInstallerPackageName(packageName);
23493            if (!TextUtils.isEmpty(installerName)) {
23494                return installerName;
23495            }
23496            // differentiate between preload and sideload
23497            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23498            ApplicationInfo appInfo = getApplicationInfo(packageName,
23499                                    /*flags*/ 0,
23500                                    /*userId*/ callingUser);
23501            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23502                return "preload";
23503            }
23504            return "";
23505        }
23506
23507        @Override
23508        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23509            try {
23510                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23511                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23512                if (pInfo != null) {
23513                    return pInfo.getLongVersionCode();
23514                }
23515            } catch (Exception e) {
23516            }
23517            return 0;
23518        }
23519    }
23520
23521    private class PackageManagerInternalImpl extends PackageManagerInternal {
23522        @Override
23523        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23524                int flagValues, int userId) {
23525            PackageManagerService.this.updatePermissionFlags(
23526                    permName, packageName, flagMask, flagValues, userId);
23527        }
23528
23529        @Override
23530        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23531            SigningDetails sd = getSigningDetails(packageName);
23532            if (sd == null) {
23533                return false;
23534            }
23535            return sd.hasSha256Certificate(restoringFromSigHash,
23536                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23537        }
23538
23539        @Override
23540        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23541            SigningDetails sd = getSigningDetails(packageName);
23542            if (sd == null) {
23543                return false;
23544            }
23545            return sd.hasCertificate(restoringFromSig,
23546                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23547        }
23548
23549        private SigningDetails getSigningDetails(@NonNull String packageName) {
23550            synchronized (mPackages) {
23551                PackageParser.Package p = mPackages.get(packageName);
23552                if (p == null) {
23553                    return null;
23554                }
23555                return p.mSigningDetails;
23556            }
23557        }
23558
23559        @Override
23560        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23561            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23562        }
23563
23564        @Override
23565        public boolean isInstantApp(String packageName, int userId) {
23566            return PackageManagerService.this.isInstantApp(packageName, userId);
23567        }
23568
23569        @Override
23570        public String getInstantAppPackageName(int uid) {
23571            return PackageManagerService.this.getInstantAppPackageName(uid);
23572        }
23573
23574        @Override
23575        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23576            synchronized (mPackages) {
23577                return PackageManagerService.this.filterAppAccessLPr(
23578                        (PackageSetting) pkg.mExtras, callingUid, userId);
23579            }
23580        }
23581
23582        @Override
23583        public PackageParser.Package getPackage(String packageName) {
23584            synchronized (mPackages) {
23585                packageName = resolveInternalPackageNameLPr(
23586                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23587                return mPackages.get(packageName);
23588            }
23589        }
23590
23591        @Override
23592        public PackageList getPackageList(PackageListObserver observer) {
23593            synchronized (mPackages) {
23594                final int N = mPackages.size();
23595                final ArrayList<String> list = new ArrayList<>(N);
23596                for (int i = 0; i < N; i++) {
23597                    list.add(mPackages.keyAt(i));
23598                }
23599                final PackageList packageList = new PackageList(list, observer);
23600                if (observer != null) {
23601                    mPackageListObservers.add(packageList);
23602                }
23603                return packageList;
23604            }
23605        }
23606
23607        @Override
23608        public void removePackageListObserver(PackageListObserver observer) {
23609            synchronized (mPackages) {
23610                mPackageListObservers.remove(observer);
23611            }
23612        }
23613
23614        @Override
23615        public PackageParser.Package getDisabledPackage(String packageName) {
23616            synchronized (mPackages) {
23617                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23618                return (ps != null) ? ps.pkg : null;
23619            }
23620        }
23621
23622        @Override
23623        public String getKnownPackageName(int knownPackage, int userId) {
23624            switch(knownPackage) {
23625                case PackageManagerInternal.PACKAGE_BROWSER:
23626                    return getDefaultBrowserPackageName(userId);
23627                case PackageManagerInternal.PACKAGE_INSTALLER:
23628                    return mRequiredInstallerPackage;
23629                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23630                    return mSetupWizardPackage;
23631                case PackageManagerInternal.PACKAGE_SYSTEM:
23632                    return "android";
23633                case PackageManagerInternal.PACKAGE_VERIFIER:
23634                    return mRequiredVerifierPackage;
23635                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23636                    return mSystemTextClassifierPackage;
23637            }
23638            return null;
23639        }
23640
23641        @Override
23642        public boolean isResolveActivityComponent(ComponentInfo component) {
23643            return mResolveActivity.packageName.equals(component.packageName)
23644                    && mResolveActivity.name.equals(component.name);
23645        }
23646
23647        @Override
23648        public void setLocationPackagesProvider(PackagesProvider provider) {
23649            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23650        }
23651
23652        @Override
23653        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23654            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23655        }
23656
23657        @Override
23658        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23659            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23660        }
23661
23662        @Override
23663        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23664            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23665        }
23666
23667        @Override
23668        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23669            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23670        }
23671
23672        @Override
23673        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23674            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23675        }
23676
23677        @Override
23678        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23679            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23680        }
23681
23682        @Override
23683        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23684            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23685        }
23686
23687        @Override
23688        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23689            synchronized (mPackages) {
23690                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23691            }
23692            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23693        }
23694
23695        @Override
23696        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23697            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23698                    packageName, userId);
23699        }
23700
23701        @Override
23702        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23703            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23704                    packageName, userId);
23705        }
23706
23707        @Override
23708        public void setKeepUninstalledPackages(final List<String> packageList) {
23709            Preconditions.checkNotNull(packageList);
23710            List<String> removedFromList = null;
23711            synchronized (mPackages) {
23712                if (mKeepUninstalledPackages != null) {
23713                    final int packagesCount = mKeepUninstalledPackages.size();
23714                    for (int i = 0; i < packagesCount; i++) {
23715                        String oldPackage = mKeepUninstalledPackages.get(i);
23716                        if (packageList != null && packageList.contains(oldPackage)) {
23717                            continue;
23718                        }
23719                        if (removedFromList == null) {
23720                            removedFromList = new ArrayList<>();
23721                        }
23722                        removedFromList.add(oldPackage);
23723                    }
23724                }
23725                mKeepUninstalledPackages = new ArrayList<>(packageList);
23726                if (removedFromList != null) {
23727                    final int removedCount = removedFromList.size();
23728                    for (int i = 0; i < removedCount; i++) {
23729                        deletePackageIfUnusedLPr(removedFromList.get(i));
23730                    }
23731                }
23732            }
23733        }
23734
23735        @Override
23736        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23737            synchronized (mPackages) {
23738                return mPermissionManager.isPermissionsReviewRequired(
23739                        mPackages.get(packageName), userId);
23740            }
23741        }
23742
23743        @Override
23744        public PackageInfo getPackageInfo(
23745                String packageName, int flags, int filterCallingUid, int userId) {
23746            return PackageManagerService.this
23747                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23748                            flags, filterCallingUid, userId);
23749        }
23750
23751        @Override
23752        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23753            synchronized (mPackages) {
23754                final PackageSetting ps = mSettings.mPackages.get(packageName);
23755                PersistableBundle launcherExtras = null;
23756                if (ps != null) {
23757                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23758                }
23759                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23760            }
23761        }
23762
23763        @Override
23764        public int getPackageUid(String packageName, int flags, int userId) {
23765            return PackageManagerService.this
23766                    .getPackageUid(packageName, flags, userId);
23767        }
23768
23769        @Override
23770        public ApplicationInfo getApplicationInfo(
23771                String packageName, int flags, int filterCallingUid, int userId) {
23772            return PackageManagerService.this
23773                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23774        }
23775
23776        @Override
23777        public ActivityInfo getActivityInfo(
23778                ComponentName component, int flags, int filterCallingUid, int userId) {
23779            return PackageManagerService.this
23780                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23781        }
23782
23783        @Override
23784        public List<ResolveInfo> queryIntentActivities(
23785                Intent intent, int flags, int filterCallingUid, int userId) {
23786            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23787            return PackageManagerService.this
23788                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23789                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23790        }
23791
23792        @Override
23793        public List<ResolveInfo> queryIntentServices(
23794                Intent intent, int flags, int callingUid, int userId) {
23795            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23796            return PackageManagerService.this
23797                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23798                            false);
23799        }
23800
23801        @Override
23802        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23803                int userId) {
23804            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23805        }
23806
23807        @Override
23808        public ComponentName getDefaultHomeActivity(int userId) {
23809            return PackageManagerService.this.getDefaultHomeActivity(userId);
23810        }
23811
23812        @Override
23813        public void setDeviceAndProfileOwnerPackages(
23814                int deviceOwnerUserId, String deviceOwnerPackage,
23815                SparseArray<String> profileOwnerPackages) {
23816            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23817                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23818        }
23819
23820        @Override
23821        public boolean isPackageDataProtected(int userId, String packageName) {
23822            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23823        }
23824
23825        @Override
23826        public boolean isPackageEphemeral(int userId, String packageName) {
23827            synchronized (mPackages) {
23828                final PackageSetting ps = mSettings.mPackages.get(packageName);
23829                return ps != null ? ps.getInstantApp(userId) : false;
23830            }
23831        }
23832
23833        @Override
23834        public boolean wasPackageEverLaunched(String packageName, int userId) {
23835            synchronized (mPackages) {
23836                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23837            }
23838        }
23839
23840        @Override
23841        public void grantRuntimePermission(String packageName, String permName, int userId,
23842                boolean overridePolicy) {
23843            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23844                    permName, packageName, overridePolicy, getCallingUid(), userId,
23845                    mPermissionCallback);
23846        }
23847
23848        @Override
23849        public void revokeRuntimePermission(String packageName, String permName, int userId,
23850                boolean overridePolicy) {
23851            mPermissionManager.revokeRuntimePermission(
23852                    permName, packageName, overridePolicy, getCallingUid(), userId,
23853                    mPermissionCallback);
23854        }
23855
23856        @Override
23857        public String getNameForUid(int uid) {
23858            return PackageManagerService.this.getNameForUid(uid);
23859        }
23860
23861        @Override
23862        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23863                Intent origIntent, String resolvedType, String callingPackage,
23864                Bundle verificationBundle, int userId) {
23865            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23866                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23867                    userId);
23868        }
23869
23870        @Override
23871        public void grantEphemeralAccess(int userId, Intent intent,
23872                int targetAppId, int ephemeralAppId) {
23873            synchronized (mPackages) {
23874                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23875                        targetAppId, ephemeralAppId);
23876            }
23877        }
23878
23879        @Override
23880        public boolean isInstantAppInstallerComponent(ComponentName component) {
23881            synchronized (mPackages) {
23882                return mInstantAppInstallerActivity != null
23883                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23884            }
23885        }
23886
23887        @Override
23888        public void pruneInstantApps() {
23889            mInstantAppRegistry.pruneInstantApps();
23890        }
23891
23892        @Override
23893        public String getSetupWizardPackageName() {
23894            return mSetupWizardPackage;
23895        }
23896
23897        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23898            if (policy != null) {
23899                mExternalSourcesPolicy = policy;
23900            }
23901        }
23902
23903        @Override
23904        public boolean isPackagePersistent(String packageName) {
23905            synchronized (mPackages) {
23906                PackageParser.Package pkg = mPackages.get(packageName);
23907                return pkg != null
23908                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23909                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23910                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23911                        : false;
23912            }
23913        }
23914
23915        @Override
23916        public boolean isLegacySystemApp(Package pkg) {
23917            synchronized (mPackages) {
23918                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23919                return mPromoteSystemApps
23920                        && ps.isSystem()
23921                        && mExistingSystemPackages.contains(ps.name);
23922            }
23923        }
23924
23925        @Override
23926        public List<PackageInfo> getOverlayPackages(int userId) {
23927            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23928            synchronized (mPackages) {
23929                for (PackageParser.Package p : mPackages.values()) {
23930                    if (p.mOverlayTarget != null) {
23931                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23932                        if (pkg != null) {
23933                            overlayPackages.add(pkg);
23934                        }
23935                    }
23936                }
23937            }
23938            return overlayPackages;
23939        }
23940
23941        @Override
23942        public List<String> getTargetPackageNames(int userId) {
23943            List<String> targetPackages = new ArrayList<>();
23944            synchronized (mPackages) {
23945                for (PackageParser.Package p : mPackages.values()) {
23946                    if (p.mOverlayTarget == null) {
23947                        targetPackages.add(p.packageName);
23948                    }
23949                }
23950            }
23951            return targetPackages;
23952        }
23953
23954        @Override
23955        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23956                @Nullable List<String> overlayPackageNames) {
23957            synchronized (mPackages) {
23958                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23959                    Slog.e(TAG, "failed to find package " + targetPackageName);
23960                    return false;
23961                }
23962                ArrayList<String> overlayPaths = null;
23963                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23964                    final int N = overlayPackageNames.size();
23965                    overlayPaths = new ArrayList<>(N);
23966                    for (int i = 0; i < N; i++) {
23967                        final String packageName = overlayPackageNames.get(i);
23968                        final PackageParser.Package pkg = mPackages.get(packageName);
23969                        if (pkg == null) {
23970                            Slog.e(TAG, "failed to find package " + packageName);
23971                            return false;
23972                        }
23973                        overlayPaths.add(pkg.baseCodePath);
23974                    }
23975                }
23976
23977                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23978                ps.setOverlayPaths(overlayPaths, userId);
23979                return true;
23980            }
23981        }
23982
23983        @Override
23984        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23985                int flags, int userId, boolean resolveForStart) {
23986            return resolveIntentInternal(
23987                    intent, resolvedType, flags, userId, resolveForStart);
23988        }
23989
23990        @Override
23991        public ResolveInfo resolveService(Intent intent, String resolvedType,
23992                int flags, int userId, int callingUid) {
23993            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23994        }
23995
23996        @Override
23997        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23998            return PackageManagerService.this.resolveContentProviderInternal(
23999                    name, flags, userId);
24000        }
24001
24002        @Override
24003        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24004            synchronized (mPackages) {
24005                mIsolatedOwners.put(isolatedUid, ownerUid);
24006            }
24007        }
24008
24009        @Override
24010        public void removeIsolatedUid(int isolatedUid) {
24011            synchronized (mPackages) {
24012                mIsolatedOwners.delete(isolatedUid);
24013            }
24014        }
24015
24016        @Override
24017        public int getUidTargetSdkVersion(int uid) {
24018            synchronized (mPackages) {
24019                return getUidTargetSdkVersionLockedLPr(uid);
24020            }
24021        }
24022
24023        @Override
24024        public int getPackageTargetSdkVersion(String packageName) {
24025            synchronized (mPackages) {
24026                return getPackageTargetSdkVersionLockedLPr(packageName);
24027            }
24028        }
24029
24030        @Override
24031        public boolean canAccessInstantApps(int callingUid, int userId) {
24032            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24033        }
24034
24035        @Override
24036        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24037            synchronized (mPackages) {
24038                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24039                return !PackageManagerService.this.filterAppAccessLPr(
24040                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24041            }
24042        }
24043
24044        @Override
24045        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24046            synchronized (mPackages) {
24047                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24048            }
24049        }
24050
24051        @Override
24052        public void notifyPackageUse(String packageName, int reason) {
24053            synchronized (mPackages) {
24054                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24055            }
24056        }
24057    }
24058
24059    @Override
24060    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24061        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24062        synchronized (mPackages) {
24063            final long identity = Binder.clearCallingIdentity();
24064            try {
24065                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24066                        packageNames, userId);
24067            } finally {
24068                Binder.restoreCallingIdentity(identity);
24069            }
24070        }
24071    }
24072
24073    @Override
24074    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24075        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24076        synchronized (mPackages) {
24077            final long identity = Binder.clearCallingIdentity();
24078            try {
24079                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24080                        packageNames, userId);
24081            } finally {
24082                Binder.restoreCallingIdentity(identity);
24083            }
24084        }
24085    }
24086
24087    @Override
24088    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24089            String[] packageNames, int userId) {
24090        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24091        synchronized (mPackages) {
24092            Binder.withCleanCallingIdentity( () -> {
24093                mDefaultPermissionPolicy.
24094                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24095                                packageNames, userId);
24096            });
24097        }
24098    }
24099
24100    @Override
24101    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24102            String[] packageNames, int userId) {
24103        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24104        synchronized (mPackages) {
24105            Binder.withCleanCallingIdentity( () -> {
24106                mDefaultPermissionPolicy.
24107                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24108                                packageNames, userId);
24109            });
24110        }
24111    }
24112
24113    private static void enforceSystemOrPhoneCaller(String tag) {
24114        int callingUid = Binder.getCallingUid();
24115        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24116            throw new SecurityException(
24117                    "Cannot call " + tag + " from UID " + callingUid);
24118        }
24119    }
24120
24121    boolean isHistoricalPackageUsageAvailable() {
24122        return mPackageUsage.isHistoricalPackageUsageAvailable();
24123    }
24124
24125    /**
24126     * Return a <b>copy</b> of the collection of packages known to the package manager.
24127     * @return A copy of the values of mPackages.
24128     */
24129    Collection<PackageParser.Package> getPackages() {
24130        synchronized (mPackages) {
24131            return new ArrayList<>(mPackages.values());
24132        }
24133    }
24134
24135    /**
24136     * Logs process start information (including base APK hash) to the security log.
24137     * @hide
24138     */
24139    @Override
24140    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24141            String apkFile, int pid) {
24142        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24143            return;
24144        }
24145        if (!SecurityLog.isLoggingEnabled()) {
24146            return;
24147        }
24148        Bundle data = new Bundle();
24149        data.putLong("startTimestamp", System.currentTimeMillis());
24150        data.putString("processName", processName);
24151        data.putInt("uid", uid);
24152        data.putString("seinfo", seinfo);
24153        data.putString("apkFile", apkFile);
24154        data.putInt("pid", pid);
24155        Message msg = mProcessLoggingHandler.obtainMessage(
24156                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24157        msg.setData(data);
24158        mProcessLoggingHandler.sendMessage(msg);
24159    }
24160
24161    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24162        return mCompilerStats.getPackageStats(pkgName);
24163    }
24164
24165    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24166        return getOrCreateCompilerPackageStats(pkg.packageName);
24167    }
24168
24169    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24170        return mCompilerStats.getOrCreatePackageStats(pkgName);
24171    }
24172
24173    public void deleteCompilerPackageStats(String pkgName) {
24174        mCompilerStats.deletePackageStats(pkgName);
24175    }
24176
24177    @Override
24178    public int getInstallReason(String packageName, int userId) {
24179        final int callingUid = Binder.getCallingUid();
24180        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24181                true /* requireFullPermission */, false /* checkShell */,
24182                "get install reason");
24183        synchronized (mPackages) {
24184            final PackageSetting ps = mSettings.mPackages.get(packageName);
24185            if (filterAppAccessLPr(ps, callingUid, userId)) {
24186                return PackageManager.INSTALL_REASON_UNKNOWN;
24187            }
24188            if (ps != null) {
24189                return ps.getInstallReason(userId);
24190            }
24191        }
24192        return PackageManager.INSTALL_REASON_UNKNOWN;
24193    }
24194
24195    @Override
24196    public boolean canRequestPackageInstalls(String packageName, int userId) {
24197        return canRequestPackageInstallsInternal(packageName, 0, userId,
24198                true /* throwIfPermNotDeclared*/);
24199    }
24200
24201    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24202            boolean throwIfPermNotDeclared) {
24203        int callingUid = Binder.getCallingUid();
24204        int uid = getPackageUid(packageName, 0, userId);
24205        if (callingUid != uid && callingUid != Process.ROOT_UID
24206                && callingUid != Process.SYSTEM_UID) {
24207            throw new SecurityException(
24208                    "Caller uid " + callingUid + " does not own package " + packageName);
24209        }
24210        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24211        if (info == null) {
24212            return false;
24213        }
24214        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24215            return false;
24216        }
24217        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24218        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24219        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24220            if (throwIfPermNotDeclared) {
24221                throw new SecurityException("Need to declare " + appOpPermission
24222                        + " to call this api");
24223            } else {
24224                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24225                return false;
24226            }
24227        }
24228        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24229            return false;
24230        }
24231        if (mExternalSourcesPolicy != null) {
24232            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24233            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24234                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24235            }
24236        }
24237        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24238    }
24239
24240    @Override
24241    public ComponentName getInstantAppResolverSettingsComponent() {
24242        return mInstantAppResolverSettingsComponent;
24243    }
24244
24245    @Override
24246    public ComponentName getInstantAppInstallerComponent() {
24247        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24248            return null;
24249        }
24250        return mInstantAppInstallerActivity == null
24251                ? null : mInstantAppInstallerActivity.getComponentName();
24252    }
24253
24254    @Override
24255    public String getInstantAppAndroidId(String packageName, int userId) {
24256        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24257                "getInstantAppAndroidId");
24258        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24259                true /* requireFullPermission */, false /* checkShell */,
24260                "getInstantAppAndroidId");
24261        // Make sure the target is an Instant App.
24262        if (!isInstantApp(packageName, userId)) {
24263            return null;
24264        }
24265        synchronized (mPackages) {
24266            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24267        }
24268    }
24269
24270    boolean canHaveOatDir(String packageName) {
24271        synchronized (mPackages) {
24272            PackageParser.Package p = mPackages.get(packageName);
24273            if (p == null) {
24274                return false;
24275            }
24276            return p.canHaveOatDir();
24277        }
24278    }
24279
24280    private String getOatDir(PackageParser.Package pkg) {
24281        if (!pkg.canHaveOatDir()) {
24282            return null;
24283        }
24284        File codePath = new File(pkg.codePath);
24285        if (codePath.isDirectory()) {
24286            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24287        }
24288        return null;
24289    }
24290
24291    void deleteOatArtifactsOfPackage(String packageName) {
24292        final String[] instructionSets;
24293        final List<String> codePaths;
24294        final String oatDir;
24295        final PackageParser.Package pkg;
24296        synchronized (mPackages) {
24297            pkg = mPackages.get(packageName);
24298        }
24299        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24300        codePaths = pkg.getAllCodePaths();
24301        oatDir = getOatDir(pkg);
24302
24303        for (String codePath : codePaths) {
24304            for (String isa : instructionSets) {
24305                try {
24306                    mInstaller.deleteOdex(codePath, isa, oatDir);
24307                } catch (InstallerException e) {
24308                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24309                }
24310            }
24311        }
24312    }
24313
24314    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24315        Set<String> unusedPackages = new HashSet<>();
24316        long currentTimeInMillis = System.currentTimeMillis();
24317        synchronized (mPackages) {
24318            for (PackageParser.Package pkg : mPackages.values()) {
24319                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24320                if (ps == null) {
24321                    continue;
24322                }
24323                PackageDexUsage.PackageUseInfo packageUseInfo =
24324                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24325                if (PackageManagerServiceUtils
24326                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24327                                downgradeTimeThresholdMillis, packageUseInfo,
24328                                pkg.getLatestPackageUseTimeInMills(),
24329                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24330                    unusedPackages.add(pkg.packageName);
24331                }
24332            }
24333        }
24334        return unusedPackages;
24335    }
24336
24337    @Override
24338    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24339            int userId) {
24340        final int callingUid = Binder.getCallingUid();
24341        final int callingAppId = UserHandle.getAppId(callingUid);
24342
24343        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24344                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24345
24346        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24347                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24348            throw new SecurityException("Caller must have the "
24349                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24350        }
24351
24352        synchronized(mPackages) {
24353            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24354            scheduleWritePackageRestrictionsLocked(userId);
24355        }
24356    }
24357
24358    @Nullable
24359    @Override
24360    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24361        final int callingUid = Binder.getCallingUid();
24362        final int callingAppId = UserHandle.getAppId(callingUid);
24363
24364        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24365                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24366
24367        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24368                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24369            throw new SecurityException("Caller must have the "
24370                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24371        }
24372
24373        synchronized(mPackages) {
24374            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24375        }
24376    }
24377
24378    @Override
24379    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24380        final int callingUid = Binder.getCallingUid();
24381        final int callingAppId = UserHandle.getAppId(callingUid);
24382
24383        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24384                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24385
24386        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24387                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24388            throw new SecurityException("Caller must have the "
24389                    + MANAGE_DEVICE_ADMINS + " permission.");
24390        }
24391
24392        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24393    }
24394}
24395
24396interface PackageSender {
24397    /**
24398     * @param userIds User IDs where the action occurred on a full application
24399     * @param instantUserIds User IDs where the action occurred on an instant application
24400     */
24401    void sendPackageBroadcast(final String action, final String pkg,
24402        final Bundle extras, final int flags, final String targetPkg,
24403        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24404    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24405        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24406    void notifyPackageAdded(String packageName);
24407    void notifyPackageRemoved(String packageName);
24408}
24409