PackageManagerService.java revision 2cf94bf6988a2be160288f92c029082c661590cf
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.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
26import static android.Manifest.permission.WRITE_MEDIA_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_SANDBOX_VERSION_DOWNGRADE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
57import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
58import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
59import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
60import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
61import static android.content.pm.PackageManager.INSTALL_INTERNAL;
62import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
67import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
68import static android.content.pm.PackageManager.MATCH_ALL;
69import static android.content.pm.PackageManager.MATCH_ANY_USER;
70import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
72import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
73import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
74import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
75import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
76import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
77import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
78import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
79import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
80import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
81import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
82import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
83import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
84import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
85import static android.content.pm.PackageManager.PERMISSION_DENIED;
86import static android.content.pm.PackageManager.PERMISSION_GRANTED;
87import static android.content.pm.PackageParser.isApkFile;
88import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
89import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
90import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
91import static android.system.OsConstants.O_CREAT;
92import static android.system.OsConstants.O_RDWR;
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
106import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
107import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
108import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
109import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
110import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
111import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
112import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
113import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasCertificate;
114import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasSha256Certificate;
115import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
117import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
118import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
119
120import android.Manifest;
121import android.annotation.IntDef;
122import android.annotation.NonNull;
123import android.annotation.Nullable;
124import android.app.ActivityManager;
125import android.app.ActivityManagerInternal;
126import android.app.AppOpsManager;
127import android.app.IActivityManager;
128import android.app.ResourcesManager;
129import android.app.admin.IDevicePolicyManager;
130import android.app.admin.SecurityLog;
131import android.app.backup.IBackupManager;
132import android.content.BroadcastReceiver;
133import android.content.ComponentName;
134import android.content.ContentResolver;
135import android.content.Context;
136import android.content.IIntentReceiver;
137import android.content.Intent;
138import android.content.IntentFilter;
139import android.content.IntentSender;
140import android.content.IntentSender.SendIntentException;
141import android.content.ServiceConnection;
142import android.content.pm.ActivityInfo;
143import android.content.pm.ApplicationInfo;
144import android.content.pm.AppsQueryHelper;
145import android.content.pm.AuxiliaryResolveInfo;
146import android.content.pm.ChangedPackages;
147import android.content.pm.ComponentInfo;
148import android.content.pm.FallbackCategoryProvider;
149import android.content.pm.FeatureInfo;
150import android.content.pm.IDexModuleRegisterCallback;
151import android.content.pm.IOnPermissionsChangeListener;
152import android.content.pm.IPackageDataObserver;
153import android.content.pm.IPackageDeleteObserver;
154import android.content.pm.IPackageDeleteObserver2;
155import android.content.pm.IPackageInstallObserver2;
156import android.content.pm.IPackageInstaller;
157import android.content.pm.IPackageManager;
158import android.content.pm.IPackageManagerNative;
159import android.content.pm.IPackageMoveObserver;
160import android.content.pm.IPackageStatsObserver;
161import android.content.pm.InstantAppInfo;
162import android.content.pm.InstantAppRequest;
163import android.content.pm.InstantAppResolveInfo;
164import android.content.pm.InstrumentationInfo;
165import android.content.pm.IntentFilterVerificationInfo;
166import android.content.pm.KeySet;
167import android.content.pm.PackageCleanItem;
168import android.content.pm.PackageInfo;
169import android.content.pm.PackageInfoLite;
170import android.content.pm.PackageInstaller;
171import android.content.pm.PackageList;
172import android.content.pm.PackageManager;
173import android.content.pm.PackageManagerInternal;
174import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
175import android.content.pm.PackageManagerInternal.PackageListObserver;
176import android.content.pm.PackageParser;
177import android.content.pm.PackageParser.ActivityIntentInfo;
178import android.content.pm.PackageParser.Package;
179import android.content.pm.PackageParser.PackageLite;
180import android.content.pm.PackageParser.PackageParserException;
181import android.content.pm.PackageParser.ParseFlags;
182import android.content.pm.PackageParser.ServiceIntentInfo;
183import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
184import android.content.pm.PackageStats;
185import android.content.pm.PackageUserState;
186import android.content.pm.ParceledListSlice;
187import android.content.pm.PermissionGroupInfo;
188import android.content.pm.PermissionInfo;
189import android.content.pm.ProviderInfo;
190import android.content.pm.ResolveInfo;
191import android.content.pm.ServiceInfo;
192import android.content.pm.SharedLibraryInfo;
193import android.content.pm.Signature;
194import android.content.pm.UserInfo;
195import android.content.pm.VerifierDeviceIdentity;
196import android.content.pm.VerifierInfo;
197import android.content.pm.VersionedPackage;
198import android.content.pm.dex.DexMetadataHelper;
199import android.content.pm.dex.IArtManager;
200import android.content.res.Resources;
201import android.database.ContentObserver;
202import android.graphics.Bitmap;
203import android.hardware.display.DisplayManager;
204import android.net.Uri;
205import android.os.Binder;
206import android.os.Build;
207import android.os.Bundle;
208import android.os.Debug;
209import android.os.Environment;
210import android.os.Environment.UserEnvironment;
211import android.os.FileUtils;
212import android.os.Handler;
213import android.os.IBinder;
214import android.os.Looper;
215import android.os.Message;
216import android.os.Parcel;
217import android.os.ParcelFileDescriptor;
218import android.os.PatternMatcher;
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.DisplayMetrics;
251import android.util.EventLog;
252import android.util.ExceptionUtils;
253import android.util.Log;
254import android.util.LogPrinter;
255import android.util.LongSparseArray;
256import android.util.LongSparseLongArray;
257import android.util.MathUtils;
258import android.util.PackageUtils;
259import android.util.Pair;
260import android.util.PrintStreamPrinter;
261import android.util.Slog;
262import android.util.SparseArray;
263import android.util.SparseBooleanArray;
264import android.util.SparseIntArray;
265import android.util.TimingsTraceLog;
266import android.util.Xml;
267import android.util.jar.StrictJarFile;
268import android.util.proto.ProtoOutputStream;
269import android.view.Display;
270
271import com.android.internal.R;
272import com.android.internal.annotations.GuardedBy;
273import com.android.internal.app.IMediaContainerService;
274import com.android.internal.app.ResolverActivity;
275import com.android.internal.content.NativeLibraryHelper;
276import com.android.internal.content.PackageHelper;
277import com.android.internal.logging.MetricsLogger;
278import com.android.internal.os.IParcelFileDescriptorFactory;
279import com.android.internal.os.SomeArgs;
280import com.android.internal.os.Zygote;
281import com.android.internal.telephony.CarrierAppUtils;
282import com.android.internal.util.ArrayUtils;
283import com.android.internal.util.ConcurrentUtils;
284import com.android.internal.util.DumpUtils;
285import com.android.internal.util.FastXmlSerializer;
286import com.android.internal.util.IndentingPrintWriter;
287import com.android.internal.util.Preconditions;
288import com.android.internal.util.XmlUtils;
289import com.android.server.AttributeCache;
290import com.android.server.DeviceIdleController;
291import com.android.server.EventLogTags;
292import com.android.server.FgThread;
293import com.android.server.IntentResolver;
294import com.android.server.LocalServices;
295import com.android.server.LockGuard;
296import com.android.server.ServiceThread;
297import com.android.server.SystemConfig;
298import com.android.server.SystemServerInitThreadPool;
299import com.android.server.Watchdog;
300import com.android.server.net.NetworkPolicyManagerInternal;
301import com.android.server.pm.Installer.InstallerException;
302import com.android.server.pm.Settings.DatabaseVersion;
303import com.android.server.pm.Settings.VersionInfo;
304import com.android.server.pm.dex.ArtManagerService;
305import com.android.server.pm.dex.DexLogger;
306import com.android.server.pm.dex.DexManager;
307import com.android.server.pm.dex.DexoptOptions;
308import com.android.server.pm.dex.PackageDexUsage;
309import com.android.server.pm.permission.BasePermission;
310import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
311import com.android.server.pm.permission.PermissionManagerService;
312import com.android.server.pm.permission.PermissionManagerInternal;
313import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
314import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
315import com.android.server.pm.permission.PermissionsState;
316import com.android.server.pm.permission.PermissionsState.PermissionState;
317import com.android.server.storage.DeviceStorageMonitorInternal;
318
319import dalvik.system.CloseGuard;
320import dalvik.system.VMRuntime;
321
322import libcore.io.IoUtils;
323
324import org.xmlpull.v1.XmlPullParser;
325import org.xmlpull.v1.XmlPullParserException;
326import org.xmlpull.v1.XmlSerializer;
327
328import java.io.BufferedOutputStream;
329import java.io.ByteArrayInputStream;
330import java.io.ByteArrayOutputStream;
331import java.io.File;
332import java.io.FileDescriptor;
333import java.io.FileInputStream;
334import java.io.FileOutputStream;
335import java.io.FilenameFilter;
336import java.io.IOException;
337import java.io.PrintWriter;
338import java.lang.annotation.Retention;
339import java.lang.annotation.RetentionPolicy;
340import java.nio.charset.StandardCharsets;
341import java.security.DigestInputStream;
342import java.security.MessageDigest;
343import java.security.NoSuchAlgorithmException;
344import java.security.PublicKey;
345import java.security.SecureRandom;
346import java.security.cert.CertificateException;
347import java.util.ArrayList;
348import java.util.Arrays;
349import java.util.Collection;
350import java.util.Collections;
351import java.util.Comparator;
352import java.util.HashMap;
353import java.util.HashSet;
354import java.util.Iterator;
355import java.util.LinkedHashSet;
356import java.util.List;
357import java.util.Map;
358import java.util.Objects;
359import java.util.Set;
360import java.util.concurrent.CountDownLatch;
361import java.util.concurrent.Future;
362import java.util.concurrent.TimeUnit;
363import java.util.concurrent.atomic.AtomicBoolean;
364import java.util.concurrent.atomic.AtomicInteger;
365
366/**
367 * Keep track of all those APKs everywhere.
368 * <p>
369 * Internally there are two important locks:
370 * <ul>
371 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
372 * and other related state. It is a fine-grained lock that should only be held
373 * momentarily, as it's one of the most contended locks in the system.
374 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
375 * operations typically involve heavy lifting of application data on disk. Since
376 * {@code installd} is single-threaded, and it's operations can often be slow,
377 * this lock should never be acquired while already holding {@link #mPackages}.
378 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
379 * holding {@link #mInstallLock}.
380 * </ul>
381 * Many internal methods rely on the caller to hold the appropriate locks, and
382 * this contract is expressed through method name suffixes:
383 * <ul>
384 * <li>fooLI(): the caller must hold {@link #mInstallLock}
385 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
386 * being modified must be frozen
387 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
388 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
389 * </ul>
390 * <p>
391 * Because this class is very central to the platform's security; please run all
392 * CTS and unit tests whenever making modifications:
393 *
394 * <pre>
395 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
396 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
397 * </pre>
398 */
399public class PackageManagerService extends IPackageManager.Stub
400        implements PackageSender {
401    static final String TAG = "PackageManager";
402    public static final boolean DEBUG_SETTINGS = false;
403    static final boolean DEBUG_PREFERRED = false;
404    static final boolean DEBUG_UPGRADE = false;
405    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
406    private static final boolean DEBUG_BACKUP = false;
407    public static final boolean DEBUG_INSTALL = false;
408    public static final boolean DEBUG_REMOVE = false;
409    private static final boolean DEBUG_BROADCASTS = false;
410    private static final boolean DEBUG_SHOW_INFO = false;
411    private static final boolean DEBUG_PACKAGE_INFO = false;
412    private static final boolean DEBUG_INTENT_MATCHING = false;
413    public static final boolean DEBUG_PACKAGE_SCANNING = false;
414    private static final boolean DEBUG_VERIFY = false;
415    private static final boolean DEBUG_FILTERS = false;
416    public static final boolean DEBUG_PERMISSIONS = false;
417    private static final boolean DEBUG_SHARED_LIBRARIES = false;
418    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
419
420    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
421    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
422    // user, but by default initialize to this.
423    public static final boolean DEBUG_DEXOPT = false;
424
425    private static final boolean DEBUG_ABI_SELECTION = false;
426    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
427    private static final boolean DEBUG_TRIAGED_MISSING = false;
428    private static final boolean DEBUG_APP_DATA = false;
429
430    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
431    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
432
433    private static final boolean HIDE_EPHEMERAL_APIS = false;
434
435    private static final boolean ENABLE_FREE_CACHE_V2 =
436            SystemProperties.getBoolean("fw.free_cache_v2", true);
437
438    private static final int RADIO_UID = Process.PHONE_UID;
439    private static final int LOG_UID = Process.LOG_UID;
440    private static final int NFC_UID = Process.NFC_UID;
441    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
442    private static final int SHELL_UID = Process.SHELL_UID;
443
444    // Suffix used during package installation when copying/moving
445    // package apks to install directory.
446    private static final String INSTALL_PACKAGE_SUFFIX = "-";
447
448    static final int SCAN_NO_DEX = 1<<0;
449    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
450    static final int SCAN_NEW_INSTALL = 1<<2;
451    static final int SCAN_UPDATE_TIME = 1<<3;
452    static final int SCAN_BOOTING = 1<<4;
453    static final int SCAN_TRUSTED_OVERLAY = 1<<5;
454    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
455    static final int SCAN_REQUIRE_KNOWN = 1<<7;
456    static final int SCAN_MOVE = 1<<8;
457    static final int SCAN_INITIAL = 1<<9;
458    static final int SCAN_CHECK_ONLY = 1<<10;
459    static final int SCAN_DONT_KILL_APP = 1<<11;
460    static final int SCAN_IGNORE_FROZEN = 1<<12;
461    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
462    static final int SCAN_AS_INSTANT_APP = 1<<14;
463    static final int SCAN_AS_FULL_APP = 1<<15;
464    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
465    static final int SCAN_AS_SYSTEM = 1<<17;
466    static final int SCAN_AS_PRIVILEGED = 1<<18;
467    static final int SCAN_AS_OEM = 1<<19;
468    static final int SCAN_AS_VENDOR = 1<<20;
469
470    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
471            SCAN_NO_DEX,
472            SCAN_UPDATE_SIGNATURE,
473            SCAN_NEW_INSTALL,
474            SCAN_UPDATE_TIME,
475            SCAN_BOOTING,
476            SCAN_TRUSTED_OVERLAY,
477            SCAN_DELETE_DATA_ON_FAILURES,
478            SCAN_REQUIRE_KNOWN,
479            SCAN_MOVE,
480            SCAN_INITIAL,
481            SCAN_CHECK_ONLY,
482            SCAN_DONT_KILL_APP,
483            SCAN_IGNORE_FROZEN,
484            SCAN_FIRST_BOOT_OR_UPGRADE,
485            SCAN_AS_INSTANT_APP,
486            SCAN_AS_FULL_APP,
487            SCAN_AS_VIRTUAL_PRELOAD,
488    })
489    @Retention(RetentionPolicy.SOURCE)
490    public @interface ScanFlags {}
491
492    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
493    /** Extension of the compressed packages */
494    public final static String COMPRESSED_EXTENSION = ".gz";
495    /** Suffix of stub packages on the system partition */
496    public final static String STUB_SUFFIX = "-Stub";
497
498    private static final int[] EMPTY_INT_ARRAY = new int[0];
499
500    private static final int TYPE_UNKNOWN = 0;
501    private static final int TYPE_ACTIVITY = 1;
502    private static final int TYPE_RECEIVER = 2;
503    private static final int TYPE_SERVICE = 3;
504    private static final int TYPE_PROVIDER = 4;
505    @IntDef(prefix = { "TYPE_" }, value = {
506            TYPE_UNKNOWN,
507            TYPE_ACTIVITY,
508            TYPE_RECEIVER,
509            TYPE_SERVICE,
510            TYPE_PROVIDER,
511    })
512    @Retention(RetentionPolicy.SOURCE)
513    public @interface ComponentType {}
514
515    /**
516     * Timeout (in milliseconds) after which the watchdog should declare that
517     * our handler thread is wedged.  The usual default for such things is one
518     * minute but we sometimes do very lengthy I/O operations on this thread,
519     * such as installing multi-gigabyte applications, so ours needs to be longer.
520     */
521    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
522
523    /**
524     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
525     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
526     * settings entry if available, otherwise we use the hardcoded default.  If it's been
527     * more than this long since the last fstrim, we force one during the boot sequence.
528     *
529     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
530     * one gets run at the next available charging+idle time.  This final mandatory
531     * no-fstrim check kicks in only of the other scheduling criteria is never met.
532     */
533    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
534
535    /**
536     * Whether verification is enabled by default.
537     */
538    private static final boolean DEFAULT_VERIFY_ENABLE = true;
539
540    /**
541     * The default maximum time to wait for the verification agent to return in
542     * milliseconds.
543     */
544    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
545
546    /**
547     * The default response for package verification timeout.
548     *
549     * This can be either PackageManager.VERIFICATION_ALLOW or
550     * PackageManager.VERIFICATION_REJECT.
551     */
552    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
553
554    public static final String PLATFORM_PACKAGE_NAME = "android";
555
556    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
557
558    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
559            DEFAULT_CONTAINER_PACKAGE,
560            "com.android.defcontainer.DefaultContainerService");
561
562    private static final String KILL_APP_REASON_GIDS_CHANGED =
563            "permission grant or revoke changed gids";
564
565    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
566            "permissions revoked";
567
568    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
569
570    private static final String PACKAGE_SCHEME = "package";
571
572    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
573
574    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
575
576    /** Canonical intent used to identify what counts as a "web browser" app */
577    private static final Intent sBrowserIntent;
578    static {
579        sBrowserIntent = new Intent();
580        sBrowserIntent.setAction(Intent.ACTION_VIEW);
581        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
582        sBrowserIntent.setData(Uri.parse("http:"));
583    }
584
585    /**
586     * The set of all protected actions [i.e. those actions for which a high priority
587     * intent filter is disallowed].
588     */
589    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
590    static {
591        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
592        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
593        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
594        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
595    }
596
597    // Compilation reasons.
598    public static final int REASON_FIRST_BOOT = 0;
599    public static final int REASON_BOOT = 1;
600    public static final int REASON_INSTALL = 2;
601    public static final int REASON_BACKGROUND_DEXOPT = 3;
602    public static final int REASON_AB_OTA = 4;
603    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
604    public static final int REASON_SHARED = 6;
605
606    public static final int REASON_LAST = REASON_SHARED;
607
608    /**
609     * Version number for the package parser cache. Increment this whenever the format or
610     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
611     */
612    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
613
614    /**
615     * Whether the package parser cache is enabled.
616     */
617    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
618
619    /**
620     * Permissions required in order to receive instant application lifecycle broadcasts.
621     */
622    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
623            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
624
625    final ServiceThread mHandlerThread;
626
627    final PackageHandler mHandler;
628
629    private final ProcessLoggingHandler mProcessLoggingHandler;
630
631    /**
632     * Messages for {@link #mHandler} that need to wait for system ready before
633     * being dispatched.
634     */
635    private ArrayList<Message> mPostSystemReadyMessages;
636
637    final int mSdkVersion = Build.VERSION.SDK_INT;
638
639    final Context mContext;
640    final boolean mFactoryTest;
641    final boolean mOnlyCore;
642    final DisplayMetrics mMetrics;
643    final int mDefParseFlags;
644    final String[] mSeparateProcesses;
645    final boolean mIsUpgrade;
646    final boolean mIsPreNUpgrade;
647    final boolean mIsPreNMR1Upgrade;
648
649    // Have we told the Activity Manager to whitelist the default container service by uid yet?
650    @GuardedBy("mPackages")
651    boolean mDefaultContainerWhitelisted = false;
652
653    @GuardedBy("mPackages")
654    private boolean mDexOptDialogShown;
655
656    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
657    // LOCK HELD.  Can be called with mInstallLock held.
658    @GuardedBy("mInstallLock")
659    final Installer mInstaller;
660
661    /** Directory where installed applications are stored */
662    private static final File sAppInstallDir =
663            new File(Environment.getDataDirectory(), "app");
664    /** Directory where installed application's 32-bit native libraries are copied. */
665    private static final File sAppLib32InstallDir =
666            new File(Environment.getDataDirectory(), "app-lib");
667    /** Directory where code and non-resource assets of forward-locked applications are stored */
668    private static final File sDrmAppPrivateInstallDir =
669            new File(Environment.getDataDirectory(), "app-private");
670
671    // ----------------------------------------------------------------
672
673    // Lock for state used when installing and doing other long running
674    // operations.  Methods that must be called with this lock held have
675    // the suffix "LI".
676    final Object mInstallLock = new Object();
677
678    // ----------------------------------------------------------------
679
680    // Keys are String (package name), values are Package.  This also serves
681    // as the lock for the global state.  Methods that must be called with
682    // this lock held have the prefix "LP".
683    @GuardedBy("mPackages")
684    final ArrayMap<String, PackageParser.Package> mPackages =
685            new ArrayMap<String, PackageParser.Package>();
686
687    final ArrayMap<String, Set<String>> mKnownCodebase =
688            new ArrayMap<String, Set<String>>();
689
690    // Keys are isolated uids and values are the uid of the application
691    // that created the isolated proccess.
692    @GuardedBy("mPackages")
693    final SparseIntArray mIsolatedOwners = new SparseIntArray();
694
695    /**
696     * Tracks new system packages [received in an OTA] that we expect to
697     * find updated user-installed versions. Keys are package name, values
698     * are package location.
699     */
700    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
701    /**
702     * Tracks high priority intent filters for protected actions. During boot, certain
703     * filter actions are protected and should never be allowed to have a high priority
704     * intent filter for them. However, there is one, and only one exception -- the
705     * setup wizard. It must be able to define a high priority intent filter for these
706     * actions to ensure there are no escapes from the wizard. We need to delay processing
707     * of these during boot as we need to look at all of the system packages in order
708     * to know which component is the setup wizard.
709     */
710    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
711    /**
712     * Whether or not processing protected filters should be deferred.
713     */
714    private boolean mDeferProtectedFilters = true;
715
716    /**
717     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
718     */
719    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
720    /**
721     * Whether or not system app permissions should be promoted from install to runtime.
722     */
723    boolean mPromoteSystemApps;
724
725    @GuardedBy("mPackages")
726    final Settings mSettings;
727
728    /**
729     * Set of package names that are currently "frozen", which means active
730     * surgery is being done on the code/data for that package. The platform
731     * will refuse to launch frozen packages to avoid race conditions.
732     *
733     * @see PackageFreezer
734     */
735    @GuardedBy("mPackages")
736    final ArraySet<String> mFrozenPackages = new ArraySet<>();
737
738    final ProtectedPackages mProtectedPackages;
739
740    @GuardedBy("mLoadedVolumes")
741    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
742
743    boolean mFirstBoot;
744
745    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
746
747    @GuardedBy("mAvailableFeatures")
748    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
749
750    private final InstantAppRegistry mInstantAppRegistry;
751
752    @GuardedBy("mPackages")
753    int mChangedPackagesSequenceNumber;
754    /**
755     * List of changed [installed, removed or updated] packages.
756     * mapping from user id -> sequence number -> package name
757     */
758    @GuardedBy("mPackages")
759    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
760    /**
761     * The sequence number of the last change to a package.
762     * mapping from user id -> package name -> sequence number
763     */
764    @GuardedBy("mPackages")
765    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
766
767    @GuardedBy("mPackages")
768    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
769
770    class PackageParserCallback implements PackageParser.Callback {
771        @Override public final boolean hasFeature(String feature) {
772            return PackageManagerService.this.hasSystemFeature(feature, 0);
773        }
774
775        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
776                Collection<PackageParser.Package> allPackages, String targetPackageName) {
777            List<PackageParser.Package> overlayPackages = null;
778            for (PackageParser.Package p : allPackages) {
779                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
780                    if (overlayPackages == null) {
781                        overlayPackages = new ArrayList<PackageParser.Package>();
782                    }
783                    overlayPackages.add(p);
784                }
785            }
786            if (overlayPackages != null) {
787                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
788                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
789                        return p1.mOverlayPriority - p2.mOverlayPriority;
790                    }
791                };
792                Collections.sort(overlayPackages, cmp);
793            }
794            return overlayPackages;
795        }
796
797        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
798                String targetPackageName, String targetPath) {
799            if ("android".equals(targetPackageName)) {
800                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
801                // native AssetManager.
802                return null;
803            }
804            List<PackageParser.Package> overlayPackages =
805                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
806            if (overlayPackages == null || overlayPackages.isEmpty()) {
807                return null;
808            }
809            List<String> overlayPathList = null;
810            for (PackageParser.Package overlayPackage : overlayPackages) {
811                if (targetPath == null) {
812                    if (overlayPathList == null) {
813                        overlayPathList = new ArrayList<String>();
814                    }
815                    overlayPathList.add(overlayPackage.baseCodePath);
816                    continue;
817                }
818
819                try {
820                    // Creates idmaps for system to parse correctly the Android manifest of the
821                    // target package.
822                    //
823                    // OverlayManagerService will update each of them with a correct gid from its
824                    // target package app id.
825                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
826                            UserHandle.getSharedAppGid(
827                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
828                    if (overlayPathList == null) {
829                        overlayPathList = new ArrayList<String>();
830                    }
831                    overlayPathList.add(overlayPackage.baseCodePath);
832                } catch (InstallerException e) {
833                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
834                            overlayPackage.baseCodePath);
835                }
836            }
837            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
838        }
839
840        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
841            synchronized (mPackages) {
842                return getStaticOverlayPathsLocked(
843                        mPackages.values(), targetPackageName, targetPath);
844            }
845        }
846
847        @Override public final String[] getOverlayApks(String targetPackageName) {
848            return getStaticOverlayPaths(targetPackageName, null);
849        }
850
851        @Override public final String[] getOverlayPaths(String targetPackageName,
852                String targetPath) {
853            return getStaticOverlayPaths(targetPackageName, targetPath);
854        }
855    }
856
857    class ParallelPackageParserCallback extends PackageParserCallback {
858        List<PackageParser.Package> mOverlayPackages = null;
859
860        void findStaticOverlayPackages() {
861            synchronized (mPackages) {
862                for (PackageParser.Package p : mPackages.values()) {
863                    if (p.mIsStaticOverlay) {
864                        if (mOverlayPackages == null) {
865                            mOverlayPackages = new ArrayList<PackageParser.Package>();
866                        }
867                        mOverlayPackages.add(p);
868                    }
869                }
870            }
871        }
872
873        @Override
874        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
875            // We can trust mOverlayPackages without holding mPackages because package uninstall
876            // can't happen while running parallel parsing.
877            // Moreover holding mPackages on each parsing thread causes dead-lock.
878            return mOverlayPackages == null ? null :
879                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
880        }
881    }
882
883    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
884    final ParallelPackageParserCallback mParallelPackageParserCallback =
885            new ParallelPackageParserCallback();
886
887    public static final class SharedLibraryEntry {
888        public final @Nullable String path;
889        public final @Nullable String apk;
890        public final @NonNull SharedLibraryInfo info;
891
892        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
893                String declaringPackageName, long declaringPackageVersionCode) {
894            path = _path;
895            apk = _apk;
896            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
897                    declaringPackageName, declaringPackageVersionCode), null);
898        }
899    }
900
901    // Currently known shared libraries.
902    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
903    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
904            new ArrayMap<>();
905
906    // All available activities, for your resolving pleasure.
907    final ActivityIntentResolver mActivities =
908            new ActivityIntentResolver();
909
910    // All available receivers, for your resolving pleasure.
911    final ActivityIntentResolver mReceivers =
912            new ActivityIntentResolver();
913
914    // All available services, for your resolving pleasure.
915    final ServiceIntentResolver mServices = new ServiceIntentResolver();
916
917    // All available providers, for your resolving pleasure.
918    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
919
920    // Mapping from provider base names (first directory in content URI codePath)
921    // to the provider information.
922    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
923            new ArrayMap<String, PackageParser.Provider>();
924
925    // Mapping from instrumentation class names to info about them.
926    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
927            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
928
929    // Packages whose data we have transfered into another package, thus
930    // should no longer exist.
931    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
932
933    // Broadcast actions that are only available to the system.
934    @GuardedBy("mProtectedBroadcasts")
935    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
936
937    /** List of packages waiting for verification. */
938    final SparseArray<PackageVerificationState> mPendingVerification
939            = new SparseArray<PackageVerificationState>();
940
941    final PackageInstallerService mInstallerService;
942
943    final ArtManagerService mArtManagerService;
944
945    private final PackageDexOptimizer mPackageDexOptimizer;
946    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
947    // is used by other apps).
948    private final DexManager mDexManager;
949
950    private AtomicInteger mNextMoveId = new AtomicInteger();
951    private final MoveCallbacks mMoveCallbacks;
952
953    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
954
955    // Cache of users who need badging.
956    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
957
958    /** Token for keys in mPendingVerification. */
959    private int mPendingVerificationToken = 0;
960
961    volatile boolean mSystemReady;
962    volatile boolean mSafeMode;
963    volatile boolean mHasSystemUidErrors;
964    private volatile boolean mEphemeralAppsDisabled;
965
966    ApplicationInfo mAndroidApplication;
967    final ActivityInfo mResolveActivity = new ActivityInfo();
968    final ResolveInfo mResolveInfo = new ResolveInfo();
969    ComponentName mResolveComponentName;
970    PackageParser.Package mPlatformPackage;
971    ComponentName mCustomResolverComponentName;
972
973    boolean mResolverReplaced = false;
974
975    private final @Nullable ComponentName mIntentFilterVerifierComponent;
976    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
977
978    private int mIntentFilterVerificationToken = 0;
979
980    /** The service connection to the ephemeral resolver */
981    final EphemeralResolverConnection mInstantAppResolverConnection;
982    /** Component used to show resolver settings for Instant Apps */
983    final ComponentName mInstantAppResolverSettingsComponent;
984
985    /** Activity used to install instant applications */
986    ActivityInfo mInstantAppInstallerActivity;
987    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
988
989    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
990            = new SparseArray<IntentFilterVerificationState>();
991
992    // TODO remove this and go through mPermissonManager directly
993    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
994    private final PermissionManagerInternal mPermissionManager;
995
996    // List of packages names to keep cached, even if they are uninstalled for all users
997    private List<String> mKeepUninstalledPackages;
998
999    private UserManagerInternal mUserManagerInternal;
1000    private ActivityManagerInternal mActivityManagerInternal;
1001
1002    private DeviceIdleController.LocalService mDeviceIdleController;
1003
1004    private File mCacheDir;
1005
1006    private Future<?> mPrepareAppDataFuture;
1007
1008    private static class IFVerificationParams {
1009        PackageParser.Package pkg;
1010        boolean replacing;
1011        int userId;
1012        int verifierUid;
1013
1014        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1015                int _userId, int _verifierUid) {
1016            pkg = _pkg;
1017            replacing = _replacing;
1018            userId = _userId;
1019            replacing = _replacing;
1020            verifierUid = _verifierUid;
1021        }
1022    }
1023
1024    private interface IntentFilterVerifier<T extends IntentFilter> {
1025        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1026                                               T filter, String packageName);
1027        void startVerifications(int userId);
1028        void receiveVerificationResponse(int verificationId);
1029    }
1030
1031    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1032        private Context mContext;
1033        private ComponentName mIntentFilterVerifierComponent;
1034        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1035
1036        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1037            mContext = context;
1038            mIntentFilterVerifierComponent = verifierComponent;
1039        }
1040
1041        private String getDefaultScheme() {
1042            return IntentFilter.SCHEME_HTTPS;
1043        }
1044
1045        @Override
1046        public void startVerifications(int userId) {
1047            // Launch verifications requests
1048            int count = mCurrentIntentFilterVerifications.size();
1049            for (int n=0; n<count; n++) {
1050                int verificationId = mCurrentIntentFilterVerifications.get(n);
1051                final IntentFilterVerificationState ivs =
1052                        mIntentFilterVerificationStates.get(verificationId);
1053
1054                String packageName = ivs.getPackageName();
1055
1056                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1057                final int filterCount = filters.size();
1058                ArraySet<String> domainsSet = new ArraySet<>();
1059                for (int m=0; m<filterCount; m++) {
1060                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1061                    domainsSet.addAll(filter.getHostsList());
1062                }
1063                synchronized (mPackages) {
1064                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1065                            packageName, domainsSet) != null) {
1066                        scheduleWriteSettingsLocked();
1067                    }
1068                }
1069                sendVerificationRequest(verificationId, ivs);
1070            }
1071            mCurrentIntentFilterVerifications.clear();
1072        }
1073
1074        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1075            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1078                    verificationId);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1081                    getDefaultScheme());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1084                    ivs.getHostsString());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1087                    ivs.getPackageName());
1088            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1089            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1090
1091            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1092            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1093                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1094                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1095
1096            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1097            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1098                    "Sending IntentFilter verification broadcast");
1099        }
1100
1101        public void receiveVerificationResponse(int verificationId) {
1102            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1103
1104            final boolean verified = ivs.isVerified();
1105
1106            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1107            final int count = filters.size();
1108            if (DEBUG_DOMAIN_VERIFICATION) {
1109                Slog.i(TAG, "Received verification response " + verificationId
1110                        + " for " + count + " filters, verified=" + verified);
1111            }
1112            for (int n=0; n<count; n++) {
1113                PackageParser.ActivityIntentInfo filter = filters.get(n);
1114                filter.setVerified(verified);
1115
1116                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1117                        + " verified with result:" + verified + " and hosts:"
1118                        + ivs.getHostsString());
1119            }
1120
1121            mIntentFilterVerificationStates.remove(verificationId);
1122
1123            final String packageName = ivs.getPackageName();
1124            IntentFilterVerificationInfo ivi = null;
1125
1126            synchronized (mPackages) {
1127                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1128            }
1129            if (ivi == null) {
1130                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1131                        + verificationId + " packageName:" + packageName);
1132                return;
1133            }
1134            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1135                    "Updating IntentFilterVerificationInfo for package " + packageName
1136                            +" verificationId:" + verificationId);
1137
1138            synchronized (mPackages) {
1139                if (verified) {
1140                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1141                } else {
1142                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1143                }
1144                scheduleWriteSettingsLocked();
1145
1146                final int userId = ivs.getUserId();
1147                if (userId != UserHandle.USER_ALL) {
1148                    final int userStatus =
1149                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1150
1151                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1152                    boolean needUpdate = false;
1153
1154                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1155                    // already been set by the User thru the Disambiguation dialog
1156                    switch (userStatus) {
1157                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1158                            if (verified) {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1160                            } else {
1161                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1162                            }
1163                            needUpdate = true;
1164                            break;
1165
1166                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1167                            if (verified) {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1169                                needUpdate = true;
1170                            }
1171                            break;
1172
1173                        default:
1174                            // Nothing to do
1175                    }
1176
1177                    if (needUpdate) {
1178                        mSettings.updateIntentFilterVerificationStatusLPw(
1179                                packageName, updatedStatus, userId);
1180                        scheduleWritePackageRestrictionsLocked(userId);
1181                    }
1182                }
1183            }
1184        }
1185
1186        @Override
1187        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1188                    ActivityIntentInfo filter, String packageName) {
1189            if (!hasValidDomains(filter)) {
1190                return false;
1191            }
1192            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1193            if (ivs == null) {
1194                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1195                        packageName);
1196            }
1197            if (DEBUG_DOMAIN_VERIFICATION) {
1198                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1199            }
1200            ivs.addFilter(filter);
1201            return true;
1202        }
1203
1204        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1205                int userId, int verificationId, String packageName) {
1206            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1207                    verifierUid, userId, packageName);
1208            ivs.setPendingState();
1209            synchronized (mPackages) {
1210                mIntentFilterVerificationStates.append(verificationId, ivs);
1211                mCurrentIntentFilterVerifications.add(verificationId);
1212            }
1213            return ivs;
1214        }
1215    }
1216
1217    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1218        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1219                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1220                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1221    }
1222
1223    // Set of pending broadcasts for aggregating enable/disable of components.
1224    static class PendingPackageBroadcasts {
1225        // for each user id, a map of <package name -> components within that package>
1226        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1227
1228        public PendingPackageBroadcasts() {
1229            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1230        }
1231
1232        public ArrayList<String> get(int userId, String packageName) {
1233            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1234            return packages.get(packageName);
1235        }
1236
1237        public void put(int userId, String packageName, ArrayList<String> components) {
1238            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1239            packages.put(packageName, components);
1240        }
1241
1242        public void remove(int userId, String packageName) {
1243            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1244            if (packages != null) {
1245                packages.remove(packageName);
1246            }
1247        }
1248
1249        public void remove(int userId) {
1250            mUidMap.remove(userId);
1251        }
1252
1253        public int userIdCount() {
1254            return mUidMap.size();
1255        }
1256
1257        public int userIdAt(int n) {
1258            return mUidMap.keyAt(n);
1259        }
1260
1261        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1262            return mUidMap.get(userId);
1263        }
1264
1265        public int size() {
1266            // total number of pending broadcast entries across all userIds
1267            int num = 0;
1268            for (int i = 0; i< mUidMap.size(); i++) {
1269                num += mUidMap.valueAt(i).size();
1270            }
1271            return num;
1272        }
1273
1274        public void clear() {
1275            mUidMap.clear();
1276        }
1277
1278        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1279            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1280            if (map == null) {
1281                map = new ArrayMap<String, ArrayList<String>>();
1282                mUidMap.put(userId, map);
1283            }
1284            return map;
1285        }
1286    }
1287    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1288
1289    // Service Connection to remote media container service to copy
1290    // package uri's from external media onto secure containers
1291    // or internal storage.
1292    private IMediaContainerService mContainerService = null;
1293
1294    static final int SEND_PENDING_BROADCAST = 1;
1295    static final int MCS_BOUND = 3;
1296    static final int END_COPY = 4;
1297    static final int INIT_COPY = 5;
1298    static final int MCS_UNBIND = 6;
1299    static final int START_CLEANING_PACKAGE = 7;
1300    static final int FIND_INSTALL_LOC = 8;
1301    static final int POST_INSTALL = 9;
1302    static final int MCS_RECONNECT = 10;
1303    static final int MCS_GIVE_UP = 11;
1304    static final int WRITE_SETTINGS = 13;
1305    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1306    static final int PACKAGE_VERIFIED = 15;
1307    static final int CHECK_PENDING_VERIFICATION = 16;
1308    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1309    static final int INTENT_FILTER_VERIFIED = 18;
1310    static final int WRITE_PACKAGE_LIST = 19;
1311    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1312
1313    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1314
1315    // Delay time in millisecs
1316    static final int BROADCAST_DELAY = 10 * 1000;
1317
1318    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1319            2 * 60 * 60 * 1000L; /* two hours */
1320
1321    static UserManagerService sUserManager;
1322
1323    // Stores a list of users whose package restrictions file needs to be updated
1324    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1325
1326    final private DefaultContainerConnection mDefContainerConn =
1327            new DefaultContainerConnection();
1328    class DefaultContainerConnection implements ServiceConnection {
1329        public void onServiceConnected(ComponentName name, IBinder service) {
1330            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1331            final IMediaContainerService imcs = IMediaContainerService.Stub
1332                    .asInterface(Binder.allowBlocking(service));
1333            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1334        }
1335
1336        public void onServiceDisconnected(ComponentName name) {
1337            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1338        }
1339    }
1340
1341    // Recordkeeping of restore-after-install operations that are currently in flight
1342    // between the Package Manager and the Backup Manager
1343    static class PostInstallData {
1344        public InstallArgs args;
1345        public PackageInstalledInfo res;
1346
1347        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1348            args = _a;
1349            res = _r;
1350        }
1351    }
1352
1353    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1354    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1355
1356    // XML tags for backup/restore of various bits of state
1357    private static final String TAG_PREFERRED_BACKUP = "pa";
1358    private static final String TAG_DEFAULT_APPS = "da";
1359    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1360
1361    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1362    private static final String TAG_ALL_GRANTS = "rt-grants";
1363    private static final String TAG_GRANT = "grant";
1364    private static final String ATTR_PACKAGE_NAME = "pkg";
1365
1366    private static final String TAG_PERMISSION = "perm";
1367    private static final String ATTR_PERMISSION_NAME = "name";
1368    private static final String ATTR_IS_GRANTED = "g";
1369    private static final String ATTR_USER_SET = "set";
1370    private static final String ATTR_USER_FIXED = "fixed";
1371    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1372
1373    // System/policy permission grants are not backed up
1374    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1375            FLAG_PERMISSION_POLICY_FIXED
1376            | FLAG_PERMISSION_SYSTEM_FIXED
1377            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1378
1379    // And we back up these user-adjusted states
1380    private static final int USER_RUNTIME_GRANT_MASK =
1381            FLAG_PERMISSION_USER_SET
1382            | FLAG_PERMISSION_USER_FIXED
1383            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1384
1385    final @Nullable String mRequiredVerifierPackage;
1386    final @NonNull String mRequiredInstallerPackage;
1387    final @NonNull String mRequiredUninstallerPackage;
1388    final @Nullable String mSetupWizardPackage;
1389    final @Nullable String mStorageManagerPackage;
1390    final @NonNull String mServicesSystemSharedLibraryPackageName;
1391    final @NonNull String mSharedSystemSharedLibraryPackageName;
1392
1393    private final PackageUsage mPackageUsage = new PackageUsage();
1394    private final CompilerStats mCompilerStats = new CompilerStats();
1395
1396    class PackageHandler extends Handler {
1397        private boolean mBound = false;
1398        final ArrayList<HandlerParams> mPendingInstalls =
1399            new ArrayList<HandlerParams>();
1400
1401        private boolean connectToService() {
1402            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1403                    " DefaultContainerService");
1404            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1405            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1407                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1408                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409                mBound = true;
1410                return true;
1411            }
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413            return false;
1414        }
1415
1416        private void disconnectService() {
1417            mContainerService = null;
1418            mBound = false;
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            mContext.unbindService(mDefContainerConn);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422        }
1423
1424        PackageHandler(Looper looper) {
1425            super(looper);
1426        }
1427
1428        public void handleMessage(Message msg) {
1429            try {
1430                doHandleMessage(msg);
1431            } finally {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            }
1434        }
1435
1436        void doHandleMessage(Message msg) {
1437            switch (msg.what) {
1438                case INIT_COPY: {
1439                    HandlerParams params = (HandlerParams) msg.obj;
1440                    int idx = mPendingInstalls.size();
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1442                    // If a bind was already initiated we dont really
1443                    // need to do anything. The pending install
1444                    // will be processed later on.
1445                    if (!mBound) {
1446                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1447                                System.identityHashCode(mHandler));
1448                        // If this is the only one pending we might
1449                        // have to bind to the service again.
1450                        if (!connectToService()) {
1451                            Slog.e(TAG, "Failed to bind to media container service");
1452                            params.serviceError();
1453                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                    System.identityHashCode(mHandler));
1455                            if (params.traceMethod != null) {
1456                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1457                                        params.traceCookie);
1458                            }
1459                            return;
1460                        } else {
1461                            // Once we bind to the service, the first
1462                            // pending request will be processed.
1463                            mPendingInstalls.add(idx, params);
1464                        }
1465                    } else {
1466                        mPendingInstalls.add(idx, params);
1467                        // Already bound to the service. Just make
1468                        // sure we trigger off processing the first request.
1469                        if (idx == 0) {
1470                            mHandler.sendEmptyMessage(MCS_BOUND);
1471                        }
1472                    }
1473                    break;
1474                }
1475                case MCS_BOUND: {
1476                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1477                    if (msg.obj != null) {
1478                        mContainerService = (IMediaContainerService) msg.obj;
1479                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1480                                System.identityHashCode(mHandler));
1481                    }
1482                    if (mContainerService == null) {
1483                        if (!mBound) {
1484                            // Something seriously wrong since we are not bound and we are not
1485                            // waiting for connection. Bail out.
1486                            Slog.e(TAG, "Cannot bind to media container service");
1487                            for (HandlerParams params : mPendingInstalls) {
1488                                // Indicate service bind error
1489                                params.serviceError();
1490                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1491                                        System.identityHashCode(params));
1492                                if (params.traceMethod != null) {
1493                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1494                                            params.traceMethod, params.traceCookie);
1495                                }
1496                                return;
1497                            }
1498                            mPendingInstalls.clear();
1499                        } else {
1500                            Slog.w(TAG, "Waiting to connect to media container service");
1501                        }
1502                    } else if (mPendingInstalls.size() > 0) {
1503                        HandlerParams params = mPendingInstalls.get(0);
1504                        if (params != null) {
1505                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                                    System.identityHashCode(params));
1507                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1508                            if (params.startCopy()) {
1509                                // We are done...  look for more work or to
1510                                // go idle.
1511                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                        "Checking for more work or unbind...");
1513                                // Delete pending install
1514                                if (mPendingInstalls.size() > 0) {
1515                                    mPendingInstalls.remove(0);
1516                                }
1517                                if (mPendingInstalls.size() == 0) {
1518                                    if (mBound) {
1519                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1520                                                "Posting delayed MCS_UNBIND");
1521                                        removeMessages(MCS_UNBIND);
1522                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1523                                        // Unbind after a little delay, to avoid
1524                                        // continual thrashing.
1525                                        sendMessageDelayed(ubmsg, 10000);
1526                                    }
1527                                } else {
1528                                    // There are more pending requests in queue.
1529                                    // Just post MCS_BOUND message to trigger processing
1530                                    // of next pending install.
1531                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                            "Posting MCS_BOUND for next work");
1533                                    mHandler.sendEmptyMessage(MCS_BOUND);
1534                                }
1535                            }
1536                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1537                        }
1538                    } else {
1539                        // Should never happen ideally.
1540                        Slog.w(TAG, "Empty queue");
1541                    }
1542                    break;
1543                }
1544                case MCS_RECONNECT: {
1545                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1546                    if (mPendingInstalls.size() > 0) {
1547                        if (mBound) {
1548                            disconnectService();
1549                        }
1550                        if (!connectToService()) {
1551                            Slog.e(TAG, "Failed to bind to media container service");
1552                            for (HandlerParams params : mPendingInstalls) {
1553                                // Indicate service bind error
1554                                params.serviceError();
1555                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1556                                        System.identityHashCode(params));
1557                            }
1558                            mPendingInstalls.clear();
1559                        }
1560                    }
1561                    break;
1562                }
1563                case MCS_UNBIND: {
1564                    // If there is no actual work left, then time to unbind.
1565                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1566
1567                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1568                        if (mBound) {
1569                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1570
1571                            disconnectService();
1572                        }
1573                    } else if (mPendingInstalls.size() > 0) {
1574                        // There are more pending requests in queue.
1575                        // Just post MCS_BOUND message to trigger processing
1576                        // of next pending install.
1577                        mHandler.sendEmptyMessage(MCS_BOUND);
1578                    }
1579
1580                    break;
1581                }
1582                case MCS_GIVE_UP: {
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1584                    HandlerParams params = mPendingInstalls.remove(0);
1585                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                            System.identityHashCode(params));
1587                    break;
1588                }
1589                case SEND_PENDING_BROADCAST: {
1590                    String packages[];
1591                    ArrayList<String> components[];
1592                    int size = 0;
1593                    int uids[];
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        if (mPendingBroadcasts == null) {
1597                            return;
1598                        }
1599                        size = mPendingBroadcasts.size();
1600                        if (size <= 0) {
1601                            // Nothing to be done. Just return
1602                            return;
1603                        }
1604                        packages = new String[size];
1605                        components = new ArrayList[size];
1606                        uids = new int[size];
1607                        int i = 0;  // filling out the above arrays
1608
1609                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1610                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1611                            Iterator<Map.Entry<String, ArrayList<String>>> it
1612                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1613                                            .entrySet().iterator();
1614                            while (it.hasNext() && i < size) {
1615                                Map.Entry<String, ArrayList<String>> ent = it.next();
1616                                packages[i] = ent.getKey();
1617                                components[i] = ent.getValue();
1618                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1619                                uids[i] = (ps != null)
1620                                        ? UserHandle.getUid(packageUserId, ps.appId)
1621                                        : -1;
1622                                i++;
1623                            }
1624                        }
1625                        size = i;
1626                        mPendingBroadcasts.clear();
1627                    }
1628                    // Send broadcasts
1629                    for (int i = 0; i < size; i++) {
1630                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1631                    }
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1633                    break;
1634                }
1635                case START_CLEANING_PACKAGE: {
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1637                    final String packageName = (String)msg.obj;
1638                    final int userId = msg.arg1;
1639                    final boolean andCode = msg.arg2 != 0;
1640                    synchronized (mPackages) {
1641                        if (userId == UserHandle.USER_ALL) {
1642                            int[] users = sUserManager.getUserIds();
1643                            for (int user : users) {
1644                                mSettings.addPackageToCleanLPw(
1645                                        new PackageCleanItem(user, packageName, andCode));
1646                            }
1647                        } else {
1648                            mSettings.addPackageToCleanLPw(
1649                                    new PackageCleanItem(userId, packageName, andCode));
1650                        }
1651                    }
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1653                    startCleaningPackages();
1654                } break;
1655                case POST_INSTALL: {
1656                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1657
1658                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1659                    final boolean didRestore = (msg.arg2 != 0);
1660                    mRunningInstalls.delete(msg.arg1);
1661
1662                    if (data != null) {
1663                        InstallArgs args = data.args;
1664                        PackageInstalledInfo parentRes = data.res;
1665
1666                        final boolean grantPermissions = (args.installFlags
1667                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1668                        final boolean killApp = (args.installFlags
1669                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1670                        final boolean virtualPreload = ((args.installFlags
1671                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1672                        final String[] grantedPermissions = args.installGrantPermissions;
1673
1674                        // Handle the parent package
1675                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1676                                virtualPreload, grantedPermissions, didRestore,
1677                                args.installerPackageName, args.observer);
1678
1679                        // Handle the child packages
1680                        final int childCount = (parentRes.addedChildPackages != null)
1681                                ? parentRes.addedChildPackages.size() : 0;
1682                        for (int i = 0; i < childCount; i++) {
1683                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1684                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1685                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1686                                    args.installerPackageName, args.observer);
1687                        }
1688
1689                        // Log tracing if needed
1690                        if (args.traceMethod != null) {
1691                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1692                                    args.traceCookie);
1693                        }
1694                    } else {
1695                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1696                    }
1697
1698                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1699                } break;
1700                case WRITE_SETTINGS: {
1701                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1702                    synchronized (mPackages) {
1703                        removeMessages(WRITE_SETTINGS);
1704                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1705                        mSettings.writeLPr();
1706                        mDirtyUsers.clear();
1707                    }
1708                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1709                } break;
1710                case WRITE_PACKAGE_RESTRICTIONS: {
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1712                    synchronized (mPackages) {
1713                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1714                        for (int userId : mDirtyUsers) {
1715                            mSettings.writePackageRestrictionsLPr(userId);
1716                        }
1717                        mDirtyUsers.clear();
1718                    }
1719                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1720                } break;
1721                case WRITE_PACKAGE_LIST: {
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1723                    synchronized (mPackages) {
1724                        removeMessages(WRITE_PACKAGE_LIST);
1725                        mSettings.writePackageListLPr(msg.arg1);
1726                    }
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1728                } break;
1729                case CHECK_PENDING_VERIFICATION: {
1730                    final int verificationId = msg.arg1;
1731                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1732
1733                    if ((state != null) && !state.timeoutExtended()) {
1734                        final InstallArgs args = state.getInstallArgs();
1735                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1736
1737                        Slog.i(TAG, "Verification timed out for " + originUri);
1738                        mPendingVerification.remove(verificationId);
1739
1740                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1741
1742                        final UserHandle user = args.getUser();
1743                        if (getDefaultVerificationResponse(user)
1744                                == PackageManager.VERIFICATION_ALLOW) {
1745                            Slog.i(TAG, "Continuing with installation of " + originUri);
1746                            state.setVerifierResponse(Binder.getCallingUid(),
1747                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1748                            broadcastPackageVerified(verificationId, originUri,
1749                                    PackageManager.VERIFICATION_ALLOW, user);
1750                            try {
1751                                ret = args.copyApk(mContainerService, true);
1752                            } catch (RemoteException e) {
1753                                Slog.e(TAG, "Could not contact the ContainerService");
1754                            }
1755                        } else {
1756                            broadcastPackageVerified(verificationId, originUri,
1757                                    PackageManager.VERIFICATION_REJECT, user);
1758                        }
1759
1760                        Trace.asyncTraceEnd(
1761                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1762
1763                        processPendingInstall(args, ret);
1764                        mHandler.sendEmptyMessage(MCS_UNBIND);
1765                    }
1766                    break;
1767                }
1768                case PACKAGE_VERIFIED: {
1769                    final int verificationId = msg.arg1;
1770
1771                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1772                    if (state == null) {
1773                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1774                        break;
1775                    }
1776
1777                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1778
1779                    state.setVerifierResponse(response.callerUid, response.code);
1780
1781                    if (state.isVerificationComplete()) {
1782                        mPendingVerification.remove(verificationId);
1783
1784                        final InstallArgs args = state.getInstallArgs();
1785                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1786
1787                        int ret;
1788                        if (state.isInstallAllowed()) {
1789                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1790                            broadcastPackageVerified(verificationId, originUri,
1791                                    response.code, state.getInstallArgs().getUser());
1792                            try {
1793                                ret = args.copyApk(mContainerService, true);
1794                            } catch (RemoteException e) {
1795                                Slog.e(TAG, "Could not contact the ContainerService");
1796                            }
1797                        } else {
1798                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1799                        }
1800
1801                        Trace.asyncTraceEnd(
1802                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1803
1804                        processPendingInstall(args, ret);
1805                        mHandler.sendEmptyMessage(MCS_UNBIND);
1806                    }
1807
1808                    break;
1809                }
1810                case START_INTENT_FILTER_VERIFICATIONS: {
1811                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1812                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1813                            params.replacing, params.pkg);
1814                    break;
1815                }
1816                case INTENT_FILTER_VERIFIED: {
1817                    final int verificationId = msg.arg1;
1818
1819                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1820                            verificationId);
1821                    if (state == null) {
1822                        Slog.w(TAG, "Invalid IntentFilter verification token "
1823                                + verificationId + " received");
1824                        break;
1825                    }
1826
1827                    final int userId = state.getUserId();
1828
1829                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1830                            "Processing IntentFilter verification with token:"
1831                            + verificationId + " and userId:" + userId);
1832
1833                    final IntentFilterVerificationResponse response =
1834                            (IntentFilterVerificationResponse) msg.obj;
1835
1836                    state.setVerifierResponse(response.callerUid, response.code);
1837
1838                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1839                            "IntentFilter verification with token:" + verificationId
1840                            + " and userId:" + userId
1841                            + " is settings verifier response with response code:"
1842                            + response.code);
1843
1844                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1845                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1846                                + response.getFailedDomainsString());
1847                    }
1848
1849                    if (state.isVerificationComplete()) {
1850                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1851                    } else {
1852                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1853                                "IntentFilter verification with token:" + verificationId
1854                                + " was not said to be complete");
1855                    }
1856
1857                    break;
1858                }
1859                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1860                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1861                            mInstantAppResolverConnection,
1862                            (InstantAppRequest) msg.obj,
1863                            mInstantAppInstallerActivity,
1864                            mHandler);
1865                }
1866            }
1867        }
1868    }
1869
1870    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1871        @Override
1872        public void onGidsChanged(int appId, int userId) {
1873            mHandler.post(new Runnable() {
1874                @Override
1875                public void run() {
1876                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1877                }
1878            });
1879        }
1880        @Override
1881        public void onPermissionGranted(int uid, int userId) {
1882            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1883
1884            // Not critical; if this is lost, the application has to request again.
1885            synchronized (mPackages) {
1886                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1887            }
1888        }
1889        @Override
1890        public void onInstallPermissionGranted() {
1891            synchronized (mPackages) {
1892                scheduleWriteSettingsLocked();
1893            }
1894        }
1895        @Override
1896        public void onPermissionRevoked(int uid, int userId) {
1897            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1898
1899            synchronized (mPackages) {
1900                // Critical; after this call the application should never have the permission
1901                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1902            }
1903
1904            final int appId = UserHandle.getAppId(uid);
1905            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1906        }
1907        @Override
1908        public void onInstallPermissionRevoked() {
1909            synchronized (mPackages) {
1910                scheduleWriteSettingsLocked();
1911            }
1912        }
1913        @Override
1914        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1915            synchronized (mPackages) {
1916                for (int userId : updatedUserIds) {
1917                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1918                }
1919            }
1920        }
1921        @Override
1922        public void onInstallPermissionUpdated() {
1923            synchronized (mPackages) {
1924                scheduleWriteSettingsLocked();
1925            }
1926        }
1927        @Override
1928        public void onPermissionRemoved() {
1929            synchronized (mPackages) {
1930                mSettings.writeLPr();
1931            }
1932        }
1933    };
1934
1935    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1936            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1937            boolean launchedForRestore, String installerPackage,
1938            IPackageInstallObserver2 installObserver) {
1939        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1940            // Send the removed broadcasts
1941            if (res.removedInfo != null) {
1942                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1943            }
1944
1945            // Now that we successfully installed the package, grant runtime
1946            // permissions if requested before broadcasting the install. Also
1947            // for legacy apps in permission review mode we clear the permission
1948            // review flag which is used to emulate runtime permissions for
1949            // legacy apps.
1950            if (grantPermissions) {
1951                final int callingUid = Binder.getCallingUid();
1952                mPermissionManager.grantRequestedRuntimePermissions(
1953                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1954                        mPermissionCallback);
1955            }
1956
1957            final boolean update = res.removedInfo != null
1958                    && res.removedInfo.removedPackage != null;
1959            final String installerPackageName =
1960                    res.installerPackageName != null
1961                            ? res.installerPackageName
1962                            : res.removedInfo != null
1963                                    ? res.removedInfo.installerPackageName
1964                                    : null;
1965
1966            // If this is the first time we have child packages for a disabled privileged
1967            // app that had no children, we grant requested runtime permissions to the new
1968            // children if the parent on the system image had them already granted.
1969            if (res.pkg.parentPackage != null) {
1970                final int callingUid = Binder.getCallingUid();
1971                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1972                        res.pkg, callingUid, mPermissionCallback);
1973            }
1974
1975            synchronized (mPackages) {
1976                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1977            }
1978
1979            final String packageName = res.pkg.applicationInfo.packageName;
1980
1981            // Determine the set of users who are adding this package for
1982            // the first time vs. those who are seeing an update.
1983            int[] firstUserIds = EMPTY_INT_ARRAY;
1984            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1985            int[] updateUserIds = EMPTY_INT_ARRAY;
1986            int[] instantUserIds = EMPTY_INT_ARRAY;
1987            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1988            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1989            for (int newUser : res.newUsers) {
1990                final boolean isInstantApp = ps.getInstantApp(newUser);
1991                if (allNewUsers) {
1992                    if (isInstantApp) {
1993                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1994                    } else {
1995                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1996                    }
1997                    continue;
1998                }
1999                boolean isNew = true;
2000                for (int origUser : res.origUsers) {
2001                    if (origUser == newUser) {
2002                        isNew = false;
2003                        break;
2004                    }
2005                }
2006                if (isNew) {
2007                    if (isInstantApp) {
2008                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2009                    } else {
2010                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2011                    }
2012                } else {
2013                    if (isInstantApp) {
2014                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2015                    } else {
2016                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2017                    }
2018                }
2019            }
2020
2021            // Send installed broadcasts if the package is not a static shared lib.
2022            if (res.pkg.staticSharedLibName == null) {
2023                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2024
2025                // Send added for users that see the package for the first time
2026                // sendPackageAddedForNewUsers also deals with system apps
2027                int appId = UserHandle.getAppId(res.uid);
2028                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2029                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2030                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2031
2032                // Send added for users that don't see the package for the first time
2033                Bundle extras = new Bundle(1);
2034                extras.putInt(Intent.EXTRA_UID, res.uid);
2035                if (update) {
2036                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2037                }
2038                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2039                        extras, 0 /*flags*/,
2040                        null /*targetPackage*/, null /*finishedReceiver*/,
2041                        updateUserIds, instantUserIds);
2042                if (installerPackageName != null) {
2043                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2044                            extras, 0 /*flags*/,
2045                            installerPackageName, null /*finishedReceiver*/,
2046                            updateUserIds, instantUserIds);
2047                }
2048
2049                // Send replaced for users that don't see the package for the first time
2050                if (update) {
2051                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2052                            packageName, extras, 0 /*flags*/,
2053                            null /*targetPackage*/, null /*finishedReceiver*/,
2054                            updateUserIds, instantUserIds);
2055                    if (installerPackageName != null) {
2056                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2057                                extras, 0 /*flags*/,
2058                                installerPackageName, null /*finishedReceiver*/,
2059                                updateUserIds, instantUserIds);
2060                    }
2061                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2062                            null /*package*/, null /*extras*/, 0 /*flags*/,
2063                            packageName /*targetPackage*/,
2064                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2065                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2066                    // First-install and we did a restore, so we're responsible for the
2067                    // first-launch broadcast.
2068                    if (DEBUG_BACKUP) {
2069                        Slog.i(TAG, "Post-restore of " + packageName
2070                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2071                    }
2072                    sendFirstLaunchBroadcast(packageName, installerPackage,
2073                            firstUserIds, firstInstantUserIds);
2074                }
2075
2076                // Send broadcast package appeared if forward locked/external for all users
2077                // treat asec-hosted packages like removable media on upgrade
2078                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2079                    if (DEBUG_INSTALL) {
2080                        Slog.i(TAG, "upgrading pkg " + res.pkg
2081                                + " is ASEC-hosted -> AVAILABLE");
2082                    }
2083                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2084                    ArrayList<String> pkgList = new ArrayList<>(1);
2085                    pkgList.add(packageName);
2086                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2087                }
2088            }
2089
2090            // Work that needs to happen on first install within each user
2091            if (firstUserIds != null && firstUserIds.length > 0) {
2092                synchronized (mPackages) {
2093                    for (int userId : firstUserIds) {
2094                        // If this app is a browser and it's newly-installed for some
2095                        // users, clear any default-browser state in those users. The
2096                        // app's nature doesn't depend on the user, so we can just check
2097                        // its browser nature in any user and generalize.
2098                        if (packageIsBrowser(packageName, userId)) {
2099                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2100                        }
2101
2102                        // We may also need to apply pending (restored) runtime
2103                        // permission grants within these users.
2104                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2105                    }
2106                }
2107            }
2108
2109            if (allNewUsers && !update) {
2110                notifyPackageAdded(packageName);
2111            }
2112
2113            // Log current value of "unknown sources" setting
2114            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2115                    getUnknownSourcesSettings());
2116
2117            // Remove the replaced package's older resources safely now
2118            // We delete after a gc for applications  on sdcard.
2119            if (res.removedInfo != null && res.removedInfo.args != null) {
2120                Runtime.getRuntime().gc();
2121                synchronized (mInstallLock) {
2122                    res.removedInfo.args.doPostDeleteLI(true);
2123                }
2124            } else {
2125                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2126                // and not block here.
2127                VMRuntime.getRuntime().requestConcurrentGC();
2128            }
2129
2130            // Notify DexManager that the package was installed for new users.
2131            // The updated users should already be indexed and the package code paths
2132            // should not change.
2133            // Don't notify the manager for ephemeral apps as they are not expected to
2134            // survive long enough to benefit of background optimizations.
2135            for (int userId : firstUserIds) {
2136                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2137                // There's a race currently where some install events may interleave with an uninstall.
2138                // This can lead to package info being null (b/36642664).
2139                if (info != null) {
2140                    mDexManager.notifyPackageInstalled(info, userId);
2141                }
2142            }
2143        }
2144
2145        // If someone is watching installs - notify them
2146        if (installObserver != null) {
2147            try {
2148                Bundle extras = extrasForInstallResult(res);
2149                installObserver.onPackageInstalled(res.name, res.returnCode,
2150                        res.returnMsg, extras);
2151            } catch (RemoteException e) {
2152                Slog.i(TAG, "Observer no longer exists.");
2153            }
2154        }
2155    }
2156
2157    private StorageEventListener mStorageListener = new StorageEventListener() {
2158        @Override
2159        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2160            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2161                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2162                    final String volumeUuid = vol.getFsUuid();
2163
2164                    // Clean up any users or apps that were removed or recreated
2165                    // while this volume was missing
2166                    sUserManager.reconcileUsers(volumeUuid);
2167                    reconcileApps(volumeUuid);
2168
2169                    // Clean up any install sessions that expired or were
2170                    // cancelled while this volume was missing
2171                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2172
2173                    loadPrivatePackages(vol);
2174
2175                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2176                    unloadPrivatePackages(vol);
2177                }
2178            }
2179        }
2180
2181        @Override
2182        public void onVolumeForgotten(String fsUuid) {
2183            if (TextUtils.isEmpty(fsUuid)) {
2184                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2185                return;
2186            }
2187
2188            // Remove any apps installed on the forgotten volume
2189            synchronized (mPackages) {
2190                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2191                for (PackageSetting ps : packages) {
2192                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2193                    deletePackageVersioned(new VersionedPackage(ps.name,
2194                            PackageManager.VERSION_CODE_HIGHEST),
2195                            new LegacyPackageDeleteObserver(null).getBinder(),
2196                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2197                    // Try very hard to release any references to this package
2198                    // so we don't risk the system server being killed due to
2199                    // open FDs
2200                    AttributeCache.instance().removePackage(ps.name);
2201                }
2202
2203                mSettings.onVolumeForgotten(fsUuid);
2204                mSettings.writeLPr();
2205            }
2206        }
2207    };
2208
2209    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2210        Bundle extras = null;
2211        switch (res.returnCode) {
2212            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2213                extras = new Bundle();
2214                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2215                        res.origPermission);
2216                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2217                        res.origPackage);
2218                break;
2219            }
2220            case PackageManager.INSTALL_SUCCEEDED: {
2221                extras = new Bundle();
2222                extras.putBoolean(Intent.EXTRA_REPLACING,
2223                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2224                break;
2225            }
2226        }
2227        return extras;
2228    }
2229
2230    void scheduleWriteSettingsLocked() {
2231        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2232            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2233        }
2234    }
2235
2236    void scheduleWritePackageListLocked(int userId) {
2237        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2238            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2239            msg.arg1 = userId;
2240            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2241        }
2242    }
2243
2244    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2245        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2246        scheduleWritePackageRestrictionsLocked(userId);
2247    }
2248
2249    void scheduleWritePackageRestrictionsLocked(int userId) {
2250        final int[] userIds = (userId == UserHandle.USER_ALL)
2251                ? sUserManager.getUserIds() : new int[]{userId};
2252        for (int nextUserId : userIds) {
2253            if (!sUserManager.exists(nextUserId)) return;
2254            mDirtyUsers.add(nextUserId);
2255            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2256                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2257            }
2258        }
2259    }
2260
2261    public static PackageManagerService main(Context context, Installer installer,
2262            boolean factoryTest, boolean onlyCore) {
2263        // Self-check for initial settings.
2264        PackageManagerServiceCompilerMapping.checkProperties();
2265
2266        PackageManagerService m = new PackageManagerService(context, installer,
2267                factoryTest, onlyCore);
2268        m.enableSystemUserPackages();
2269        ServiceManager.addService("package", m);
2270        final PackageManagerNative pmn = m.new PackageManagerNative();
2271        ServiceManager.addService("package_native", pmn);
2272        return m;
2273    }
2274
2275    private void enableSystemUserPackages() {
2276        if (!UserManager.isSplitSystemUser()) {
2277            return;
2278        }
2279        // For system user, enable apps based on the following conditions:
2280        // - app is whitelisted or belong to one of these groups:
2281        //   -- system app which has no launcher icons
2282        //   -- system app which has INTERACT_ACROSS_USERS permission
2283        //   -- system IME app
2284        // - app is not in the blacklist
2285        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2286        Set<String> enableApps = new ArraySet<>();
2287        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2288                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2289                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2290        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2291        enableApps.addAll(wlApps);
2292        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2293                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2294        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2295        enableApps.removeAll(blApps);
2296        Log.i(TAG, "Applications installed for system user: " + enableApps);
2297        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2298                UserHandle.SYSTEM);
2299        final int allAppsSize = allAps.size();
2300        synchronized (mPackages) {
2301            for (int i = 0; i < allAppsSize; i++) {
2302                String pName = allAps.get(i);
2303                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2304                // Should not happen, but we shouldn't be failing if it does
2305                if (pkgSetting == null) {
2306                    continue;
2307                }
2308                boolean install = enableApps.contains(pName);
2309                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2310                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2311                            + " for system user");
2312                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2313                }
2314            }
2315            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2316        }
2317    }
2318
2319    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2320        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2321                Context.DISPLAY_SERVICE);
2322        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2323    }
2324
2325    /**
2326     * Requests that files preopted on a secondary system partition be copied to the data partition
2327     * if possible.  Note that the actual copying of the files is accomplished by init for security
2328     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2329     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2330     */
2331    private static void requestCopyPreoptedFiles() {
2332        final int WAIT_TIME_MS = 100;
2333        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2334        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2335            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2336            // We will wait for up to 100 seconds.
2337            final long timeStart = SystemClock.uptimeMillis();
2338            final long timeEnd = timeStart + 100 * 1000;
2339            long timeNow = timeStart;
2340            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2341                try {
2342                    Thread.sleep(WAIT_TIME_MS);
2343                } catch (InterruptedException e) {
2344                    // Do nothing
2345                }
2346                timeNow = SystemClock.uptimeMillis();
2347                if (timeNow > timeEnd) {
2348                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2349                    Slog.wtf(TAG, "cppreopt did not finish!");
2350                    break;
2351                }
2352            }
2353
2354            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2355        }
2356    }
2357
2358    public PackageManagerService(Context context, Installer installer,
2359            boolean factoryTest, boolean onlyCore) {
2360        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2361        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2362        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2363                SystemClock.uptimeMillis());
2364
2365        if (mSdkVersion <= 0) {
2366            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2367        }
2368
2369        mContext = context;
2370
2371        mFactoryTest = factoryTest;
2372        mOnlyCore = onlyCore;
2373        mMetrics = new DisplayMetrics();
2374        mInstaller = installer;
2375
2376        // Create sub-components that provide services / data. Order here is important.
2377        synchronized (mInstallLock) {
2378        synchronized (mPackages) {
2379            // Expose private service for system components to use.
2380            LocalServices.addService(
2381                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2382            sUserManager = new UserManagerService(context, this,
2383                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2384            mPermissionManager = PermissionManagerService.create(context,
2385                    new DefaultPermissionGrantedCallback() {
2386                        @Override
2387                        public void onDefaultRuntimePermissionsGranted(int userId) {
2388                            synchronized(mPackages) {
2389                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2390                            }
2391                        }
2392                    }, mPackages /*externalLock*/);
2393            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2394            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2395        }
2396        }
2397        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409
2410        String separateProcesses = SystemProperties.get("debug.separate_processes");
2411        if (separateProcesses != null && separateProcesses.length() > 0) {
2412            if ("*".equals(separateProcesses)) {
2413                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2414                mSeparateProcesses = null;
2415                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2416            } else {
2417                mDefParseFlags = 0;
2418                mSeparateProcesses = separateProcesses.split(",");
2419                Slog.w(TAG, "Running with debug.separate_processes: "
2420                        + separateProcesses);
2421            }
2422        } else {
2423            mDefParseFlags = 0;
2424            mSeparateProcesses = null;
2425        }
2426
2427        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2428                "*dexopt*");
2429        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2430                installer, mInstallLock);
2431        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2432                dexManagerListener);
2433        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2434
2435        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2436                FgThread.get().getLooper());
2437
2438        getDefaultDisplayMetrics(context, mMetrics);
2439
2440        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2441        SystemConfig systemConfig = SystemConfig.getInstance();
2442        mAvailableFeatures = systemConfig.getAvailableFeatures();
2443        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2444
2445        mProtectedPackages = new ProtectedPackages(mContext);
2446
2447        synchronized (mInstallLock) {
2448        // writer
2449        synchronized (mPackages) {
2450            mHandlerThread = new ServiceThread(TAG,
2451                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2452            mHandlerThread.start();
2453            mHandler = new PackageHandler(mHandlerThread.getLooper());
2454            mProcessLoggingHandler = new ProcessLoggingHandler();
2455            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2456            mInstantAppRegistry = new InstantAppRegistry(this);
2457
2458            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2459            final int builtInLibCount = libConfig.size();
2460            for (int i = 0; i < builtInLibCount; i++) {
2461                String name = libConfig.keyAt(i);
2462                String path = libConfig.valueAt(i);
2463                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2464                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2465            }
2466
2467            SELinuxMMAC.readInstallPolicy();
2468
2469            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2470            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2471            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2472
2473            // Clean up orphaned packages for which the code path doesn't exist
2474            // and they are an update to a system app - caused by bug/32321269
2475            final int packageSettingCount = mSettings.mPackages.size();
2476            for (int i = packageSettingCount - 1; i >= 0; i--) {
2477                PackageSetting ps = mSettings.mPackages.valueAt(i);
2478                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2479                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2480                    mSettings.mPackages.removeAt(i);
2481                    mSettings.enableSystemPackageLPw(ps.name);
2482                }
2483            }
2484
2485            if (mFirstBoot) {
2486                requestCopyPreoptedFiles();
2487            }
2488
2489            String customResolverActivity = Resources.getSystem().getString(
2490                    R.string.config_customResolverActivity);
2491            if (TextUtils.isEmpty(customResolverActivity)) {
2492                customResolverActivity = null;
2493            } else {
2494                mCustomResolverComponentName = ComponentName.unflattenFromString(
2495                        customResolverActivity);
2496            }
2497
2498            long startTime = SystemClock.uptimeMillis();
2499
2500            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2501                    startTime);
2502
2503            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2504            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2505
2506            if (bootClassPath == null) {
2507                Slog.w(TAG, "No BOOTCLASSPATH found!");
2508            }
2509
2510            if (systemServerClassPath == null) {
2511                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2512            }
2513
2514            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2515
2516            final VersionInfo ver = mSettings.getInternalVersion();
2517            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2518            if (mIsUpgrade) {
2519                logCriticalInfo(Log.INFO,
2520                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2521            }
2522
2523            // when upgrading from pre-M, promote system app permissions from install to runtime
2524            mPromoteSystemApps =
2525                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2526
2527            // When upgrading from pre-N, we need to handle package extraction like first boot,
2528            // as there is no profiling data available.
2529            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2530
2531            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2532
2533            // save off the names of pre-existing system packages prior to scanning; we don't
2534            // want to automatically grant runtime permissions for new system apps
2535            if (mPromoteSystemApps) {
2536                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2537                while (pkgSettingIter.hasNext()) {
2538                    PackageSetting ps = pkgSettingIter.next();
2539                    if (isSystemApp(ps)) {
2540                        mExistingSystemPackages.add(ps.name);
2541                    }
2542                }
2543            }
2544
2545            mCacheDir = preparePackageParserCache(mIsUpgrade);
2546
2547            // Set flag to monitor and not change apk file paths when
2548            // scanning install directories.
2549            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2550
2551            if (mIsUpgrade || mFirstBoot) {
2552                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2553            }
2554
2555            // Collect vendor overlay packages. (Do this before scanning any apps.)
2556            // For security and version matching reason, only consider
2557            // overlay packages if they reside in the right directory.
2558            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2559                    mDefParseFlags
2560                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2561                    scanFlags
2562                    | SCAN_AS_SYSTEM
2563                    | SCAN_TRUSTED_OVERLAY,
2564                    0);
2565
2566            mParallelPackageParserCallback.findStaticOverlayPackages();
2567
2568            // Find base frameworks (resource packages without code).
2569            scanDirTracedLI(frameworkDir,
2570                    mDefParseFlags
2571                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2572                    scanFlags
2573                    | SCAN_NO_DEX
2574                    | SCAN_AS_SYSTEM
2575                    | SCAN_AS_PRIVILEGED,
2576                    0);
2577
2578            // Collected privileged system packages.
2579            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2580            scanDirTracedLI(privilegedAppDir,
2581                    mDefParseFlags
2582                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2583                    scanFlags
2584                    | SCAN_AS_SYSTEM
2585                    | SCAN_AS_PRIVILEGED,
2586                    0);
2587
2588            // Collect ordinary system packages.
2589            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2590            scanDirTracedLI(systemAppDir,
2591                    mDefParseFlags
2592                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2593                    scanFlags
2594                    | SCAN_AS_SYSTEM,
2595                    0);
2596
2597            // Collected privileged vendor packages.
2598                File privilegedVendorAppDir = new File(Environment.getVendorDirectory(),
2599                        "priv-app");
2600            try {
2601                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2602            } catch (IOException e) {
2603                // failed to look up canonical path, continue with original one
2604            }
2605            scanDirTracedLI(privilegedVendorAppDir,
2606                    mDefParseFlags
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2608                    scanFlags
2609                    | SCAN_AS_SYSTEM
2610                    | SCAN_AS_VENDOR
2611                    | SCAN_AS_PRIVILEGED,
2612                    0);
2613
2614            // Collect ordinary vendor packages.
2615            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2616            try {
2617                vendorAppDir = vendorAppDir.getCanonicalFile();
2618            } catch (IOException e) {
2619                // failed to look up canonical path, continue with original one
2620            }
2621            scanDirTracedLI(vendorAppDir,
2622                    mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2624                    scanFlags
2625                    | SCAN_AS_SYSTEM
2626                    | SCAN_AS_VENDOR,
2627                    0);
2628
2629            // Collect all OEM packages.
2630            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2631            scanDirTracedLI(oemAppDir,
2632                    mDefParseFlags
2633                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2634                    scanFlags
2635                    | SCAN_AS_SYSTEM
2636                    | SCAN_AS_OEM,
2637                    0);
2638
2639            // Prune any system packages that no longer exist.
2640            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2641            // Stub packages must either be replaced with full versions in the /data
2642            // partition or be disabled.
2643            final List<String> stubSystemApps = new ArrayList<>();
2644            if (!mOnlyCore) {
2645                // do this first before mucking with mPackages for the "expecting better" case
2646                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2647                while (pkgIterator.hasNext()) {
2648                    final PackageParser.Package pkg = pkgIterator.next();
2649                    if (pkg.isStub) {
2650                        stubSystemApps.add(pkg.packageName);
2651                    }
2652                }
2653
2654                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2655                while (psit.hasNext()) {
2656                    PackageSetting ps = psit.next();
2657
2658                    /*
2659                     * If this is not a system app, it can't be a
2660                     * disable system app.
2661                     */
2662                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2663                        continue;
2664                    }
2665
2666                    /*
2667                     * If the package is scanned, it's not erased.
2668                     */
2669                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2670                    if (scannedPkg != null) {
2671                        /*
2672                         * If the system app is both scanned and in the
2673                         * disabled packages list, then it must have been
2674                         * added via OTA. Remove it from the currently
2675                         * scanned package so the previously user-installed
2676                         * application can be scanned.
2677                         */
2678                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2679                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2680                                    + ps.name + "; removing system app.  Last known codePath="
2681                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2682                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2683                                    + scannedPkg.getLongVersionCode());
2684                            removePackageLI(scannedPkg, true);
2685                            mExpectingBetter.put(ps.name, ps.codePath);
2686                        }
2687
2688                        continue;
2689                    }
2690
2691                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2692                        psit.remove();
2693                        logCriticalInfo(Log.WARN, "System package " + ps.name
2694                                + " no longer exists; it's data will be wiped");
2695                        // Actual deletion of code and data will be handled by later
2696                        // reconciliation step
2697                    } else {
2698                        // we still have a disabled system package, but, it still might have
2699                        // been removed. check the code path still exists and check there's
2700                        // still a package. the latter can happen if an OTA keeps the same
2701                        // code path, but, changes the package name.
2702                        final PackageSetting disabledPs =
2703                                mSettings.getDisabledSystemPkgLPr(ps.name);
2704                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2705                                || disabledPs.pkg == null) {
2706if (REFACTOR_DEBUG) {
2707Slog.e("TODD",
2708        "Possibly deleted app: " + ps.dumpState_temp()
2709        + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath)
2710        + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString()));
2711}
2712                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2713                        }
2714                    }
2715                }
2716            }
2717
2718            //look for any incomplete package installations
2719            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2720            for (int i = 0; i < deletePkgsList.size(); i++) {
2721                // Actual deletion of code and data will be handled by later
2722                // reconciliation step
2723                final String packageName = deletePkgsList.get(i).name;
2724                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2725                synchronized (mPackages) {
2726                    mSettings.removePackageLPw(packageName);
2727                }
2728            }
2729
2730            //delete tmp files
2731            deleteTempPackageFiles();
2732
2733            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2734
2735            // Remove any shared userIDs that have no associated packages
2736            mSettings.pruneSharedUsersLPw();
2737            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2738            final int systemPackagesCount = mPackages.size();
2739            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2740                    + " ms, packageCount: " + systemPackagesCount
2741                    + " , timePerPackage: "
2742                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2743                    + " , cached: " + cachedSystemApps);
2744            if (mIsUpgrade && systemPackagesCount > 0) {
2745                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2746                        ((int) systemScanTime) / systemPackagesCount);
2747            }
2748            if (!mOnlyCore) {
2749                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2750                        SystemClock.uptimeMillis());
2751                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2752
2753                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2754                        | PackageParser.PARSE_FORWARD_LOCK,
2755                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2756
2757                // Remove disable package settings for updated system apps that were
2758                // removed via an OTA. If the update is no longer present, remove the
2759                // app completely. Otherwise, revoke their system privileges.
2760                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2761                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2762                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2763if (REFACTOR_DEBUG) {
2764Slog.e("TODD",
2765        "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null));
2766}
2767                    final String msg;
2768                    if (deletedPkg == null) {
2769                        // should have found an update, but, we didn't; remove everything
2770                        msg = "Updated system package " + deletedAppName
2771                                + " no longer exists; removing its data";
2772                        // Actual deletion of code and data will be handled by later
2773                        // reconciliation step
2774                    } else {
2775                        // found an update; revoke system privileges
2776                        msg = "Updated system package + " + deletedAppName
2777                                + " no longer exists; revoking system privileges";
2778
2779                        // Don't do anything if a stub is removed from the system image. If
2780                        // we were to remove the uncompressed version from the /data partition,
2781                        // this is where it'd be done.
2782
2783                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2784                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2785                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2786                    }
2787                    logCriticalInfo(Log.WARN, msg);
2788                }
2789
2790                /*
2791                 * Make sure all system apps that we expected to appear on
2792                 * the userdata partition actually showed up. If they never
2793                 * appeared, crawl back and revive the system version.
2794                 */
2795                for (int i = 0; i < mExpectingBetter.size(); i++) {
2796                    final String packageName = mExpectingBetter.keyAt(i);
2797                    if (!mPackages.containsKey(packageName)) {
2798                        final File scanFile = mExpectingBetter.valueAt(i);
2799
2800                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2801                                + " but never showed up; reverting to system");
2802
2803                        final @ParseFlags int reparseFlags;
2804                        final @ScanFlags int rescanFlags;
2805                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2806                            reparseFlags =
2807                                    mDefParseFlags |
2808                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2809                            rescanFlags =
2810                                    scanFlags
2811                                    | SCAN_AS_SYSTEM
2812                                    | SCAN_AS_PRIVILEGED;
2813                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2814                            reparseFlags =
2815                                    mDefParseFlags |
2816                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2817                            rescanFlags =
2818                                    scanFlags
2819                                    | SCAN_AS_SYSTEM;
2820                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2821                            reparseFlags =
2822                                    mDefParseFlags |
2823                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2824                            rescanFlags =
2825                                    scanFlags
2826                                    | SCAN_AS_SYSTEM
2827                                    | SCAN_AS_VENDOR
2828                                    | SCAN_AS_PRIVILEGED;
2829                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2830                            reparseFlags =
2831                                    mDefParseFlags |
2832                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2833                            rescanFlags =
2834                                    scanFlags
2835                                    | SCAN_AS_SYSTEM
2836                                    | SCAN_AS_VENDOR;
2837                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2838                            reparseFlags =
2839                                    mDefParseFlags |
2840                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2841                            rescanFlags =
2842                                    scanFlags
2843                                    | SCAN_AS_SYSTEM
2844                                    | SCAN_AS_OEM;
2845                        } else {
2846                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2847                            continue;
2848                        }
2849
2850                        mSettings.enableSystemPackageLPw(packageName);
2851
2852                        try {
2853                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2854                        } catch (PackageManagerException e) {
2855                            Slog.e(TAG, "Failed to parse original system package: "
2856                                    + e.getMessage());
2857                        }
2858                    }
2859                }
2860
2861                // Uncompress and install any stubbed system applications.
2862                // This must be done last to ensure all stubs are replaced or disabled.
2863                decompressSystemApplications(stubSystemApps, scanFlags);
2864
2865                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2866                                - cachedSystemApps;
2867
2868                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2869                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2870                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2871                        + " ms, packageCount: " + dataPackagesCount
2872                        + " , timePerPackage: "
2873                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2874                        + " , cached: " + cachedNonSystemApps);
2875                if (mIsUpgrade && dataPackagesCount > 0) {
2876                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2877                            ((int) dataScanTime) / dataPackagesCount);
2878                }
2879            }
2880            mExpectingBetter.clear();
2881
2882            // Resolve the storage manager.
2883            mStorageManagerPackage = getStorageManagerPackageName();
2884
2885            // Resolve protected action filters. Only the setup wizard is allowed to
2886            // have a high priority filter for these actions.
2887            mSetupWizardPackage = getSetupWizardPackageName();
2888            if (mProtectedFilters.size() > 0) {
2889                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2890                    Slog.i(TAG, "No setup wizard;"
2891                        + " All protected intents capped to priority 0");
2892                }
2893                for (ActivityIntentInfo filter : mProtectedFilters) {
2894                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2895                        if (DEBUG_FILTERS) {
2896                            Slog.i(TAG, "Found setup wizard;"
2897                                + " allow priority " + filter.getPriority() + ";"
2898                                + " package: " + filter.activity.info.packageName
2899                                + " activity: " + filter.activity.className
2900                                + " priority: " + filter.getPriority());
2901                        }
2902                        // skip setup wizard; allow it to keep the high priority filter
2903                        continue;
2904                    }
2905                    if (DEBUG_FILTERS) {
2906                        Slog.i(TAG, "Protected action; cap priority to 0;"
2907                                + " package: " + filter.activity.info.packageName
2908                                + " activity: " + filter.activity.className
2909                                + " origPrio: " + filter.getPriority());
2910                    }
2911                    filter.setPriority(0);
2912                }
2913            }
2914            mDeferProtectedFilters = false;
2915            mProtectedFilters.clear();
2916
2917            // Now that we know all of the shared libraries, update all clients to have
2918            // the correct library paths.
2919            updateAllSharedLibrariesLPw(null);
2920
2921            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2922                // NOTE: We ignore potential failures here during a system scan (like
2923                // the rest of the commands above) because there's precious little we
2924                // can do about it. A settings error is reported, though.
2925                final List<String> changedAbiCodePath =
2926                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2927                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2928                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2929                        final String codePathString = changedAbiCodePath.get(i);
2930                        try {
2931                            mInstaller.rmdex(codePathString,
2932                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2933                        } catch (InstallerException ignored) {
2934                        }
2935                    }
2936                }
2937            }
2938
2939            // Now that we know all the packages we are keeping,
2940            // read and update their last usage times.
2941            mPackageUsage.read(mPackages);
2942            mCompilerStats.read();
2943
2944            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2945                    SystemClock.uptimeMillis());
2946            Slog.i(TAG, "Time to scan packages: "
2947                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2948                    + " seconds");
2949
2950            // If the platform SDK has changed since the last time we booted,
2951            // we need to re-grant app permission to catch any new ones that
2952            // appear.  This is really a hack, and means that apps can in some
2953            // cases get permissions that the user didn't initially explicitly
2954            // allow...  it would be nice to have some better way to handle
2955            // this situation.
2956            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2957            if (sdkUpdated) {
2958                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2959                        + mSdkVersion + "; regranting permissions for internal storage");
2960            }
2961            mPermissionManager.updateAllPermissions(
2962                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2963                    mPermissionCallback);
2964            ver.sdkVersion = mSdkVersion;
2965
2966            // If this is the first boot or an update from pre-M, and it is a normal
2967            // boot, then we need to initialize the default preferred apps across
2968            // all defined users.
2969            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2970                for (UserInfo user : sUserManager.getUsers(true)) {
2971                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2972                    applyFactoryDefaultBrowserLPw(user.id);
2973                    primeDomainVerificationsLPw(user.id);
2974                }
2975            }
2976
2977            // Prepare storage for system user really early during boot,
2978            // since core system apps like SettingsProvider and SystemUI
2979            // can't wait for user to start
2980            final int storageFlags;
2981            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2982                storageFlags = StorageManager.FLAG_STORAGE_DE;
2983            } else {
2984                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2985            }
2986            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2987                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2988                    true /* onlyCoreApps */);
2989            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2990                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2991                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2992                traceLog.traceBegin("AppDataFixup");
2993                try {
2994                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2995                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2996                } catch (InstallerException e) {
2997                    Slog.w(TAG, "Trouble fixing GIDs", e);
2998                }
2999                traceLog.traceEnd();
3000
3001                traceLog.traceBegin("AppDataPrepare");
3002                if (deferPackages == null || deferPackages.isEmpty()) {
3003                    return;
3004                }
3005                int count = 0;
3006                for (String pkgName : deferPackages) {
3007                    PackageParser.Package pkg = null;
3008                    synchronized (mPackages) {
3009                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3010                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3011                            pkg = ps.pkg;
3012                        }
3013                    }
3014                    if (pkg != null) {
3015                        synchronized (mInstallLock) {
3016                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3017                                    true /* maybeMigrateAppData */);
3018                        }
3019                        count++;
3020                    }
3021                }
3022                traceLog.traceEnd();
3023                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3024            }, "prepareAppData");
3025
3026            // If this is first boot after an OTA, and a normal boot, then
3027            // we need to clear code cache directories.
3028            // Note that we do *not* clear the application profiles. These remain valid
3029            // across OTAs and are used to drive profile verification (post OTA) and
3030            // profile compilation (without waiting to collect a fresh set of profiles).
3031            if (mIsUpgrade && !onlyCore) {
3032                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3033                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3034                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3035                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3036                        // No apps are running this early, so no need to freeze
3037                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3038                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3039                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3040                    }
3041                }
3042                ver.fingerprint = Build.FINGERPRINT;
3043            }
3044
3045            checkDefaultBrowser();
3046
3047            // clear only after permissions and other defaults have been updated
3048            mExistingSystemPackages.clear();
3049            mPromoteSystemApps = false;
3050
3051            // All the changes are done during package scanning.
3052            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3053
3054            // can downgrade to reader
3055            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3056            mSettings.writeLPr();
3057            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3058            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3059                    SystemClock.uptimeMillis());
3060
3061            if (!mOnlyCore) {
3062                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3063                mRequiredInstallerPackage = getRequiredInstallerLPr();
3064                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3065                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3066                if (mIntentFilterVerifierComponent != null) {
3067                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3068                            mIntentFilterVerifierComponent);
3069                } else {
3070                    mIntentFilterVerifier = null;
3071                }
3072                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3073                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3074                        SharedLibraryInfo.VERSION_UNDEFINED);
3075                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3076                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3077                        SharedLibraryInfo.VERSION_UNDEFINED);
3078            } else {
3079                mRequiredVerifierPackage = null;
3080                mRequiredInstallerPackage = null;
3081                mRequiredUninstallerPackage = null;
3082                mIntentFilterVerifierComponent = null;
3083                mIntentFilterVerifier = null;
3084                mServicesSystemSharedLibraryPackageName = null;
3085                mSharedSystemSharedLibraryPackageName = null;
3086            }
3087
3088            mInstallerService = new PackageInstallerService(context, this);
3089            mArtManagerService = new ArtManagerService(this, mInstaller, mInstallLock);
3090            final Pair<ComponentName, String> instantAppResolverComponent =
3091                    getInstantAppResolverLPr();
3092            if (instantAppResolverComponent != null) {
3093                if (DEBUG_EPHEMERAL) {
3094                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3095                }
3096                mInstantAppResolverConnection = new EphemeralResolverConnection(
3097                        mContext, instantAppResolverComponent.first,
3098                        instantAppResolverComponent.second);
3099                mInstantAppResolverSettingsComponent =
3100                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3101            } else {
3102                mInstantAppResolverConnection = null;
3103                mInstantAppResolverSettingsComponent = null;
3104            }
3105            updateInstantAppInstallerLocked(null);
3106
3107            // Read and update the usage of dex files.
3108            // Do this at the end of PM init so that all the packages have their
3109            // data directory reconciled.
3110            // At this point we know the code paths of the packages, so we can validate
3111            // the disk file and build the internal cache.
3112            // The usage file is expected to be small so loading and verifying it
3113            // should take a fairly small time compare to the other activities (e.g. package
3114            // scanning).
3115            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3116            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3117            for (int userId : currentUserIds) {
3118                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3119            }
3120            mDexManager.load(userPackages);
3121            if (mIsUpgrade) {
3122                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3123                        (int) (SystemClock.uptimeMillis() - startTime));
3124            }
3125        } // synchronized (mPackages)
3126        } // synchronized (mInstallLock)
3127
3128        // Now after opening every single application zip, make sure they
3129        // are all flushed.  Not really needed, but keeps things nice and
3130        // tidy.
3131        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3132        Runtime.getRuntime().gc();
3133        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3134
3135        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3136        FallbackCategoryProvider.loadFallbacks();
3137        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3138
3139        // The initial scanning above does many calls into installd while
3140        // holding the mPackages lock, but we're mostly interested in yelling
3141        // once we have a booted system.
3142        mInstaller.setWarnIfHeld(mPackages);
3143
3144        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3145    }
3146
3147    /**
3148     * Uncompress and install stub applications.
3149     * <p>In order to save space on the system partition, some applications are shipped in a
3150     * compressed form. In addition the compressed bits for the full application, the
3151     * system image contains a tiny stub comprised of only the Android manifest.
3152     * <p>During the first boot, attempt to uncompress and install the full application. If
3153     * the application can't be installed for any reason, disable the stub and prevent
3154     * uncompressing the full application during future boots.
3155     * <p>In order to forcefully attempt an installation of a full application, go to app
3156     * settings and enable the application.
3157     */
3158    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3159        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3160            final String pkgName = stubSystemApps.get(i);
3161            // skip if the system package is already disabled
3162            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3163                stubSystemApps.remove(i);
3164                continue;
3165            }
3166            // skip if the package isn't installed (?!); this should never happen
3167            final PackageParser.Package pkg = mPackages.get(pkgName);
3168            if (pkg == null) {
3169                stubSystemApps.remove(i);
3170                continue;
3171            }
3172            // skip if the package has been disabled by the user
3173            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3174            if (ps != null) {
3175                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3176                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3177                    stubSystemApps.remove(i);
3178                    continue;
3179                }
3180            }
3181
3182            if (DEBUG_COMPRESSION) {
3183                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3184            }
3185
3186            // uncompress the binary to its eventual destination on /data
3187            final File scanFile = decompressPackage(pkg);
3188            if (scanFile == null) {
3189                continue;
3190            }
3191
3192            // install the package to replace the stub on /system
3193            try {
3194                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3195                removePackageLI(pkg, true /*chatty*/);
3196                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3197                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3198                        UserHandle.USER_SYSTEM, "android");
3199                stubSystemApps.remove(i);
3200                continue;
3201            } catch (PackageManagerException e) {
3202                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3203            }
3204
3205            // any failed attempt to install the package will be cleaned up later
3206        }
3207
3208        // disable any stub still left; these failed to install the full application
3209        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3210            final String pkgName = stubSystemApps.get(i);
3211            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3212            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3213                    UserHandle.USER_SYSTEM, "android");
3214            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3215        }
3216    }
3217
3218    /**
3219     * Decompresses the given package on the system image onto
3220     * the /data partition.
3221     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3222     */
3223    private File decompressPackage(PackageParser.Package pkg) {
3224        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3225        if (compressedFiles == null || compressedFiles.length == 0) {
3226            if (DEBUG_COMPRESSION) {
3227                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3228            }
3229            return null;
3230        }
3231        final File dstCodePath =
3232                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3233        int ret = PackageManager.INSTALL_SUCCEEDED;
3234        try {
3235            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3236            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3237            for (File srcFile : compressedFiles) {
3238                final String srcFileName = srcFile.getName();
3239                final String dstFileName = srcFileName.substring(
3240                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3241                final File dstFile = new File(dstCodePath, dstFileName);
3242                ret = decompressFile(srcFile, dstFile);
3243                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3244                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3245                            + "; pkg: " + pkg.packageName
3246                            + ", file: " + dstFileName);
3247                    break;
3248                }
3249            }
3250        } catch (ErrnoException e) {
3251            logCriticalInfo(Log.ERROR, "Failed to decompress"
3252                    + "; pkg: " + pkg.packageName
3253                    + ", err: " + e.errno);
3254        }
3255        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3256            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3257            NativeLibraryHelper.Handle handle = null;
3258            try {
3259                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3260                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3261                        null /*abiOverride*/);
3262            } catch (IOException e) {
3263                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3264                        + "; pkg: " + pkg.packageName);
3265                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3266            } finally {
3267                IoUtils.closeQuietly(handle);
3268            }
3269        }
3270        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3271            if (dstCodePath == null || !dstCodePath.exists()) {
3272                return null;
3273            }
3274            removeCodePathLI(dstCodePath);
3275            return null;
3276        }
3277
3278        return dstCodePath;
3279    }
3280
3281    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3282        // we're only interested in updating the installer appliction when 1) it's not
3283        // already set or 2) the modified package is the installer
3284        if (mInstantAppInstallerActivity != null
3285                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3286                        .equals(modifiedPackage)) {
3287            return;
3288        }
3289        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3290    }
3291
3292    private static File preparePackageParserCache(boolean isUpgrade) {
3293        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3294            return null;
3295        }
3296
3297        // Disable package parsing on eng builds to allow for faster incremental development.
3298        if (Build.IS_ENG) {
3299            return null;
3300        }
3301
3302        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3303            Slog.i(TAG, "Disabling package parser cache due to system property.");
3304            return null;
3305        }
3306
3307        // The base directory for the package parser cache lives under /data/system/.
3308        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3309                "package_cache");
3310        if (cacheBaseDir == null) {
3311            return null;
3312        }
3313
3314        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3315        // This also serves to "GC" unused entries when the package cache version changes (which
3316        // can only happen during upgrades).
3317        if (isUpgrade) {
3318            FileUtils.deleteContents(cacheBaseDir);
3319        }
3320
3321
3322        // Return the versioned package cache directory. This is something like
3323        // "/data/system/package_cache/1"
3324        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3325
3326        // The following is a workaround to aid development on non-numbered userdebug
3327        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3328        // the system partition is newer.
3329        //
3330        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3331        // that starts with "eng." to signify that this is an engineering build and not
3332        // destined for release.
3333        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3334            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3335
3336            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3337            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3338            // in general and should not be used for production changes. In this specific case,
3339            // we know that they will work.
3340            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3341            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3342                FileUtils.deleteContents(cacheBaseDir);
3343                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3344            }
3345        }
3346
3347        return cacheDir;
3348    }
3349
3350    @Override
3351    public boolean isFirstBoot() {
3352        // allow instant applications
3353        return mFirstBoot;
3354    }
3355
3356    @Override
3357    public boolean isOnlyCoreApps() {
3358        // allow instant applications
3359        return mOnlyCore;
3360    }
3361
3362    @Override
3363    public boolean isUpgrade() {
3364        // allow instant applications
3365        // The system property allows testing ota flow when upgraded to the same image.
3366        return mIsUpgrade || SystemProperties.getBoolean(
3367                "persist.pm.mock-upgrade", false /* default */);
3368    }
3369
3370    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3371        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3372
3373        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3374                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3375                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3376        if (matches.size() == 1) {
3377            return matches.get(0).getComponentInfo().packageName;
3378        } else if (matches.size() == 0) {
3379            Log.e(TAG, "There should probably be a verifier, but, none were found");
3380            return null;
3381        }
3382        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3383    }
3384
3385    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3386        synchronized (mPackages) {
3387            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3388            if (libraryEntry == null) {
3389                throw new IllegalStateException("Missing required shared library:" + name);
3390            }
3391            return libraryEntry.apk;
3392        }
3393    }
3394
3395    private @NonNull String getRequiredInstallerLPr() {
3396        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3397        intent.addCategory(Intent.CATEGORY_DEFAULT);
3398        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3399
3400        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3401                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3402                UserHandle.USER_SYSTEM);
3403        if (matches.size() == 1) {
3404            ResolveInfo resolveInfo = matches.get(0);
3405            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3406                throw new RuntimeException("The installer must be a privileged app");
3407            }
3408            return matches.get(0).getComponentInfo().packageName;
3409        } else {
3410            throw new RuntimeException("There must be exactly one installer; found " + matches);
3411        }
3412    }
3413
3414    private @NonNull String getRequiredUninstallerLPr() {
3415        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3416        intent.addCategory(Intent.CATEGORY_DEFAULT);
3417        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3418
3419        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3420                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3421                UserHandle.USER_SYSTEM);
3422        if (resolveInfo == null ||
3423                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3424            throw new RuntimeException("There must be exactly one uninstaller; found "
3425                    + resolveInfo);
3426        }
3427        return resolveInfo.getComponentInfo().packageName;
3428    }
3429
3430    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3431        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3432
3433        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3434                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3435                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3436        ResolveInfo best = null;
3437        final int N = matches.size();
3438        for (int i = 0; i < N; i++) {
3439            final ResolveInfo cur = matches.get(i);
3440            final String packageName = cur.getComponentInfo().packageName;
3441            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3442                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3443                continue;
3444            }
3445
3446            if (best == null || cur.priority > best.priority) {
3447                best = cur;
3448            }
3449        }
3450
3451        if (best != null) {
3452            return best.getComponentInfo().getComponentName();
3453        }
3454        Slog.w(TAG, "Intent filter verifier not found");
3455        return null;
3456    }
3457
3458    @Override
3459    public @Nullable ComponentName getInstantAppResolverComponent() {
3460        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3461            return null;
3462        }
3463        synchronized (mPackages) {
3464            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3465            if (instantAppResolver == null) {
3466                return null;
3467            }
3468            return instantAppResolver.first;
3469        }
3470    }
3471
3472    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3473        final String[] packageArray =
3474                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3475        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3476            if (DEBUG_EPHEMERAL) {
3477                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3478            }
3479            return null;
3480        }
3481
3482        final int callingUid = Binder.getCallingUid();
3483        final int resolveFlags =
3484                MATCH_DIRECT_BOOT_AWARE
3485                | MATCH_DIRECT_BOOT_UNAWARE
3486                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3487        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3488        final Intent resolverIntent = new Intent(actionName);
3489        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3490                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3491        // temporarily look for the old action
3492        if (resolvers.size() == 0) {
3493            if (DEBUG_EPHEMERAL) {
3494                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3495            }
3496            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3497            resolverIntent.setAction(actionName);
3498            resolvers = queryIntentServicesInternal(resolverIntent, null,
3499                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3500        }
3501        final int N = resolvers.size();
3502        if (N == 0) {
3503            if (DEBUG_EPHEMERAL) {
3504                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3505            }
3506            return null;
3507        }
3508
3509        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3510        for (int i = 0; i < N; i++) {
3511            final ResolveInfo info = resolvers.get(i);
3512
3513            if (info.serviceInfo == null) {
3514                continue;
3515            }
3516
3517            final String packageName = info.serviceInfo.packageName;
3518            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3519                if (DEBUG_EPHEMERAL) {
3520                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3521                            + " pkg: " + packageName + ", info:" + info);
3522                }
3523                continue;
3524            }
3525
3526            if (DEBUG_EPHEMERAL) {
3527                Slog.v(TAG, "Ephemeral resolver found;"
3528                        + " pkg: " + packageName + ", info:" + info);
3529            }
3530            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3531        }
3532        if (DEBUG_EPHEMERAL) {
3533            Slog.v(TAG, "Ephemeral resolver NOT found");
3534        }
3535        return null;
3536    }
3537
3538    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3539        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3540        intent.addCategory(Intent.CATEGORY_DEFAULT);
3541        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3542
3543        final int resolveFlags =
3544                MATCH_DIRECT_BOOT_AWARE
3545                | MATCH_DIRECT_BOOT_UNAWARE
3546                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3547        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3548                resolveFlags, UserHandle.USER_SYSTEM);
3549        // temporarily look for the old action
3550        if (matches.isEmpty()) {
3551            if (DEBUG_EPHEMERAL) {
3552                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3553            }
3554            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3555            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3556                    resolveFlags, UserHandle.USER_SYSTEM);
3557        }
3558        Iterator<ResolveInfo> iter = matches.iterator();
3559        while (iter.hasNext()) {
3560            final ResolveInfo rInfo = iter.next();
3561            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3562            if (ps != null) {
3563                final PermissionsState permissionsState = ps.getPermissionsState();
3564                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3565                    continue;
3566                }
3567            }
3568            iter.remove();
3569        }
3570        if (matches.size() == 0) {
3571            return null;
3572        } else if (matches.size() == 1) {
3573            return (ActivityInfo) matches.get(0).getComponentInfo();
3574        } else {
3575            throw new RuntimeException(
3576                    "There must be at most one ephemeral installer; found " + matches);
3577        }
3578    }
3579
3580    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3581            @NonNull ComponentName resolver) {
3582        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3583                .addCategory(Intent.CATEGORY_DEFAULT)
3584                .setPackage(resolver.getPackageName());
3585        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3586        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3587                UserHandle.USER_SYSTEM);
3588        // temporarily look for the old action
3589        if (matches.isEmpty()) {
3590            if (DEBUG_EPHEMERAL) {
3591                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3592            }
3593            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3594            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3595                    UserHandle.USER_SYSTEM);
3596        }
3597        if (matches.isEmpty()) {
3598            return null;
3599        }
3600        return matches.get(0).getComponentInfo().getComponentName();
3601    }
3602
3603    private void primeDomainVerificationsLPw(int userId) {
3604        if (DEBUG_DOMAIN_VERIFICATION) {
3605            Slog.d(TAG, "Priming domain verifications in user " + userId);
3606        }
3607
3608        SystemConfig systemConfig = SystemConfig.getInstance();
3609        ArraySet<String> packages = systemConfig.getLinkedApps();
3610
3611        for (String packageName : packages) {
3612            PackageParser.Package pkg = mPackages.get(packageName);
3613            if (pkg != null) {
3614                if (!pkg.isSystem()) {
3615                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3616                    continue;
3617                }
3618
3619                ArraySet<String> domains = null;
3620                for (PackageParser.Activity a : pkg.activities) {
3621                    for (ActivityIntentInfo filter : a.intents) {
3622                        if (hasValidDomains(filter)) {
3623                            if (domains == null) {
3624                                domains = new ArraySet<String>();
3625                            }
3626                            domains.addAll(filter.getHostsList());
3627                        }
3628                    }
3629                }
3630
3631                if (domains != null && domains.size() > 0) {
3632                    if (DEBUG_DOMAIN_VERIFICATION) {
3633                        Slog.v(TAG, "      + " + packageName);
3634                    }
3635                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3636                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3637                    // and then 'always' in the per-user state actually used for intent resolution.
3638                    final IntentFilterVerificationInfo ivi;
3639                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3640                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3641                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3642                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3643                } else {
3644                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3645                            + "' does not handle web links");
3646                }
3647            } else {
3648                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3649            }
3650        }
3651
3652        scheduleWritePackageRestrictionsLocked(userId);
3653        scheduleWriteSettingsLocked();
3654    }
3655
3656    private void applyFactoryDefaultBrowserLPw(int userId) {
3657        // The default browser app's package name is stored in a string resource,
3658        // with a product-specific overlay used for vendor customization.
3659        String browserPkg = mContext.getResources().getString(
3660                com.android.internal.R.string.default_browser);
3661        if (!TextUtils.isEmpty(browserPkg)) {
3662            // non-empty string => required to be a known package
3663            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3664            if (ps == null) {
3665                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3666                browserPkg = null;
3667            } else {
3668                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3669            }
3670        }
3671
3672        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3673        // default.  If there's more than one, just leave everything alone.
3674        if (browserPkg == null) {
3675            calculateDefaultBrowserLPw(userId);
3676        }
3677    }
3678
3679    private void calculateDefaultBrowserLPw(int userId) {
3680        List<String> allBrowsers = resolveAllBrowserApps(userId);
3681        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3682        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3683    }
3684
3685    private List<String> resolveAllBrowserApps(int userId) {
3686        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3687        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3688                PackageManager.MATCH_ALL, userId);
3689
3690        final int count = list.size();
3691        List<String> result = new ArrayList<String>(count);
3692        for (int i=0; i<count; i++) {
3693            ResolveInfo info = list.get(i);
3694            if (info.activityInfo == null
3695                    || !info.handleAllWebDataURI
3696                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3697                    || result.contains(info.activityInfo.packageName)) {
3698                continue;
3699            }
3700            result.add(info.activityInfo.packageName);
3701        }
3702
3703        return result;
3704    }
3705
3706    private boolean packageIsBrowser(String packageName, int userId) {
3707        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3708                PackageManager.MATCH_ALL, userId);
3709        final int N = list.size();
3710        for (int i = 0; i < N; i++) {
3711            ResolveInfo info = list.get(i);
3712            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3713                return true;
3714            }
3715        }
3716        return false;
3717    }
3718
3719    private void checkDefaultBrowser() {
3720        final int myUserId = UserHandle.myUserId();
3721        final String packageName = getDefaultBrowserPackageName(myUserId);
3722        if (packageName != null) {
3723            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3724            if (info == null) {
3725                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3726                synchronized (mPackages) {
3727                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3728                }
3729            }
3730        }
3731    }
3732
3733    @Override
3734    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3735            throws RemoteException {
3736        try {
3737            return super.onTransact(code, data, reply, flags);
3738        } catch (RuntimeException e) {
3739            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3740                Slog.wtf(TAG, "Package Manager Crash", e);
3741            }
3742            throw e;
3743        }
3744    }
3745
3746    static int[] appendInts(int[] cur, int[] add) {
3747        if (add == null) return cur;
3748        if (cur == null) return add;
3749        final int N = add.length;
3750        for (int i=0; i<N; i++) {
3751            cur = appendInt(cur, add[i]);
3752        }
3753        return cur;
3754    }
3755
3756    /**
3757     * Returns whether or not a full application can see an instant application.
3758     * <p>
3759     * Currently, there are three cases in which this can occur:
3760     * <ol>
3761     * <li>The calling application is a "special" process. Special processes
3762     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3763     * <li>The calling application has the permission
3764     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3765     * <li>The calling application is the default launcher on the
3766     *     system partition.</li>
3767     * </ol>
3768     */
3769    private boolean canViewInstantApps(int callingUid, int userId) {
3770        if (callingUid < Process.FIRST_APPLICATION_UID) {
3771            return true;
3772        }
3773        if (mContext.checkCallingOrSelfPermission(
3774                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3775            return true;
3776        }
3777        if (mContext.checkCallingOrSelfPermission(
3778                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3779            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3780            if (homeComponent != null
3781                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3782                return true;
3783            }
3784        }
3785        return false;
3786    }
3787
3788    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3789        if (!sUserManager.exists(userId)) return null;
3790        if (ps == null) {
3791            return null;
3792        }
3793        PackageParser.Package p = ps.pkg;
3794        if (p == null) {
3795            return null;
3796        }
3797        final int callingUid = Binder.getCallingUid();
3798        // Filter out ephemeral app metadata:
3799        //   * The system/shell/root can see metadata for any app
3800        //   * An installed app can see metadata for 1) other installed apps
3801        //     and 2) ephemeral apps that have explicitly interacted with it
3802        //   * Ephemeral apps can only see their own data and exposed installed apps
3803        //   * Holding a signature permission allows seeing instant apps
3804        if (filterAppAccessLPr(ps, callingUid, userId)) {
3805            return null;
3806        }
3807
3808        final PermissionsState permissionsState = ps.getPermissionsState();
3809
3810        // Compute GIDs only if requested
3811        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3812                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3813        // Compute granted permissions only if package has requested permissions
3814        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3815                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3816        final PackageUserState state = ps.readUserState(userId);
3817
3818        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3819                && ps.isSystem()) {
3820            flags |= MATCH_ANY_USER;
3821        }
3822
3823        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3824                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3825
3826        if (packageInfo == null) {
3827            return null;
3828        }
3829
3830        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3831                resolveExternalPackageNameLPr(p);
3832
3833        return packageInfo;
3834    }
3835
3836    @Override
3837    public void checkPackageStartable(String packageName, int userId) {
3838        final int callingUid = Binder.getCallingUid();
3839        if (getInstantAppPackageName(callingUid) != null) {
3840            throw new SecurityException("Instant applications don't have access to this method");
3841        }
3842        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3843        synchronized (mPackages) {
3844            final PackageSetting ps = mSettings.mPackages.get(packageName);
3845            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3846                throw new SecurityException("Package " + packageName + " was not found!");
3847            }
3848
3849            if (!ps.getInstalled(userId)) {
3850                throw new SecurityException(
3851                        "Package " + packageName + " was not installed for user " + userId + "!");
3852            }
3853
3854            if (mSafeMode && !ps.isSystem()) {
3855                throw new SecurityException("Package " + packageName + " not a system app!");
3856            }
3857
3858            if (mFrozenPackages.contains(packageName)) {
3859                throw new SecurityException("Package " + packageName + " is currently frozen!");
3860            }
3861
3862            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3863                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3864            }
3865        }
3866    }
3867
3868    @Override
3869    public boolean isPackageAvailable(String packageName, int userId) {
3870        if (!sUserManager.exists(userId)) return false;
3871        final int callingUid = Binder.getCallingUid();
3872        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3873                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3874        synchronized (mPackages) {
3875            PackageParser.Package p = mPackages.get(packageName);
3876            if (p != null) {
3877                final PackageSetting ps = (PackageSetting) p.mExtras;
3878                if (filterAppAccessLPr(ps, callingUid, userId)) {
3879                    return false;
3880                }
3881                if (ps != null) {
3882                    final PackageUserState state = ps.readUserState(userId);
3883                    if (state != null) {
3884                        return PackageParser.isAvailable(state);
3885                    }
3886                }
3887            }
3888        }
3889        return false;
3890    }
3891
3892    @Override
3893    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3894        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3895                flags, Binder.getCallingUid(), userId);
3896    }
3897
3898    @Override
3899    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3900            int flags, int userId) {
3901        return getPackageInfoInternal(versionedPackage.getPackageName(),
3902                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3903    }
3904
3905    /**
3906     * Important: The provided filterCallingUid is used exclusively to filter out packages
3907     * that can be seen based on user state. It's typically the original caller uid prior
3908     * to clearing. Because it can only be provided by trusted code, it's value can be
3909     * trusted and will be used as-is; unlike userId which will be validated by this method.
3910     */
3911    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3912            int flags, int filterCallingUid, int userId) {
3913        if (!sUserManager.exists(userId)) return null;
3914        flags = updateFlagsForPackage(flags, userId, packageName);
3915        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3916                false /* requireFullPermission */, false /* checkShell */, "get package info");
3917
3918        // reader
3919        synchronized (mPackages) {
3920            // Normalize package name to handle renamed packages and static libs
3921            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3922
3923            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3924            if (matchFactoryOnly) {
3925                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3926                if (ps != null) {
3927                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3928                        return null;
3929                    }
3930                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3931                        return null;
3932                    }
3933                    return generatePackageInfo(ps, flags, userId);
3934                }
3935            }
3936
3937            PackageParser.Package p = mPackages.get(packageName);
3938            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3939                return null;
3940            }
3941            if (DEBUG_PACKAGE_INFO)
3942                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3943            if (p != null) {
3944                final PackageSetting ps = (PackageSetting) p.mExtras;
3945                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3946                    return null;
3947                }
3948                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3949                    return null;
3950                }
3951                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3952            }
3953            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3954                final PackageSetting ps = mSettings.mPackages.get(packageName);
3955                if (ps == null) return null;
3956                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3957                    return null;
3958                }
3959                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3960                    return null;
3961                }
3962                return generatePackageInfo(ps, flags, userId);
3963            }
3964        }
3965        return null;
3966    }
3967
3968    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3969        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3970            return true;
3971        }
3972        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3973            return true;
3974        }
3975        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3976            return true;
3977        }
3978        return false;
3979    }
3980
3981    private boolean isComponentVisibleToInstantApp(
3982            @Nullable ComponentName component, @ComponentType int type) {
3983        if (type == TYPE_ACTIVITY) {
3984            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3985            return activity != null
3986                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3987                    : false;
3988        } else if (type == TYPE_RECEIVER) {
3989            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3990            return activity != null
3991                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3992                    : false;
3993        } else if (type == TYPE_SERVICE) {
3994            final PackageParser.Service service = mServices.mServices.get(component);
3995            return service != null
3996                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3997                    : false;
3998        } else if (type == TYPE_PROVIDER) {
3999            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4000            return provider != null
4001                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4002                    : false;
4003        } else if (type == TYPE_UNKNOWN) {
4004            return isComponentVisibleToInstantApp(component);
4005        }
4006        return false;
4007    }
4008
4009    /**
4010     * Returns whether or not access to the application should be filtered.
4011     * <p>
4012     * Access may be limited based upon whether the calling or target applications
4013     * are instant applications.
4014     *
4015     * @see #canAccessInstantApps(int)
4016     */
4017    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4018            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4019        // if we're in an isolated process, get the real calling UID
4020        if (Process.isIsolated(callingUid)) {
4021            callingUid = mIsolatedOwners.get(callingUid);
4022        }
4023        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4024        final boolean callerIsInstantApp = instantAppPkgName != null;
4025        if (ps == null) {
4026            if (callerIsInstantApp) {
4027                // pretend the application exists, but, needs to be filtered
4028                return true;
4029            }
4030            return false;
4031        }
4032        // if the target and caller are the same application, don't filter
4033        if (isCallerSameApp(ps.name, callingUid)) {
4034            return false;
4035        }
4036        if (callerIsInstantApp) {
4037            // request for a specific component; if it hasn't been explicitly exposed, filter
4038            if (component != null) {
4039                return !isComponentVisibleToInstantApp(component, componentType);
4040            }
4041            // request for application; if no components have been explicitly exposed, filter
4042            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4043        }
4044        if (ps.getInstantApp(userId)) {
4045            // caller can see all components of all instant applications, don't filter
4046            if (canViewInstantApps(callingUid, userId)) {
4047                return false;
4048            }
4049            // request for a specific instant application component, filter
4050            if (component != null) {
4051                return true;
4052            }
4053            // request for an instant application; if the caller hasn't been granted access, filter
4054            return !mInstantAppRegistry.isInstantAccessGranted(
4055                    userId, UserHandle.getAppId(callingUid), ps.appId);
4056        }
4057        return false;
4058    }
4059
4060    /**
4061     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4062     */
4063    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4064        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4065    }
4066
4067    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4068            int flags) {
4069        // Callers can access only the libs they depend on, otherwise they need to explicitly
4070        // ask for the shared libraries given the caller is allowed to access all static libs.
4071        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4072            // System/shell/root get to see all static libs
4073            final int appId = UserHandle.getAppId(uid);
4074            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4075                    || appId == Process.ROOT_UID) {
4076                return false;
4077            }
4078        }
4079
4080        // No package means no static lib as it is always on internal storage
4081        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4082            return false;
4083        }
4084
4085        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4086                ps.pkg.staticSharedLibVersion);
4087        if (libEntry == null) {
4088            return false;
4089        }
4090
4091        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4092        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4093        if (uidPackageNames == null) {
4094            return true;
4095        }
4096
4097        for (String uidPackageName : uidPackageNames) {
4098            if (ps.name.equals(uidPackageName)) {
4099                return false;
4100            }
4101            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4102            if (uidPs != null) {
4103                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4104                        libEntry.info.getName());
4105                if (index < 0) {
4106                    continue;
4107                }
4108                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4109                    return false;
4110                }
4111            }
4112        }
4113        return true;
4114    }
4115
4116    @Override
4117    public String[] currentToCanonicalPackageNames(String[] names) {
4118        final int callingUid = Binder.getCallingUid();
4119        if (getInstantAppPackageName(callingUid) != null) {
4120            return names;
4121        }
4122        final String[] out = new String[names.length];
4123        // reader
4124        synchronized (mPackages) {
4125            final int callingUserId = UserHandle.getUserId(callingUid);
4126            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4127            for (int i=names.length-1; i>=0; i--) {
4128                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4129                boolean translateName = false;
4130                if (ps != null && ps.realName != null) {
4131                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4132                    translateName = !targetIsInstantApp
4133                            || canViewInstantApps
4134                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4135                                    UserHandle.getAppId(callingUid), ps.appId);
4136                }
4137                out[i] = translateName ? ps.realName : names[i];
4138            }
4139        }
4140        return out;
4141    }
4142
4143    @Override
4144    public String[] canonicalToCurrentPackageNames(String[] names) {
4145        final int callingUid = Binder.getCallingUid();
4146        if (getInstantAppPackageName(callingUid) != null) {
4147            return names;
4148        }
4149        final String[] out = new String[names.length];
4150        // reader
4151        synchronized (mPackages) {
4152            final int callingUserId = UserHandle.getUserId(callingUid);
4153            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4154            for (int i=names.length-1; i>=0; i--) {
4155                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4156                boolean translateName = false;
4157                if (cur != null) {
4158                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4159                    final boolean targetIsInstantApp =
4160                            ps != null && ps.getInstantApp(callingUserId);
4161                    translateName = !targetIsInstantApp
4162                            || canViewInstantApps
4163                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4164                                    UserHandle.getAppId(callingUid), ps.appId);
4165                }
4166                out[i] = translateName ? cur : names[i];
4167            }
4168        }
4169        return out;
4170    }
4171
4172    @Override
4173    public int getPackageUid(String packageName, int flags, int userId) {
4174        if (!sUserManager.exists(userId)) return -1;
4175        final int callingUid = Binder.getCallingUid();
4176        flags = updateFlagsForPackage(flags, userId, packageName);
4177        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4178                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4179
4180        // reader
4181        synchronized (mPackages) {
4182            final PackageParser.Package p = mPackages.get(packageName);
4183            if (p != null && p.isMatch(flags)) {
4184                PackageSetting ps = (PackageSetting) p.mExtras;
4185                if (filterAppAccessLPr(ps, callingUid, userId)) {
4186                    return -1;
4187                }
4188                return UserHandle.getUid(userId, p.applicationInfo.uid);
4189            }
4190            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4191                final PackageSetting ps = mSettings.mPackages.get(packageName);
4192                if (ps != null && ps.isMatch(flags)
4193                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4194                    return UserHandle.getUid(userId, ps.appId);
4195                }
4196            }
4197        }
4198
4199        return -1;
4200    }
4201
4202    @Override
4203    public int[] getPackageGids(String packageName, int flags, int userId) {
4204        if (!sUserManager.exists(userId)) return null;
4205        final int callingUid = Binder.getCallingUid();
4206        flags = updateFlagsForPackage(flags, userId, packageName);
4207        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4208                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4209
4210        // reader
4211        synchronized (mPackages) {
4212            final PackageParser.Package p = mPackages.get(packageName);
4213            if (p != null && p.isMatch(flags)) {
4214                PackageSetting ps = (PackageSetting) p.mExtras;
4215                if (filterAppAccessLPr(ps, callingUid, userId)) {
4216                    return null;
4217                }
4218                // TODO: Shouldn't this be checking for package installed state for userId and
4219                // return null?
4220                return ps.getPermissionsState().computeGids(userId);
4221            }
4222            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4223                final PackageSetting ps = mSettings.mPackages.get(packageName);
4224                if (ps != null && ps.isMatch(flags)
4225                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4226                    return ps.getPermissionsState().computeGids(userId);
4227                }
4228            }
4229        }
4230
4231        return null;
4232    }
4233
4234    @Override
4235    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4236        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4237    }
4238
4239    @Override
4240    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4241            int flags) {
4242        final List<PermissionInfo> permissionList =
4243                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4244        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4245    }
4246
4247    @Override
4248    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4249        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4250    }
4251
4252    @Override
4253    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4254        final List<PermissionGroupInfo> permissionList =
4255                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4256        return (permissionList == null)
4257                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4258    }
4259
4260    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4261            int filterCallingUid, int userId) {
4262        if (!sUserManager.exists(userId)) return null;
4263        PackageSetting ps = mSettings.mPackages.get(packageName);
4264        if (ps != null) {
4265            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4266                return null;
4267            }
4268            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4269                return null;
4270            }
4271            if (ps.pkg == null) {
4272                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4273                if (pInfo != null) {
4274                    return pInfo.applicationInfo;
4275                }
4276                return null;
4277            }
4278            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4279                    ps.readUserState(userId), userId);
4280            if (ai != null) {
4281                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4282            }
4283            return ai;
4284        }
4285        return null;
4286    }
4287
4288    @Override
4289    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4290        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4291    }
4292
4293    /**
4294     * Important: The provided filterCallingUid is used exclusively to filter out applications
4295     * that can be seen based on user state. It's typically the original caller uid prior
4296     * to clearing. Because it can only be provided by trusted code, it's value can be
4297     * trusted and will be used as-is; unlike userId which will be validated by this method.
4298     */
4299    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4300            int filterCallingUid, int userId) {
4301        if (!sUserManager.exists(userId)) return null;
4302        flags = updateFlagsForApplication(flags, userId, packageName);
4303        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4304                false /* requireFullPermission */, false /* checkShell */, "get application info");
4305
4306        // writer
4307        synchronized (mPackages) {
4308            // Normalize package name to handle renamed packages and static libs
4309            packageName = resolveInternalPackageNameLPr(packageName,
4310                    PackageManager.VERSION_CODE_HIGHEST);
4311
4312            PackageParser.Package p = mPackages.get(packageName);
4313            if (DEBUG_PACKAGE_INFO) Log.v(
4314                    TAG, "getApplicationInfo " + packageName
4315                    + ": " + p);
4316            if (p != null) {
4317                PackageSetting ps = mSettings.mPackages.get(packageName);
4318                if (ps == null) return null;
4319                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4320                    return null;
4321                }
4322                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4323                    return null;
4324                }
4325                // Note: isEnabledLP() does not apply here - always return info
4326                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4327                        p, flags, ps.readUserState(userId), userId);
4328                if (ai != null) {
4329                    ai.packageName = resolveExternalPackageNameLPr(p);
4330                }
4331                return ai;
4332            }
4333            if ("android".equals(packageName)||"system".equals(packageName)) {
4334                return mAndroidApplication;
4335            }
4336            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4337                // Already generates the external package name
4338                return generateApplicationInfoFromSettingsLPw(packageName,
4339                        flags, filterCallingUid, userId);
4340            }
4341        }
4342        return null;
4343    }
4344
4345    private String normalizePackageNameLPr(String packageName) {
4346        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4347        return normalizedPackageName != null ? normalizedPackageName : packageName;
4348    }
4349
4350    @Override
4351    public void deletePreloadsFileCache() {
4352        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4353            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4354        }
4355        File dir = Environment.getDataPreloadsFileCacheDirectory();
4356        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4357        FileUtils.deleteContents(dir);
4358    }
4359
4360    @Override
4361    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4362            final int storageFlags, final IPackageDataObserver observer) {
4363        mContext.enforceCallingOrSelfPermission(
4364                android.Manifest.permission.CLEAR_APP_CACHE, null);
4365        mHandler.post(() -> {
4366            boolean success = false;
4367            try {
4368                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4369                success = true;
4370            } catch (IOException e) {
4371                Slog.w(TAG, e);
4372            }
4373            if (observer != null) {
4374                try {
4375                    observer.onRemoveCompleted(null, success);
4376                } catch (RemoteException e) {
4377                    Slog.w(TAG, e);
4378                }
4379            }
4380        });
4381    }
4382
4383    @Override
4384    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4385            final int storageFlags, final IntentSender pi) {
4386        mContext.enforceCallingOrSelfPermission(
4387                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4388        mHandler.post(() -> {
4389            boolean success = false;
4390            try {
4391                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4392                success = true;
4393            } catch (IOException e) {
4394                Slog.w(TAG, e);
4395            }
4396            if (pi != null) {
4397                try {
4398                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4399                } catch (SendIntentException e) {
4400                    Slog.w(TAG, e);
4401                }
4402            }
4403        });
4404    }
4405
4406    /**
4407     * Blocking call to clear various types of cached data across the system
4408     * until the requested bytes are available.
4409     */
4410    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4411        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4412        final File file = storage.findPathForUuid(volumeUuid);
4413        if (file.getUsableSpace() >= bytes) return;
4414
4415        if (ENABLE_FREE_CACHE_V2) {
4416            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4417                    volumeUuid);
4418            final boolean aggressive = (storageFlags
4419                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4420            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4421
4422            // 1. Pre-flight to determine if we have any chance to succeed
4423            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4424            if (internalVolume && (aggressive || SystemProperties
4425                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4426                deletePreloadsFileCache();
4427                if (file.getUsableSpace() >= bytes) return;
4428            }
4429
4430            // 3. Consider parsed APK data (aggressive only)
4431            if (internalVolume && aggressive) {
4432                FileUtils.deleteContents(mCacheDir);
4433                if (file.getUsableSpace() >= bytes) return;
4434            }
4435
4436            // 4. Consider cached app data (above quotas)
4437            try {
4438                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4439                        Installer.FLAG_FREE_CACHE_V2);
4440            } catch (InstallerException ignored) {
4441            }
4442            if (file.getUsableSpace() >= bytes) return;
4443
4444            // 5. Consider shared libraries with refcount=0 and age>min cache period
4445            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4446                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4447                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4448                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4449                return;
4450            }
4451
4452            // 6. Consider dexopt output (aggressive only)
4453            // TODO: Implement
4454
4455            // 7. Consider installed instant apps unused longer than min cache period
4456            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4457                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4458                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4459                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4460                return;
4461            }
4462
4463            // 8. Consider cached app data (below quotas)
4464            try {
4465                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4466                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4467            } catch (InstallerException ignored) {
4468            }
4469            if (file.getUsableSpace() >= bytes) return;
4470
4471            // 9. Consider DropBox entries
4472            // TODO: Implement
4473
4474            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4475            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4476                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4477                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4478                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4479                return;
4480            }
4481        } else {
4482            try {
4483                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4484            } catch (InstallerException ignored) {
4485            }
4486            if (file.getUsableSpace() >= bytes) return;
4487        }
4488
4489        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4490    }
4491
4492    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4493            throws IOException {
4494        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4495        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4496
4497        List<VersionedPackage> packagesToDelete = null;
4498        final long now = System.currentTimeMillis();
4499
4500        synchronized (mPackages) {
4501            final int[] allUsers = sUserManager.getUserIds();
4502            final int libCount = mSharedLibraries.size();
4503            for (int i = 0; i < libCount; i++) {
4504                final LongSparseArray<SharedLibraryEntry> versionedLib
4505                        = mSharedLibraries.valueAt(i);
4506                if (versionedLib == null) {
4507                    continue;
4508                }
4509                final int versionCount = versionedLib.size();
4510                for (int j = 0; j < versionCount; j++) {
4511                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4512                    // Skip packages that are not static shared libs.
4513                    if (!libInfo.isStatic()) {
4514                        break;
4515                    }
4516                    // Important: We skip static shared libs used for some user since
4517                    // in such a case we need to keep the APK on the device. The check for
4518                    // a lib being used for any user is performed by the uninstall call.
4519                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4520                    // Resolve the package name - we use synthetic package names internally
4521                    final String internalPackageName = resolveInternalPackageNameLPr(
4522                            declaringPackage.getPackageName(),
4523                            declaringPackage.getLongVersionCode());
4524                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4525                    // Skip unused static shared libs cached less than the min period
4526                    // to prevent pruning a lib needed by a subsequently installed package.
4527                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4528                        continue;
4529                    }
4530                    if (packagesToDelete == null) {
4531                        packagesToDelete = new ArrayList<>();
4532                    }
4533                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4534                            declaringPackage.getLongVersionCode()));
4535                }
4536            }
4537        }
4538
4539        if (packagesToDelete != null) {
4540            final int packageCount = packagesToDelete.size();
4541            for (int i = 0; i < packageCount; i++) {
4542                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4543                // Delete the package synchronously (will fail of the lib used for any user).
4544                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4545                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4546                                == PackageManager.DELETE_SUCCEEDED) {
4547                    if (volume.getUsableSpace() >= neededSpace) {
4548                        return true;
4549                    }
4550                }
4551            }
4552        }
4553
4554        return false;
4555    }
4556
4557    /**
4558     * Update given flags based on encryption status of current user.
4559     */
4560    private int updateFlags(int flags, int userId) {
4561        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4562                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4563            // Caller expressed an explicit opinion about what encryption
4564            // aware/unaware components they want to see, so fall through and
4565            // give them what they want
4566        } else {
4567            // Caller expressed no opinion, so match based on user state
4568            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4569                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4570            } else {
4571                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4572            }
4573        }
4574        return flags;
4575    }
4576
4577    private UserManagerInternal getUserManagerInternal() {
4578        if (mUserManagerInternal == null) {
4579            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4580        }
4581        return mUserManagerInternal;
4582    }
4583
4584    private ActivityManagerInternal getActivityManagerInternal() {
4585        if (mActivityManagerInternal == null) {
4586            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4587        }
4588        return mActivityManagerInternal;
4589    }
4590
4591
4592    private DeviceIdleController.LocalService getDeviceIdleController() {
4593        if (mDeviceIdleController == null) {
4594            mDeviceIdleController =
4595                    LocalServices.getService(DeviceIdleController.LocalService.class);
4596        }
4597        return mDeviceIdleController;
4598    }
4599
4600    /**
4601     * Update given flags when being used to request {@link PackageInfo}.
4602     */
4603    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4604        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4605        boolean triaged = true;
4606        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4607                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4608            // Caller is asking for component details, so they'd better be
4609            // asking for specific encryption matching behavior, or be triaged
4610            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4611                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4612                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4613                triaged = false;
4614            }
4615        }
4616        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4617                | PackageManager.MATCH_SYSTEM_ONLY
4618                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4619            triaged = false;
4620        }
4621        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4622            mPermissionManager.enforceCrossUserPermission(
4623                    Binder.getCallingUid(), userId, false, false,
4624                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4625                    + Debug.getCallers(5));
4626        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4627                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4628            // If the caller wants all packages and has a restricted profile associated with it,
4629            // then match all users. This is to make sure that launchers that need to access work
4630            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4631            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4632            flags |= PackageManager.MATCH_ANY_USER;
4633        }
4634        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4635            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4636                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4637        }
4638        return updateFlags(flags, userId);
4639    }
4640
4641    /**
4642     * Update given flags when being used to request {@link ApplicationInfo}.
4643     */
4644    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4645        return updateFlagsForPackage(flags, userId, cookie);
4646    }
4647
4648    /**
4649     * Update given flags when being used to request {@link ComponentInfo}.
4650     */
4651    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4652        if (cookie instanceof Intent) {
4653            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4654                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4655            }
4656        }
4657
4658        boolean triaged = true;
4659        // Caller is asking for component details, so they'd better be
4660        // asking for specific encryption matching behavior, or be triaged
4661        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4662                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4663                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4664            triaged = false;
4665        }
4666        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4667            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4668                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4669        }
4670
4671        return updateFlags(flags, userId);
4672    }
4673
4674    /**
4675     * Update given intent when being used to request {@link ResolveInfo}.
4676     */
4677    private Intent updateIntentForResolve(Intent intent) {
4678        if (intent.getSelector() != null) {
4679            intent = intent.getSelector();
4680        }
4681        if (DEBUG_PREFERRED) {
4682            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4683        }
4684        return intent;
4685    }
4686
4687    /**
4688     * Update given flags when being used to request {@link ResolveInfo}.
4689     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4690     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4691     * flag set. However, this flag is only honoured in three circumstances:
4692     * <ul>
4693     * <li>when called from a system process</li>
4694     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4695     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4696     * action and a {@code android.intent.category.BROWSABLE} category</li>
4697     * </ul>
4698     */
4699    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4700        return updateFlagsForResolve(flags, userId, intent, callingUid,
4701                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4702    }
4703    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4704            boolean wantInstantApps) {
4705        return updateFlagsForResolve(flags, userId, intent, callingUid,
4706                wantInstantApps, false /*onlyExposedExplicitly*/);
4707    }
4708    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4709            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4710        // Safe mode means we shouldn't match any third-party components
4711        if (mSafeMode) {
4712            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4713        }
4714        if (getInstantAppPackageName(callingUid) != null) {
4715            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4716            if (onlyExposedExplicitly) {
4717                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4718            }
4719            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4720            flags |= PackageManager.MATCH_INSTANT;
4721        } else {
4722            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4723            final boolean allowMatchInstant =
4724                    (wantInstantApps
4725                            && Intent.ACTION_VIEW.equals(intent.getAction())
4726                            && hasWebURI(intent))
4727                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4728            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4729                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4730            if (!allowMatchInstant) {
4731                flags &= ~PackageManager.MATCH_INSTANT;
4732            }
4733        }
4734        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4735    }
4736
4737    @Override
4738    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4739        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4740    }
4741
4742    /**
4743     * Important: The provided filterCallingUid is used exclusively to filter out activities
4744     * that can be seen based on user state. It's typically the original caller uid prior
4745     * to clearing. Because it can only be provided by trusted code, it's value can be
4746     * trusted and will be used as-is; unlike userId which will be validated by this method.
4747     */
4748    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4749            int filterCallingUid, int userId) {
4750        if (!sUserManager.exists(userId)) return null;
4751        flags = updateFlagsForComponent(flags, userId, component);
4752
4753        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4754            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4755                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4756        }
4757
4758        synchronized (mPackages) {
4759            PackageParser.Activity a = mActivities.mActivities.get(component);
4760
4761            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4762            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4763                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4764                if (ps == null) return null;
4765                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4766                    return null;
4767                }
4768                return PackageParser.generateActivityInfo(
4769                        a, flags, ps.readUserState(userId), userId);
4770            }
4771            if (mResolveComponentName.equals(component)) {
4772                return PackageParser.generateActivityInfo(
4773                        mResolveActivity, flags, new PackageUserState(), userId);
4774            }
4775        }
4776        return null;
4777    }
4778
4779    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4780        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4781            return false;
4782        }
4783        final long token = Binder.clearCallingIdentity();
4784        try {
4785            final int callingUserId = UserHandle.getUserId(callingUid);
4786            if (ActivityManager.getCurrentUser() != callingUserId) {
4787                return false;
4788            }
4789            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4790        } finally {
4791            Binder.restoreCallingIdentity(token);
4792        }
4793    }
4794
4795    @Override
4796    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4797            String resolvedType) {
4798        synchronized (mPackages) {
4799            if (component.equals(mResolveComponentName)) {
4800                // The resolver supports EVERYTHING!
4801                return true;
4802            }
4803            final int callingUid = Binder.getCallingUid();
4804            final int callingUserId = UserHandle.getUserId(callingUid);
4805            PackageParser.Activity a = mActivities.mActivities.get(component);
4806            if (a == null) {
4807                return false;
4808            }
4809            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4810            if (ps == null) {
4811                return false;
4812            }
4813            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4814                return false;
4815            }
4816            for (int i=0; i<a.intents.size(); i++) {
4817                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4818                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4819                    return true;
4820                }
4821            }
4822            return false;
4823        }
4824    }
4825
4826    @Override
4827    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4828        if (!sUserManager.exists(userId)) return null;
4829        final int callingUid = Binder.getCallingUid();
4830        flags = updateFlagsForComponent(flags, userId, component);
4831        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4832                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4833        synchronized (mPackages) {
4834            PackageParser.Activity a = mReceivers.mActivities.get(component);
4835            if (DEBUG_PACKAGE_INFO) Log.v(
4836                TAG, "getReceiverInfo " + component + ": " + a);
4837            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4838                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4839                if (ps == null) return null;
4840                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4841                    return null;
4842                }
4843                return PackageParser.generateActivityInfo(
4844                        a, flags, ps.readUserState(userId), userId);
4845            }
4846        }
4847        return null;
4848    }
4849
4850    @Override
4851    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4852            int flags, int userId) {
4853        if (!sUserManager.exists(userId)) return null;
4854        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4855        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4856            return null;
4857        }
4858
4859        flags = updateFlagsForPackage(flags, userId, null);
4860
4861        final boolean canSeeStaticLibraries =
4862                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4863                        == PERMISSION_GRANTED
4864                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4865                        == PERMISSION_GRANTED
4866                || canRequestPackageInstallsInternal(packageName,
4867                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4868                        false  /* throwIfPermNotDeclared*/)
4869                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4870                        == PERMISSION_GRANTED;
4871
4872        synchronized (mPackages) {
4873            List<SharedLibraryInfo> result = null;
4874
4875            final int libCount = mSharedLibraries.size();
4876            for (int i = 0; i < libCount; i++) {
4877                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4878                if (versionedLib == null) {
4879                    continue;
4880                }
4881
4882                final int versionCount = versionedLib.size();
4883                for (int j = 0; j < versionCount; j++) {
4884                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4885                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4886                        break;
4887                    }
4888                    final long identity = Binder.clearCallingIdentity();
4889                    try {
4890                        PackageInfo packageInfo = getPackageInfoVersioned(
4891                                libInfo.getDeclaringPackage(), flags
4892                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4893                        if (packageInfo == null) {
4894                            continue;
4895                        }
4896                    } finally {
4897                        Binder.restoreCallingIdentity(identity);
4898                    }
4899
4900                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4901                            libInfo.getLongVersion(), libInfo.getType(),
4902                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4903                            flags, userId));
4904
4905                    if (result == null) {
4906                        result = new ArrayList<>();
4907                    }
4908                    result.add(resLibInfo);
4909                }
4910            }
4911
4912            return result != null ? new ParceledListSlice<>(result) : null;
4913        }
4914    }
4915
4916    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4917            SharedLibraryInfo libInfo, int flags, int userId) {
4918        List<VersionedPackage> versionedPackages = null;
4919        final int packageCount = mSettings.mPackages.size();
4920        for (int i = 0; i < packageCount; i++) {
4921            PackageSetting ps = mSettings.mPackages.valueAt(i);
4922
4923            if (ps == null) {
4924                continue;
4925            }
4926
4927            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4928                continue;
4929            }
4930
4931            final String libName = libInfo.getName();
4932            if (libInfo.isStatic()) {
4933                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4934                if (libIdx < 0) {
4935                    continue;
4936                }
4937                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4938                    continue;
4939                }
4940                if (versionedPackages == null) {
4941                    versionedPackages = new ArrayList<>();
4942                }
4943                // If the dependent is a static shared lib, use the public package name
4944                String dependentPackageName = ps.name;
4945                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4946                    dependentPackageName = ps.pkg.manifestPackageName;
4947                }
4948                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4949            } else if (ps.pkg != null) {
4950                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4951                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4952                    if (versionedPackages == null) {
4953                        versionedPackages = new ArrayList<>();
4954                    }
4955                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4956                }
4957            }
4958        }
4959
4960        return versionedPackages;
4961    }
4962
4963    @Override
4964    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4965        if (!sUserManager.exists(userId)) return null;
4966        final int callingUid = Binder.getCallingUid();
4967        flags = updateFlagsForComponent(flags, userId, component);
4968        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4969                false /* requireFullPermission */, false /* checkShell */, "get service info");
4970        synchronized (mPackages) {
4971            PackageParser.Service s = mServices.mServices.get(component);
4972            if (DEBUG_PACKAGE_INFO) Log.v(
4973                TAG, "getServiceInfo " + component + ": " + s);
4974            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4975                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4976                if (ps == null) return null;
4977                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4978                    return null;
4979                }
4980                return PackageParser.generateServiceInfo(
4981                        s, flags, ps.readUserState(userId), userId);
4982            }
4983        }
4984        return null;
4985    }
4986
4987    @Override
4988    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4989        if (!sUserManager.exists(userId)) return null;
4990        final int callingUid = Binder.getCallingUid();
4991        flags = updateFlagsForComponent(flags, userId, component);
4992        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4993                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4994        synchronized (mPackages) {
4995            PackageParser.Provider p = mProviders.mProviders.get(component);
4996            if (DEBUG_PACKAGE_INFO) Log.v(
4997                TAG, "getProviderInfo " + component + ": " + p);
4998            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4999                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5000                if (ps == null) return null;
5001                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5002                    return null;
5003                }
5004                return PackageParser.generateProviderInfo(
5005                        p, flags, ps.readUserState(userId), userId);
5006            }
5007        }
5008        return null;
5009    }
5010
5011    @Override
5012    public String[] getSystemSharedLibraryNames() {
5013        // allow instant applications
5014        synchronized (mPackages) {
5015            Set<String> libs = null;
5016            final int libCount = mSharedLibraries.size();
5017            for (int i = 0; i < libCount; i++) {
5018                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5019                if (versionedLib == null) {
5020                    continue;
5021                }
5022                final int versionCount = versionedLib.size();
5023                for (int j = 0; j < versionCount; j++) {
5024                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5025                    if (!libEntry.info.isStatic()) {
5026                        if (libs == null) {
5027                            libs = new ArraySet<>();
5028                        }
5029                        libs.add(libEntry.info.getName());
5030                        break;
5031                    }
5032                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5033                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5034                            UserHandle.getUserId(Binder.getCallingUid()),
5035                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5036                        if (libs == null) {
5037                            libs = new ArraySet<>();
5038                        }
5039                        libs.add(libEntry.info.getName());
5040                        break;
5041                    }
5042                }
5043            }
5044
5045            if (libs != null) {
5046                String[] libsArray = new String[libs.size()];
5047                libs.toArray(libsArray);
5048                return libsArray;
5049            }
5050
5051            return null;
5052        }
5053    }
5054
5055    @Override
5056    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5057        // allow instant applications
5058        synchronized (mPackages) {
5059            return mServicesSystemSharedLibraryPackageName;
5060        }
5061    }
5062
5063    @Override
5064    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5065        // allow instant applications
5066        synchronized (mPackages) {
5067            return mSharedSystemSharedLibraryPackageName;
5068        }
5069    }
5070
5071    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5072        for (int i = userList.length - 1; i >= 0; --i) {
5073            final int userId = userList[i];
5074            // don't add instant app to the list of updates
5075            if (pkgSetting.getInstantApp(userId)) {
5076                continue;
5077            }
5078            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5079            if (changedPackages == null) {
5080                changedPackages = new SparseArray<>();
5081                mChangedPackages.put(userId, changedPackages);
5082            }
5083            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5084            if (sequenceNumbers == null) {
5085                sequenceNumbers = new HashMap<>();
5086                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5087            }
5088            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5089            if (sequenceNumber != null) {
5090                changedPackages.remove(sequenceNumber);
5091            }
5092            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5093            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5094        }
5095        mChangedPackagesSequenceNumber++;
5096    }
5097
5098    @Override
5099    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5100        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5101            return null;
5102        }
5103        synchronized (mPackages) {
5104            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5105                return null;
5106            }
5107            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5108            if (changedPackages == null) {
5109                return null;
5110            }
5111            final List<String> packageNames =
5112                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5113            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5114                final String packageName = changedPackages.get(i);
5115                if (packageName != null) {
5116                    packageNames.add(packageName);
5117                }
5118            }
5119            return packageNames.isEmpty()
5120                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5121        }
5122    }
5123
5124    @Override
5125    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5126        // allow instant applications
5127        ArrayList<FeatureInfo> res;
5128        synchronized (mAvailableFeatures) {
5129            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5130            res.addAll(mAvailableFeatures.values());
5131        }
5132        final FeatureInfo fi = new FeatureInfo();
5133        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5134                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5135        res.add(fi);
5136
5137        return new ParceledListSlice<>(res);
5138    }
5139
5140    @Override
5141    public boolean hasSystemFeature(String name, int version) {
5142        // allow instant applications
5143        synchronized (mAvailableFeatures) {
5144            final FeatureInfo feat = mAvailableFeatures.get(name);
5145            if (feat == null) {
5146                return false;
5147            } else {
5148                return feat.version >= version;
5149            }
5150        }
5151    }
5152
5153    @Override
5154    public int checkPermission(String permName, String pkgName, int userId) {
5155        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5156    }
5157
5158    @Override
5159    public int checkUidPermission(String permName, int uid) {
5160        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5161    }
5162
5163    @Override
5164    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5165        if (UserHandle.getCallingUserId() != userId) {
5166            mContext.enforceCallingPermission(
5167                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5168                    "isPermissionRevokedByPolicy for user " + userId);
5169        }
5170
5171        if (checkPermission(permission, packageName, userId)
5172                == PackageManager.PERMISSION_GRANTED) {
5173            return false;
5174        }
5175
5176        final int callingUid = Binder.getCallingUid();
5177        if (getInstantAppPackageName(callingUid) != null) {
5178            if (!isCallerSameApp(packageName, callingUid)) {
5179                return false;
5180            }
5181        } else {
5182            if (isInstantApp(packageName, userId)) {
5183                return false;
5184            }
5185        }
5186
5187        final long identity = Binder.clearCallingIdentity();
5188        try {
5189            final int flags = getPermissionFlags(permission, packageName, userId);
5190            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5191        } finally {
5192            Binder.restoreCallingIdentity(identity);
5193        }
5194    }
5195
5196    @Override
5197    public String getPermissionControllerPackageName() {
5198        synchronized (mPackages) {
5199            return mRequiredInstallerPackage;
5200        }
5201    }
5202
5203    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5204        return mPermissionManager.addDynamicPermission(
5205                info, async, getCallingUid(), new PermissionCallback() {
5206                    @Override
5207                    public void onPermissionChanged() {
5208                        if (!async) {
5209                            mSettings.writeLPr();
5210                        } else {
5211                            scheduleWriteSettingsLocked();
5212                        }
5213                    }
5214                });
5215    }
5216
5217    @Override
5218    public boolean addPermission(PermissionInfo info) {
5219        synchronized (mPackages) {
5220            return addDynamicPermission(info, false);
5221        }
5222    }
5223
5224    @Override
5225    public boolean addPermissionAsync(PermissionInfo info) {
5226        synchronized (mPackages) {
5227            return addDynamicPermission(info, true);
5228        }
5229    }
5230
5231    @Override
5232    public void removePermission(String permName) {
5233        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5234    }
5235
5236    @Override
5237    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5238        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5239                getCallingUid(), userId, mPermissionCallback);
5240    }
5241
5242    @Override
5243    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5244        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5245                getCallingUid(), userId, mPermissionCallback);
5246    }
5247
5248    @Override
5249    public void resetRuntimePermissions() {
5250        mContext.enforceCallingOrSelfPermission(
5251                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5252                "revokeRuntimePermission");
5253
5254        int callingUid = Binder.getCallingUid();
5255        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5256            mContext.enforceCallingOrSelfPermission(
5257                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5258                    "resetRuntimePermissions");
5259        }
5260
5261        synchronized (mPackages) {
5262            mPermissionManager.updateAllPermissions(
5263                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5264                    mPermissionCallback);
5265            for (int userId : UserManagerService.getInstance().getUserIds()) {
5266                final int packageCount = mPackages.size();
5267                for (int i = 0; i < packageCount; i++) {
5268                    PackageParser.Package pkg = mPackages.valueAt(i);
5269                    if (!(pkg.mExtras instanceof PackageSetting)) {
5270                        continue;
5271                    }
5272                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5273                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5274                }
5275            }
5276        }
5277    }
5278
5279    @Override
5280    public int getPermissionFlags(String permName, String packageName, int userId) {
5281        return mPermissionManager.getPermissionFlags(
5282                permName, packageName, getCallingUid(), userId);
5283    }
5284
5285    @Override
5286    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5287            int flagValues, int userId) {
5288        mPermissionManager.updatePermissionFlags(
5289                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5290                mPermissionCallback);
5291    }
5292
5293    /**
5294     * Update the permission flags for all packages and runtime permissions of a user in order
5295     * to allow device or profile owner to remove POLICY_FIXED.
5296     */
5297    @Override
5298    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5299        synchronized (mPackages) {
5300            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5301                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5302                    mPermissionCallback);
5303            if (changed) {
5304                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5305            }
5306        }
5307    }
5308
5309    @Override
5310    public boolean shouldShowRequestPermissionRationale(String permissionName,
5311            String packageName, int userId) {
5312        if (UserHandle.getCallingUserId() != userId) {
5313            mContext.enforceCallingPermission(
5314                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5315                    "canShowRequestPermissionRationale for user " + userId);
5316        }
5317
5318        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5319        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5320            return false;
5321        }
5322
5323        if (checkPermission(permissionName, packageName, userId)
5324                == PackageManager.PERMISSION_GRANTED) {
5325            return false;
5326        }
5327
5328        final int flags;
5329
5330        final long identity = Binder.clearCallingIdentity();
5331        try {
5332            flags = getPermissionFlags(permissionName,
5333                    packageName, userId);
5334        } finally {
5335            Binder.restoreCallingIdentity(identity);
5336        }
5337
5338        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5339                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5340                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5341
5342        if ((flags & fixedFlags) != 0) {
5343            return false;
5344        }
5345
5346        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5347    }
5348
5349    @Override
5350    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5351        mContext.enforceCallingOrSelfPermission(
5352                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5353                "addOnPermissionsChangeListener");
5354
5355        synchronized (mPackages) {
5356            mOnPermissionChangeListeners.addListenerLocked(listener);
5357        }
5358    }
5359
5360    @Override
5361    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5362        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5363            throw new SecurityException("Instant applications don't have access to this method");
5364        }
5365        synchronized (mPackages) {
5366            mOnPermissionChangeListeners.removeListenerLocked(listener);
5367        }
5368    }
5369
5370    @Override
5371    public boolean isProtectedBroadcast(String actionName) {
5372        // allow instant applications
5373        synchronized (mProtectedBroadcasts) {
5374            if (mProtectedBroadcasts.contains(actionName)) {
5375                return true;
5376            } else if (actionName != null) {
5377                // TODO: remove these terrible hacks
5378                if (actionName.startsWith("android.net.netmon.lingerExpired")
5379                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5380                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5381                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5382                    return true;
5383                }
5384            }
5385        }
5386        return false;
5387    }
5388
5389    @Override
5390    public int checkSignatures(String pkg1, String pkg2) {
5391        synchronized (mPackages) {
5392            final PackageParser.Package p1 = mPackages.get(pkg1);
5393            final PackageParser.Package p2 = mPackages.get(pkg2);
5394            if (p1 == null || p1.mExtras == null
5395                    || p2 == null || p2.mExtras == null) {
5396                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5397            }
5398            final int callingUid = Binder.getCallingUid();
5399            final int callingUserId = UserHandle.getUserId(callingUid);
5400            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5401            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5402            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5403                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5404                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5405            }
5406            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5407        }
5408    }
5409
5410    @Override
5411    public int checkUidSignatures(int uid1, int uid2) {
5412        final int callingUid = Binder.getCallingUid();
5413        final int callingUserId = UserHandle.getUserId(callingUid);
5414        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5415        // Map to base uids.
5416        uid1 = UserHandle.getAppId(uid1);
5417        uid2 = UserHandle.getAppId(uid2);
5418        // reader
5419        synchronized (mPackages) {
5420            Signature[] s1;
5421            Signature[] s2;
5422            Object obj = mSettings.getUserIdLPr(uid1);
5423            if (obj != null) {
5424                if (obj instanceof SharedUserSetting) {
5425                    if (isCallerInstantApp) {
5426                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5427                    }
5428                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5429                } else if (obj instanceof PackageSetting) {
5430                    final PackageSetting ps = (PackageSetting) obj;
5431                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5432                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5433                    }
5434                    s1 = ps.signatures.mSigningDetails.signatures;
5435                } else {
5436                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5437                }
5438            } else {
5439                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5440            }
5441            obj = mSettings.getUserIdLPr(uid2);
5442            if (obj != null) {
5443                if (obj instanceof SharedUserSetting) {
5444                    if (isCallerInstantApp) {
5445                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5446                    }
5447                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5448                } else if (obj instanceof PackageSetting) {
5449                    final PackageSetting ps = (PackageSetting) obj;
5450                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5451                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5452                    }
5453                    s2 = ps.signatures.mSigningDetails.signatures;
5454                } else {
5455                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5456                }
5457            } else {
5458                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5459            }
5460            return compareSignatures(s1, s2);
5461        }
5462    }
5463
5464    @Override
5465    public boolean hasSigningCertificate(
5466            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5467
5468        synchronized (mPackages) {
5469            final PackageParser.Package p = mPackages.get(packageName);
5470            if (p == null || p.mExtras == null) {
5471                return false;
5472            }
5473            final int callingUid = Binder.getCallingUid();
5474            final int callingUserId = UserHandle.getUserId(callingUid);
5475            final PackageSetting ps = (PackageSetting) p.mExtras;
5476            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5477                return false;
5478            }
5479            switch (type) {
5480                case CERT_INPUT_RAW_X509:
5481                    return signingDetailsHasCertificate(certificate, p.mSigningDetails);
5482                case CERT_INPUT_SHA256:
5483                    return signingDetailsHasSha256Certificate(certificate, p.mSigningDetails);
5484                default:
5485                    return false;
5486            }
5487        }
5488    }
5489
5490    @Override
5491    public boolean hasUidSigningCertificate(
5492            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5493        final int callingUid = Binder.getCallingUid();
5494        final int callingUserId = UserHandle.getUserId(callingUid);
5495        // Map to base uids.
5496        uid = UserHandle.getAppId(uid);
5497        // reader
5498        synchronized (mPackages) {
5499            final PackageParser.SigningDetails signingDetails;
5500            final Object obj = mSettings.getUserIdLPr(uid);
5501            if (obj != null) {
5502                if (obj instanceof SharedUserSetting) {
5503                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5504                    if (isCallerInstantApp) {
5505                        return false;
5506                    }
5507                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5508                } else if (obj instanceof PackageSetting) {
5509                    final PackageSetting ps = (PackageSetting) obj;
5510                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5511                        return false;
5512                    }
5513                    signingDetails = ps.signatures.mSigningDetails;
5514                } else {
5515                    return false;
5516                }
5517            } else {
5518                return false;
5519            }
5520            switch (type) {
5521                case CERT_INPUT_RAW_X509:
5522                    return signingDetailsHasCertificate(certificate, signingDetails);
5523                case CERT_INPUT_SHA256:
5524                    return signingDetailsHasSha256Certificate(certificate, signingDetails);
5525                default:
5526                    return false;
5527            }
5528        }
5529    }
5530
5531    /**
5532     * This method should typically only be used when granting or revoking
5533     * permissions, since the app may immediately restart after this call.
5534     * <p>
5535     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5536     * guard your work against the app being relaunched.
5537     */
5538    private void killUid(int appId, int userId, String reason) {
5539        final long identity = Binder.clearCallingIdentity();
5540        try {
5541            IActivityManager am = ActivityManager.getService();
5542            if (am != null) {
5543                try {
5544                    am.killUid(appId, userId, reason);
5545                } catch (RemoteException e) {
5546                    /* ignore - same process */
5547                }
5548            }
5549        } finally {
5550            Binder.restoreCallingIdentity(identity);
5551        }
5552    }
5553
5554    /**
5555     * If the database version for this type of package (internal storage or
5556     * external storage) is less than the version where package signatures
5557     * were updated, return true.
5558     */
5559    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5560        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5561        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5562    }
5563
5564    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5565        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5566        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5567    }
5568
5569    @Override
5570    public List<String> getAllPackages() {
5571        final int callingUid = Binder.getCallingUid();
5572        final int callingUserId = UserHandle.getUserId(callingUid);
5573        synchronized (mPackages) {
5574            if (canViewInstantApps(callingUid, callingUserId)) {
5575                return new ArrayList<String>(mPackages.keySet());
5576            }
5577            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5578            final List<String> result = new ArrayList<>();
5579            if (instantAppPkgName != null) {
5580                // caller is an instant application; filter unexposed applications
5581                for (PackageParser.Package pkg : mPackages.values()) {
5582                    if (!pkg.visibleToInstantApps) {
5583                        continue;
5584                    }
5585                    result.add(pkg.packageName);
5586                }
5587            } else {
5588                // caller is a normal application; filter instant applications
5589                for (PackageParser.Package pkg : mPackages.values()) {
5590                    final PackageSetting ps =
5591                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5592                    if (ps != null
5593                            && ps.getInstantApp(callingUserId)
5594                            && !mInstantAppRegistry.isInstantAccessGranted(
5595                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5596                        continue;
5597                    }
5598                    result.add(pkg.packageName);
5599                }
5600            }
5601            return result;
5602        }
5603    }
5604
5605    @Override
5606    public String[] getPackagesForUid(int uid) {
5607        final int callingUid = Binder.getCallingUid();
5608        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5609        final int userId = UserHandle.getUserId(uid);
5610        uid = UserHandle.getAppId(uid);
5611        // reader
5612        synchronized (mPackages) {
5613            Object obj = mSettings.getUserIdLPr(uid);
5614            if (obj instanceof SharedUserSetting) {
5615                if (isCallerInstantApp) {
5616                    return null;
5617                }
5618                final SharedUserSetting sus = (SharedUserSetting) obj;
5619                final int N = sus.packages.size();
5620                String[] res = new String[N];
5621                final Iterator<PackageSetting> it = sus.packages.iterator();
5622                int i = 0;
5623                while (it.hasNext()) {
5624                    PackageSetting ps = it.next();
5625                    if (ps.getInstalled(userId)) {
5626                        res[i++] = ps.name;
5627                    } else {
5628                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5629                    }
5630                }
5631                return res;
5632            } else if (obj instanceof PackageSetting) {
5633                final PackageSetting ps = (PackageSetting) obj;
5634                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5635                    return new String[]{ps.name};
5636                }
5637            }
5638        }
5639        return null;
5640    }
5641
5642    @Override
5643    public String getNameForUid(int uid) {
5644        final int callingUid = Binder.getCallingUid();
5645        if (getInstantAppPackageName(callingUid) != null) {
5646            return null;
5647        }
5648        synchronized (mPackages) {
5649            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5650            if (obj instanceof SharedUserSetting) {
5651                final SharedUserSetting sus = (SharedUserSetting) obj;
5652                return sus.name + ":" + sus.userId;
5653            } else if (obj instanceof PackageSetting) {
5654                final PackageSetting ps = (PackageSetting) obj;
5655                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5656                    return null;
5657                }
5658                return ps.name;
5659            }
5660            return null;
5661        }
5662    }
5663
5664    @Override
5665    public String[] getNamesForUids(int[] uids) {
5666        if (uids == null || uids.length == 0) {
5667            return null;
5668        }
5669        final int callingUid = Binder.getCallingUid();
5670        if (getInstantAppPackageName(callingUid) != null) {
5671            return null;
5672        }
5673        final String[] names = new String[uids.length];
5674        synchronized (mPackages) {
5675            for (int i = uids.length - 1; i >= 0; i--) {
5676                final int uid = uids[i];
5677                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5678                if (obj instanceof SharedUserSetting) {
5679                    final SharedUserSetting sus = (SharedUserSetting) obj;
5680                    names[i] = "shared:" + sus.name;
5681                } else if (obj instanceof PackageSetting) {
5682                    final PackageSetting ps = (PackageSetting) obj;
5683                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5684                        names[i] = null;
5685                    } else {
5686                        names[i] = ps.name;
5687                    }
5688                } else {
5689                    names[i] = null;
5690                }
5691            }
5692        }
5693        return names;
5694    }
5695
5696    @Override
5697    public int getUidForSharedUser(String sharedUserName) {
5698        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5699            return -1;
5700        }
5701        if (sharedUserName == null) {
5702            return -1;
5703        }
5704        // reader
5705        synchronized (mPackages) {
5706            SharedUserSetting suid;
5707            try {
5708                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5709                if (suid != null) {
5710                    return suid.userId;
5711                }
5712            } catch (PackageManagerException ignore) {
5713                // can't happen, but, still need to catch it
5714            }
5715            return -1;
5716        }
5717    }
5718
5719    @Override
5720    public int getFlagsForUid(int uid) {
5721        final int callingUid = Binder.getCallingUid();
5722        if (getInstantAppPackageName(callingUid) != null) {
5723            return 0;
5724        }
5725        synchronized (mPackages) {
5726            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5727            if (obj instanceof SharedUserSetting) {
5728                final SharedUserSetting sus = (SharedUserSetting) obj;
5729                return sus.pkgFlags;
5730            } else if (obj instanceof PackageSetting) {
5731                final PackageSetting ps = (PackageSetting) obj;
5732                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5733                    return 0;
5734                }
5735                return ps.pkgFlags;
5736            }
5737        }
5738        return 0;
5739    }
5740
5741    @Override
5742    public int getPrivateFlagsForUid(int uid) {
5743        final int callingUid = Binder.getCallingUid();
5744        if (getInstantAppPackageName(callingUid) != null) {
5745            return 0;
5746        }
5747        synchronized (mPackages) {
5748            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5749            if (obj instanceof SharedUserSetting) {
5750                final SharedUserSetting sus = (SharedUserSetting) obj;
5751                return sus.pkgPrivateFlags;
5752            } else if (obj instanceof PackageSetting) {
5753                final PackageSetting ps = (PackageSetting) obj;
5754                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5755                    return 0;
5756                }
5757                return ps.pkgPrivateFlags;
5758            }
5759        }
5760        return 0;
5761    }
5762
5763    @Override
5764    public boolean isUidPrivileged(int uid) {
5765        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5766            return false;
5767        }
5768        uid = UserHandle.getAppId(uid);
5769        // reader
5770        synchronized (mPackages) {
5771            Object obj = mSettings.getUserIdLPr(uid);
5772            if (obj instanceof SharedUserSetting) {
5773                final SharedUserSetting sus = (SharedUserSetting) obj;
5774                final Iterator<PackageSetting> it = sus.packages.iterator();
5775                while (it.hasNext()) {
5776                    if (it.next().isPrivileged()) {
5777                        return true;
5778                    }
5779                }
5780            } else if (obj instanceof PackageSetting) {
5781                final PackageSetting ps = (PackageSetting) obj;
5782                return ps.isPrivileged();
5783            }
5784        }
5785        return false;
5786    }
5787
5788    @Override
5789    public String[] getAppOpPermissionPackages(String permName) {
5790        return mPermissionManager.getAppOpPermissionPackages(permName);
5791    }
5792
5793    @Override
5794    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5795            int flags, int userId) {
5796        return resolveIntentInternal(
5797                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5798    }
5799
5800    /**
5801     * Normally instant apps can only be resolved when they're visible to the caller.
5802     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5803     * since we need to allow the system to start any installed application.
5804     */
5805    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5806            int flags, int userId, boolean resolveForStart) {
5807        try {
5808            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5809
5810            if (!sUserManager.exists(userId)) return null;
5811            final int callingUid = Binder.getCallingUid();
5812            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5813            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5814                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5815
5816            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5817            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5818                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5819            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5820
5821            final ResolveInfo bestChoice =
5822                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5823            return bestChoice;
5824        } finally {
5825            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5826        }
5827    }
5828
5829    @Override
5830    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5831        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5832            throw new SecurityException(
5833                    "findPersistentPreferredActivity can only be run by the system");
5834        }
5835        if (!sUserManager.exists(userId)) {
5836            return null;
5837        }
5838        final int callingUid = Binder.getCallingUid();
5839        intent = updateIntentForResolve(intent);
5840        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5841        final int flags = updateFlagsForResolve(
5842                0, userId, intent, callingUid, false /*includeInstantApps*/);
5843        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5844                userId);
5845        synchronized (mPackages) {
5846            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5847                    userId);
5848        }
5849    }
5850
5851    @Override
5852    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5853            IntentFilter filter, int match, ComponentName activity) {
5854        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5855            return;
5856        }
5857        final int userId = UserHandle.getCallingUserId();
5858        if (DEBUG_PREFERRED) {
5859            Log.v(TAG, "setLastChosenActivity intent=" + intent
5860                + " resolvedType=" + resolvedType
5861                + " flags=" + flags
5862                + " filter=" + filter
5863                + " match=" + match
5864                + " activity=" + activity);
5865            filter.dump(new PrintStreamPrinter(System.out), "    ");
5866        }
5867        intent.setComponent(null);
5868        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5869                userId);
5870        // Find any earlier preferred or last chosen entries and nuke them
5871        findPreferredActivity(intent, resolvedType,
5872                flags, query, 0, false, true, false, userId);
5873        // Add the new activity as the last chosen for this filter
5874        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5875                "Setting last chosen");
5876    }
5877
5878    @Override
5879    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5880        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5881            return null;
5882        }
5883        final int userId = UserHandle.getCallingUserId();
5884        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5885        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5886                userId);
5887        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5888                false, false, false, userId);
5889    }
5890
5891    /**
5892     * Returns whether or not instant apps have been disabled remotely.
5893     */
5894    private boolean isEphemeralDisabled() {
5895        return mEphemeralAppsDisabled;
5896    }
5897
5898    private boolean isInstantAppAllowed(
5899            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5900            boolean skipPackageCheck) {
5901        if (mInstantAppResolverConnection == null) {
5902            return false;
5903        }
5904        if (mInstantAppInstallerActivity == null) {
5905            return false;
5906        }
5907        if (intent.getComponent() != null) {
5908            return false;
5909        }
5910        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5911            return false;
5912        }
5913        if (!skipPackageCheck && intent.getPackage() != null) {
5914            return false;
5915        }
5916        final boolean isWebUri = hasWebURI(intent);
5917        if (!isWebUri || intent.getData().getHost() == null) {
5918            return false;
5919        }
5920        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5921        // Or if there's already an ephemeral app installed that handles the action
5922        synchronized (mPackages) {
5923            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5924            for (int n = 0; n < count; n++) {
5925                final ResolveInfo info = resolvedActivities.get(n);
5926                final String packageName = info.activityInfo.packageName;
5927                final PackageSetting ps = mSettings.mPackages.get(packageName);
5928                if (ps != null) {
5929                    // only check domain verification status if the app is not a browser
5930                    if (!info.handleAllWebDataURI) {
5931                        // Try to get the status from User settings first
5932                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5933                        final int status = (int) (packedStatus >> 32);
5934                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5935                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5936                            if (DEBUG_EPHEMERAL) {
5937                                Slog.v(TAG, "DENY instant app;"
5938                                    + " pkg: " + packageName + ", status: " + status);
5939                            }
5940                            return false;
5941                        }
5942                    }
5943                    if (ps.getInstantApp(userId)) {
5944                        if (DEBUG_EPHEMERAL) {
5945                            Slog.v(TAG, "DENY instant app installed;"
5946                                    + " pkg: " + packageName);
5947                        }
5948                        return false;
5949                    }
5950                }
5951            }
5952        }
5953        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5954        return true;
5955    }
5956
5957    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5958            Intent origIntent, String resolvedType, String callingPackage,
5959            Bundle verificationBundle, int userId) {
5960        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5961                new InstantAppRequest(responseObj, origIntent, resolvedType,
5962                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5963        mHandler.sendMessage(msg);
5964    }
5965
5966    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5967            int flags, List<ResolveInfo> query, int userId) {
5968        if (query != null) {
5969            final int N = query.size();
5970            if (N == 1) {
5971                return query.get(0);
5972            } else if (N > 1) {
5973                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5974                // If there is more than one activity with the same priority,
5975                // then let the user decide between them.
5976                ResolveInfo r0 = query.get(0);
5977                ResolveInfo r1 = query.get(1);
5978                if (DEBUG_INTENT_MATCHING || debug) {
5979                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5980                            + r1.activityInfo.name + "=" + r1.priority);
5981                }
5982                // If the first activity has a higher priority, or a different
5983                // default, then it is always desirable to pick it.
5984                if (r0.priority != r1.priority
5985                        || r0.preferredOrder != r1.preferredOrder
5986                        || r0.isDefault != r1.isDefault) {
5987                    return query.get(0);
5988                }
5989                // If we have saved a preference for a preferred activity for
5990                // this Intent, use that.
5991                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5992                        flags, query, r0.priority, true, false, debug, userId);
5993                if (ri != null) {
5994                    return ri;
5995                }
5996                // If we have an ephemeral app, use it
5997                for (int i = 0; i < N; i++) {
5998                    ri = query.get(i);
5999                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6000                        final String packageName = ri.activityInfo.packageName;
6001                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6002                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6003                        final int status = (int)(packedStatus >> 32);
6004                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6005                            return ri;
6006                        }
6007                    }
6008                }
6009                ri = new ResolveInfo(mResolveInfo);
6010                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6011                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6012                // If all of the options come from the same package, show the application's
6013                // label and icon instead of the generic resolver's.
6014                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6015                // and then throw away the ResolveInfo itself, meaning that the caller loses
6016                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6017                // a fallback for this case; we only set the target package's resources on
6018                // the ResolveInfo, not the ActivityInfo.
6019                final String intentPackage = intent.getPackage();
6020                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6021                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6022                    ri.resolvePackageName = intentPackage;
6023                    if (userNeedsBadging(userId)) {
6024                        ri.noResourceId = true;
6025                    } else {
6026                        ri.icon = appi.icon;
6027                    }
6028                    ri.iconResourceId = appi.icon;
6029                    ri.labelRes = appi.labelRes;
6030                }
6031                ri.activityInfo.applicationInfo = new ApplicationInfo(
6032                        ri.activityInfo.applicationInfo);
6033                if (userId != 0) {
6034                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6035                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6036                }
6037                // Make sure that the resolver is displayable in car mode
6038                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6039                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6040                return ri;
6041            }
6042        }
6043        return null;
6044    }
6045
6046    /**
6047     * Return true if the given list is not empty and all of its contents have
6048     * an activityInfo with the given package name.
6049     */
6050    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6051        if (ArrayUtils.isEmpty(list)) {
6052            return false;
6053        }
6054        for (int i = 0, N = list.size(); i < N; i++) {
6055            final ResolveInfo ri = list.get(i);
6056            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6057            if (ai == null || !packageName.equals(ai.packageName)) {
6058                return false;
6059            }
6060        }
6061        return true;
6062    }
6063
6064    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6065            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6066        final int N = query.size();
6067        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6068                .get(userId);
6069        // Get the list of persistent preferred activities that handle the intent
6070        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6071        List<PersistentPreferredActivity> pprefs = ppir != null
6072                ? ppir.queryIntent(intent, resolvedType,
6073                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6074                        userId)
6075                : null;
6076        if (pprefs != null && pprefs.size() > 0) {
6077            final int M = pprefs.size();
6078            for (int i=0; i<M; i++) {
6079                final PersistentPreferredActivity ppa = pprefs.get(i);
6080                if (DEBUG_PREFERRED || debug) {
6081                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6082                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6083                            + "\n  component=" + ppa.mComponent);
6084                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6085                }
6086                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6087                        flags | MATCH_DISABLED_COMPONENTS, userId);
6088                if (DEBUG_PREFERRED || debug) {
6089                    Slog.v(TAG, "Found persistent preferred activity:");
6090                    if (ai != null) {
6091                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6092                    } else {
6093                        Slog.v(TAG, "  null");
6094                    }
6095                }
6096                if (ai == null) {
6097                    // This previously registered persistent preferred activity
6098                    // component is no longer known. Ignore it and do NOT remove it.
6099                    continue;
6100                }
6101                for (int j=0; j<N; j++) {
6102                    final ResolveInfo ri = query.get(j);
6103                    if (!ri.activityInfo.applicationInfo.packageName
6104                            .equals(ai.applicationInfo.packageName)) {
6105                        continue;
6106                    }
6107                    if (!ri.activityInfo.name.equals(ai.name)) {
6108                        continue;
6109                    }
6110                    //  Found a persistent preference that can handle the intent.
6111                    if (DEBUG_PREFERRED || debug) {
6112                        Slog.v(TAG, "Returning persistent preferred activity: " +
6113                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6114                    }
6115                    return ri;
6116                }
6117            }
6118        }
6119        return null;
6120    }
6121
6122    // TODO: handle preferred activities missing while user has amnesia
6123    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6124            List<ResolveInfo> query, int priority, boolean always,
6125            boolean removeMatches, boolean debug, int userId) {
6126        if (!sUserManager.exists(userId)) return null;
6127        final int callingUid = Binder.getCallingUid();
6128        flags = updateFlagsForResolve(
6129                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6130        intent = updateIntentForResolve(intent);
6131        // writer
6132        synchronized (mPackages) {
6133            // Try to find a matching persistent preferred activity.
6134            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6135                    debug, userId);
6136
6137            // If a persistent preferred activity matched, use it.
6138            if (pri != null) {
6139                return pri;
6140            }
6141
6142            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6143            // Get the list of preferred activities that handle the intent
6144            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6145            List<PreferredActivity> prefs = pir != null
6146                    ? pir.queryIntent(intent, resolvedType,
6147                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6148                            userId)
6149                    : null;
6150            if (prefs != null && prefs.size() > 0) {
6151                boolean changed = false;
6152                try {
6153                    // First figure out how good the original match set is.
6154                    // We will only allow preferred activities that came
6155                    // from the same match quality.
6156                    int match = 0;
6157
6158                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6159
6160                    final int N = query.size();
6161                    for (int j=0; j<N; j++) {
6162                        final ResolveInfo ri = query.get(j);
6163                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6164                                + ": 0x" + Integer.toHexString(match));
6165                        if (ri.match > match) {
6166                            match = ri.match;
6167                        }
6168                    }
6169
6170                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6171                            + Integer.toHexString(match));
6172
6173                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6174                    final int M = prefs.size();
6175                    for (int i=0; i<M; i++) {
6176                        final PreferredActivity pa = prefs.get(i);
6177                        if (DEBUG_PREFERRED || debug) {
6178                            Slog.v(TAG, "Checking PreferredActivity ds="
6179                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6180                                    + "\n  component=" + pa.mPref.mComponent);
6181                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6182                        }
6183                        if (pa.mPref.mMatch != match) {
6184                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6185                                    + Integer.toHexString(pa.mPref.mMatch));
6186                            continue;
6187                        }
6188                        // If it's not an "always" type preferred activity and that's what we're
6189                        // looking for, skip it.
6190                        if (always && !pa.mPref.mAlways) {
6191                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6192                            continue;
6193                        }
6194                        final ActivityInfo ai = getActivityInfo(
6195                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6196                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6197                                userId);
6198                        if (DEBUG_PREFERRED || debug) {
6199                            Slog.v(TAG, "Found preferred activity:");
6200                            if (ai != null) {
6201                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6202                            } else {
6203                                Slog.v(TAG, "  null");
6204                            }
6205                        }
6206                        if (ai == null) {
6207                            // This previously registered preferred activity
6208                            // component is no longer known.  Most likely an update
6209                            // to the app was installed and in the new version this
6210                            // component no longer exists.  Clean it up by removing
6211                            // it from the preferred activities list, and skip it.
6212                            Slog.w(TAG, "Removing dangling preferred activity: "
6213                                    + pa.mPref.mComponent);
6214                            pir.removeFilter(pa);
6215                            changed = true;
6216                            continue;
6217                        }
6218                        for (int j=0; j<N; j++) {
6219                            final ResolveInfo ri = query.get(j);
6220                            if (!ri.activityInfo.applicationInfo.packageName
6221                                    .equals(ai.applicationInfo.packageName)) {
6222                                continue;
6223                            }
6224                            if (!ri.activityInfo.name.equals(ai.name)) {
6225                                continue;
6226                            }
6227
6228                            if (removeMatches) {
6229                                pir.removeFilter(pa);
6230                                changed = true;
6231                                if (DEBUG_PREFERRED) {
6232                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6233                                }
6234                                break;
6235                            }
6236
6237                            // Okay we found a previously set preferred or last chosen app.
6238                            // If the result set is different from when this
6239                            // was created, and is not a subset of the preferred set, we need to
6240                            // clear it and re-ask the user their preference, if we're looking for
6241                            // an "always" type entry.
6242                            if (always && !pa.mPref.sameSet(query)) {
6243                                if (pa.mPref.isSuperset(query)) {
6244                                    // some components of the set are no longer present in
6245                                    // the query, but the preferred activity can still be reused
6246                                    if (DEBUG_PREFERRED) {
6247                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6248                                                + " still valid as only non-preferred components"
6249                                                + " were removed for " + intent + " type "
6250                                                + resolvedType);
6251                                    }
6252                                    // remove obsolete components and re-add the up-to-date filter
6253                                    PreferredActivity freshPa = new PreferredActivity(pa,
6254                                            pa.mPref.mMatch,
6255                                            pa.mPref.discardObsoleteComponents(query),
6256                                            pa.mPref.mComponent,
6257                                            pa.mPref.mAlways);
6258                                    pir.removeFilter(pa);
6259                                    pir.addFilter(freshPa);
6260                                    changed = true;
6261                                } else {
6262                                    Slog.i(TAG,
6263                                            "Result set changed, dropping preferred activity for "
6264                                                    + intent + " type " + resolvedType);
6265                                    if (DEBUG_PREFERRED) {
6266                                        Slog.v(TAG, "Removing preferred activity since set changed "
6267                                                + pa.mPref.mComponent);
6268                                    }
6269                                    pir.removeFilter(pa);
6270                                    // Re-add the filter as a "last chosen" entry (!always)
6271                                    PreferredActivity lastChosen = new PreferredActivity(
6272                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6273                                    pir.addFilter(lastChosen);
6274                                    changed = true;
6275                                    return null;
6276                                }
6277                            }
6278
6279                            // Yay! Either the set matched or we're looking for the last chosen
6280                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6281                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6282                            return ri;
6283                        }
6284                    }
6285                } finally {
6286                    if (changed) {
6287                        if (DEBUG_PREFERRED) {
6288                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6289                        }
6290                        scheduleWritePackageRestrictionsLocked(userId);
6291                    }
6292                }
6293            }
6294        }
6295        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6296        return null;
6297    }
6298
6299    /*
6300     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6301     */
6302    @Override
6303    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6304            int targetUserId) {
6305        mContext.enforceCallingOrSelfPermission(
6306                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6307        List<CrossProfileIntentFilter> matches =
6308                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6309        if (matches != null) {
6310            int size = matches.size();
6311            for (int i = 0; i < size; i++) {
6312                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6313            }
6314        }
6315        if (hasWebURI(intent)) {
6316            // cross-profile app linking works only towards the parent.
6317            final int callingUid = Binder.getCallingUid();
6318            final UserInfo parent = getProfileParent(sourceUserId);
6319            synchronized(mPackages) {
6320                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6321                        false /*includeInstantApps*/);
6322                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6323                        intent, resolvedType, flags, sourceUserId, parent.id);
6324                return xpDomainInfo != null;
6325            }
6326        }
6327        return false;
6328    }
6329
6330    private UserInfo getProfileParent(int userId) {
6331        final long identity = Binder.clearCallingIdentity();
6332        try {
6333            return sUserManager.getProfileParent(userId);
6334        } finally {
6335            Binder.restoreCallingIdentity(identity);
6336        }
6337    }
6338
6339    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6340            String resolvedType, int userId) {
6341        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6342        if (resolver != null) {
6343            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6344        }
6345        return null;
6346    }
6347
6348    @Override
6349    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6350            String resolvedType, int flags, int userId) {
6351        try {
6352            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6353
6354            return new ParceledListSlice<>(
6355                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6356        } finally {
6357            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6358        }
6359    }
6360
6361    /**
6362     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6363     * instant, returns {@code null}.
6364     */
6365    private String getInstantAppPackageName(int callingUid) {
6366        synchronized (mPackages) {
6367            // If the caller is an isolated app use the owner's uid for the lookup.
6368            if (Process.isIsolated(callingUid)) {
6369                callingUid = mIsolatedOwners.get(callingUid);
6370            }
6371            final int appId = UserHandle.getAppId(callingUid);
6372            final Object obj = mSettings.getUserIdLPr(appId);
6373            if (obj instanceof PackageSetting) {
6374                final PackageSetting ps = (PackageSetting) obj;
6375                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6376                return isInstantApp ? ps.pkg.packageName : null;
6377            }
6378        }
6379        return null;
6380    }
6381
6382    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6383            String resolvedType, int flags, int userId) {
6384        return queryIntentActivitiesInternal(
6385                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6386                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6387    }
6388
6389    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6390            String resolvedType, int flags, int filterCallingUid, int userId,
6391            boolean resolveForStart, boolean allowDynamicSplits) {
6392        if (!sUserManager.exists(userId)) return Collections.emptyList();
6393        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6394        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6395                false /* requireFullPermission */, false /* checkShell */,
6396                "query intent activities");
6397        final String pkgName = intent.getPackage();
6398        ComponentName comp = intent.getComponent();
6399        if (comp == null) {
6400            if (intent.getSelector() != null) {
6401                intent = intent.getSelector();
6402                comp = intent.getComponent();
6403            }
6404        }
6405
6406        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6407                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6408        if (comp != null) {
6409            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6410            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6411            if (ai != null) {
6412                // When specifying an explicit component, we prevent the activity from being
6413                // used when either 1) the calling package is normal and the activity is within
6414                // an ephemeral application or 2) the calling package is ephemeral and the
6415                // activity is not visible to ephemeral applications.
6416                final boolean matchInstantApp =
6417                        (flags & PackageManager.MATCH_INSTANT) != 0;
6418                final boolean matchVisibleToInstantAppOnly =
6419                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6420                final boolean matchExplicitlyVisibleOnly =
6421                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6422                final boolean isCallerInstantApp =
6423                        instantAppPkgName != null;
6424                final boolean isTargetSameInstantApp =
6425                        comp.getPackageName().equals(instantAppPkgName);
6426                final boolean isTargetInstantApp =
6427                        (ai.applicationInfo.privateFlags
6428                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6429                final boolean isTargetVisibleToInstantApp =
6430                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6431                final boolean isTargetExplicitlyVisibleToInstantApp =
6432                        isTargetVisibleToInstantApp
6433                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6434                final boolean isTargetHiddenFromInstantApp =
6435                        !isTargetVisibleToInstantApp
6436                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6437                final boolean blockResolution =
6438                        !isTargetSameInstantApp
6439                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6440                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6441                                        && isTargetHiddenFromInstantApp));
6442                if (!blockResolution) {
6443                    final ResolveInfo ri = new ResolveInfo();
6444                    ri.activityInfo = ai;
6445                    list.add(ri);
6446                }
6447            }
6448            return applyPostResolutionFilter(
6449                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6450        }
6451
6452        // reader
6453        boolean sortResult = false;
6454        boolean addEphemeral = false;
6455        List<ResolveInfo> result;
6456        final boolean ephemeralDisabled = isEphemeralDisabled();
6457        synchronized (mPackages) {
6458            if (pkgName == null) {
6459                List<CrossProfileIntentFilter> matchingFilters =
6460                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6461                // Check for results that need to skip the current profile.
6462                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6463                        resolvedType, flags, userId);
6464                if (xpResolveInfo != null) {
6465                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6466                    xpResult.add(xpResolveInfo);
6467                    return applyPostResolutionFilter(
6468                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6469                            allowDynamicSplits, filterCallingUid, userId);
6470                }
6471
6472                // Check for results in the current profile.
6473                result = filterIfNotSystemUser(mActivities.queryIntent(
6474                        intent, resolvedType, flags, userId), userId);
6475                addEphemeral = !ephemeralDisabled
6476                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6477                // Check for cross profile results.
6478                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6479                xpResolveInfo = queryCrossProfileIntents(
6480                        matchingFilters, intent, resolvedType, flags, userId,
6481                        hasNonNegativePriorityResult);
6482                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6483                    boolean isVisibleToUser = filterIfNotSystemUser(
6484                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6485                    if (isVisibleToUser) {
6486                        result.add(xpResolveInfo);
6487                        sortResult = true;
6488                    }
6489                }
6490                if (hasWebURI(intent)) {
6491                    CrossProfileDomainInfo xpDomainInfo = null;
6492                    final UserInfo parent = getProfileParent(userId);
6493                    if (parent != null) {
6494                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6495                                flags, userId, parent.id);
6496                    }
6497                    if (xpDomainInfo != null) {
6498                        if (xpResolveInfo != null) {
6499                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6500                            // in the result.
6501                            result.remove(xpResolveInfo);
6502                        }
6503                        if (result.size() == 0 && !addEphemeral) {
6504                            // No result in current profile, but found candidate in parent user.
6505                            // And we are not going to add emphemeral app, so we can return the
6506                            // result straight away.
6507                            result.add(xpDomainInfo.resolveInfo);
6508                            return applyPostResolutionFilter(result, instantAppPkgName,
6509                                    allowDynamicSplits, filterCallingUid, userId);
6510                        }
6511                    } else if (result.size() <= 1 && !addEphemeral) {
6512                        // No result in parent user and <= 1 result in current profile, and we
6513                        // are not going to add emphemeral app, so we can return the result without
6514                        // further processing.
6515                        return applyPostResolutionFilter(result, instantAppPkgName,
6516                                allowDynamicSplits, filterCallingUid, userId);
6517                    }
6518                    // We have more than one candidate (combining results from current and parent
6519                    // profile), so we need filtering and sorting.
6520                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6521                            intent, flags, result, xpDomainInfo, userId);
6522                    sortResult = true;
6523                }
6524            } else {
6525                final PackageParser.Package pkg = mPackages.get(pkgName);
6526                result = null;
6527                if (pkg != null) {
6528                    result = filterIfNotSystemUser(
6529                            mActivities.queryIntentForPackage(
6530                                    intent, resolvedType, flags, pkg.activities, userId),
6531                            userId);
6532                }
6533                if (result == null || result.size() == 0) {
6534                    // the caller wants to resolve for a particular package; however, there
6535                    // were no installed results, so, try to find an ephemeral result
6536                    addEphemeral = !ephemeralDisabled
6537                            && isInstantAppAllowed(
6538                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6539                    if (result == null) {
6540                        result = new ArrayList<>();
6541                    }
6542                }
6543            }
6544        }
6545        if (addEphemeral) {
6546            result = maybeAddInstantAppInstaller(
6547                    result, intent, resolvedType, flags, userId, resolveForStart);
6548        }
6549        if (sortResult) {
6550            Collections.sort(result, mResolvePrioritySorter);
6551        }
6552        return applyPostResolutionFilter(
6553                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6554    }
6555
6556    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6557            String resolvedType, int flags, int userId, boolean resolveForStart) {
6558        // first, check to see if we've got an instant app already installed
6559        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6560        ResolveInfo localInstantApp = null;
6561        boolean blockResolution = false;
6562        if (!alreadyResolvedLocally) {
6563            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6564                    flags
6565                        | PackageManager.GET_RESOLVED_FILTER
6566                        | PackageManager.MATCH_INSTANT
6567                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6568                    userId);
6569            for (int i = instantApps.size() - 1; i >= 0; --i) {
6570                final ResolveInfo info = instantApps.get(i);
6571                final String packageName = info.activityInfo.packageName;
6572                final PackageSetting ps = mSettings.mPackages.get(packageName);
6573                if (ps.getInstantApp(userId)) {
6574                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6575                    final int status = (int)(packedStatus >> 32);
6576                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6577                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6578                        // there's a local instant application installed, but, the user has
6579                        // chosen to never use it; skip resolution and don't acknowledge
6580                        // an instant application is even available
6581                        if (DEBUG_EPHEMERAL) {
6582                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6583                        }
6584                        blockResolution = true;
6585                        break;
6586                    } else {
6587                        // we have a locally installed instant application; skip resolution
6588                        // but acknowledge there's an instant application available
6589                        if (DEBUG_EPHEMERAL) {
6590                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6591                        }
6592                        localInstantApp = info;
6593                        break;
6594                    }
6595                }
6596            }
6597        }
6598        // no app installed, let's see if one's available
6599        AuxiliaryResolveInfo auxiliaryResponse = null;
6600        if (!blockResolution) {
6601            if (localInstantApp == null) {
6602                // we don't have an instant app locally, resolve externally
6603                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6604                final InstantAppRequest requestObject = new InstantAppRequest(
6605                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6606                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6607                        resolveForStart);
6608                auxiliaryResponse =
6609                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6610                                mContext, mInstantAppResolverConnection, requestObject);
6611                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6612            } else {
6613                // we have an instant application locally, but, we can't admit that since
6614                // callers shouldn't be able to determine prior browsing. create a dummy
6615                // auxiliary response so the downstream code behaves as if there's an
6616                // instant application available externally. when it comes time to start
6617                // the instant application, we'll do the right thing.
6618                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6619                auxiliaryResponse = new AuxiliaryResolveInfo(
6620                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6621                        ai.versionCode, null /*failureIntent*/);
6622            }
6623        }
6624        if (auxiliaryResponse != null) {
6625            if (DEBUG_EPHEMERAL) {
6626                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6627            }
6628            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6629            final PackageSetting ps =
6630                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6631            if (ps != null) {
6632                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6633                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6634                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6635                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6636                // make sure this resolver is the default
6637                ephemeralInstaller.isDefault = true;
6638                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6639                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6640                // add a non-generic filter
6641                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6642                ephemeralInstaller.filter.addDataPath(
6643                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6644                ephemeralInstaller.isInstantAppAvailable = true;
6645                result.add(ephemeralInstaller);
6646            }
6647        }
6648        return result;
6649    }
6650
6651    private static class CrossProfileDomainInfo {
6652        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6653        ResolveInfo resolveInfo;
6654        /* Best domain verification status of the activities found in the other profile */
6655        int bestDomainVerificationStatus;
6656    }
6657
6658    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6659            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6660        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6661                sourceUserId)) {
6662            return null;
6663        }
6664        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6665                resolvedType, flags, parentUserId);
6666
6667        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6668            return null;
6669        }
6670        CrossProfileDomainInfo result = null;
6671        int size = resultTargetUser.size();
6672        for (int i = 0; i < size; i++) {
6673            ResolveInfo riTargetUser = resultTargetUser.get(i);
6674            // Intent filter verification is only for filters that specify a host. So don't return
6675            // those that handle all web uris.
6676            if (riTargetUser.handleAllWebDataURI) {
6677                continue;
6678            }
6679            String packageName = riTargetUser.activityInfo.packageName;
6680            PackageSetting ps = mSettings.mPackages.get(packageName);
6681            if (ps == null) {
6682                continue;
6683            }
6684            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6685            int status = (int)(verificationState >> 32);
6686            if (result == null) {
6687                result = new CrossProfileDomainInfo();
6688                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6689                        sourceUserId, parentUserId);
6690                result.bestDomainVerificationStatus = status;
6691            } else {
6692                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6693                        result.bestDomainVerificationStatus);
6694            }
6695        }
6696        // Don't consider matches with status NEVER across profiles.
6697        if (result != null && result.bestDomainVerificationStatus
6698                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6699            return null;
6700        }
6701        return result;
6702    }
6703
6704    /**
6705     * Verification statuses are ordered from the worse to the best, except for
6706     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6707     */
6708    private int bestDomainVerificationStatus(int status1, int status2) {
6709        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6710            return status2;
6711        }
6712        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6713            return status1;
6714        }
6715        return (int) MathUtils.max(status1, status2);
6716    }
6717
6718    private boolean isUserEnabled(int userId) {
6719        long callingId = Binder.clearCallingIdentity();
6720        try {
6721            UserInfo userInfo = sUserManager.getUserInfo(userId);
6722            return userInfo != null && userInfo.isEnabled();
6723        } finally {
6724            Binder.restoreCallingIdentity(callingId);
6725        }
6726    }
6727
6728    /**
6729     * Filter out activities with systemUserOnly flag set, when current user is not System.
6730     *
6731     * @return filtered list
6732     */
6733    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6734        if (userId == UserHandle.USER_SYSTEM) {
6735            return resolveInfos;
6736        }
6737        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6738            ResolveInfo info = resolveInfos.get(i);
6739            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6740                resolveInfos.remove(i);
6741            }
6742        }
6743        return resolveInfos;
6744    }
6745
6746    /**
6747     * Filters out ephemeral activities.
6748     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6749     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6750     *
6751     * @param resolveInfos The pre-filtered list of resolved activities
6752     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6753     *          is performed.
6754     * @return A filtered list of resolved activities.
6755     */
6756    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6757            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6758        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6759            final ResolveInfo info = resolveInfos.get(i);
6760            // allow activities that are defined in the provided package
6761            if (allowDynamicSplits
6762                    && info.activityInfo.splitName != null
6763                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6764                            info.activityInfo.splitName)) {
6765                if (mInstantAppInstallerInfo == null) {
6766                    if (DEBUG_INSTALL) {
6767                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6768                    }
6769                    resolveInfos.remove(i);
6770                    continue;
6771                }
6772                // requested activity is defined in a split that hasn't been installed yet.
6773                // add the installer to the resolve list
6774                if (DEBUG_INSTALL) {
6775                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6776                }
6777                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6778                final ComponentName installFailureActivity = findInstallFailureActivity(
6779                        info.activityInfo.packageName,  filterCallingUid, userId);
6780                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6781                        info.activityInfo.packageName, info.activityInfo.splitName,
6782                        installFailureActivity,
6783                        info.activityInfo.applicationInfo.versionCode,
6784                        null /*failureIntent*/);
6785                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6786                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6787                // add a non-generic filter
6788                installerInfo.filter = new IntentFilter();
6789
6790                // This resolve info may appear in the chooser UI, so let us make it
6791                // look as the one it replaces as far as the user is concerned which
6792                // requires loading the correct label and icon for the resolve info.
6793                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6794                installerInfo.labelRes = info.resolveLabelResId();
6795                installerInfo.icon = info.resolveIconResId();
6796
6797                // propagate priority/preferred order/default
6798                installerInfo.priority = info.priority;
6799                installerInfo.preferredOrder = info.preferredOrder;
6800                installerInfo.isDefault = info.isDefault;
6801                resolveInfos.set(i, installerInfo);
6802                continue;
6803            }
6804            // caller is a full app, don't need to apply any other filtering
6805            if (ephemeralPkgName == null) {
6806                continue;
6807            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6808                // caller is same app; don't need to apply any other filtering
6809                continue;
6810            }
6811            // allow activities that have been explicitly exposed to ephemeral apps
6812            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6813            if (!isEphemeralApp
6814                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6815                continue;
6816            }
6817            resolveInfos.remove(i);
6818        }
6819        return resolveInfos;
6820    }
6821
6822    /**
6823     * Returns the activity component that can handle install failures.
6824     * <p>By default, the instant application installer handles failures. However, an
6825     * application may want to handle failures on its own. Applications do this by
6826     * creating an activity with an intent filter that handles the action
6827     * {@link Intent#ACTION_INSTALL_FAILURE}.
6828     */
6829    private @Nullable ComponentName findInstallFailureActivity(
6830            String packageName, int filterCallingUid, int userId) {
6831        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6832        failureActivityIntent.setPackage(packageName);
6833        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6834        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6835                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6836                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6837        final int NR = result.size();
6838        if (NR > 0) {
6839            for (int i = 0; i < NR; i++) {
6840                final ResolveInfo info = result.get(i);
6841                if (info.activityInfo.splitName != null) {
6842                    continue;
6843                }
6844                return new ComponentName(packageName, info.activityInfo.name);
6845            }
6846        }
6847        return null;
6848    }
6849
6850    /**
6851     * @param resolveInfos list of resolve infos in descending priority order
6852     * @return if the list contains a resolve info with non-negative priority
6853     */
6854    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6855        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6856    }
6857
6858    private static boolean hasWebURI(Intent intent) {
6859        if (intent.getData() == null) {
6860            return false;
6861        }
6862        final String scheme = intent.getScheme();
6863        if (TextUtils.isEmpty(scheme)) {
6864            return false;
6865        }
6866        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6867    }
6868
6869    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6870            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6871            int userId) {
6872        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6873
6874        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6875            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6876                    candidates.size());
6877        }
6878
6879        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6880        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6881        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6882        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6883        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6884        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6885
6886        synchronized (mPackages) {
6887            final int count = candidates.size();
6888            // First, try to use linked apps. Partition the candidates into four lists:
6889            // one for the final results, one for the "do not use ever", one for "undefined status"
6890            // and finally one for "browser app type".
6891            for (int n=0; n<count; n++) {
6892                ResolveInfo info = candidates.get(n);
6893                String packageName = info.activityInfo.packageName;
6894                PackageSetting ps = mSettings.mPackages.get(packageName);
6895                if (ps != null) {
6896                    // Add to the special match all list (Browser use case)
6897                    if (info.handleAllWebDataURI) {
6898                        matchAllList.add(info);
6899                        continue;
6900                    }
6901                    // Try to get the status from User settings first
6902                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6903                    int status = (int)(packedStatus >> 32);
6904                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6905                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6906                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6907                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6908                                    + " : linkgen=" + linkGeneration);
6909                        }
6910                        // Use link-enabled generation as preferredOrder, i.e.
6911                        // prefer newly-enabled over earlier-enabled.
6912                        info.preferredOrder = linkGeneration;
6913                        alwaysList.add(info);
6914                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6915                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6916                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6917                        }
6918                        neverList.add(info);
6919                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6920                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6921                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6922                        }
6923                        alwaysAskList.add(info);
6924                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6925                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6926                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6927                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6928                        }
6929                        undefinedList.add(info);
6930                    }
6931                }
6932            }
6933
6934            // We'll want to include browser possibilities in a few cases
6935            boolean includeBrowser = false;
6936
6937            // First try to add the "always" resolution(s) for the current user, if any
6938            if (alwaysList.size() > 0) {
6939                result.addAll(alwaysList);
6940            } else {
6941                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6942                result.addAll(undefinedList);
6943                // Maybe add one for the other profile.
6944                if (xpDomainInfo != null && (
6945                        xpDomainInfo.bestDomainVerificationStatus
6946                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6947                    result.add(xpDomainInfo.resolveInfo);
6948                }
6949                includeBrowser = true;
6950            }
6951
6952            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6953            // If there were 'always' entries their preferred order has been set, so we also
6954            // back that off to make the alternatives equivalent
6955            if (alwaysAskList.size() > 0) {
6956                for (ResolveInfo i : result) {
6957                    i.preferredOrder = 0;
6958                }
6959                result.addAll(alwaysAskList);
6960                includeBrowser = true;
6961            }
6962
6963            if (includeBrowser) {
6964                // Also add browsers (all of them or only the default one)
6965                if (DEBUG_DOMAIN_VERIFICATION) {
6966                    Slog.v(TAG, "   ...including browsers in candidate set");
6967                }
6968                if ((matchFlags & MATCH_ALL) != 0) {
6969                    result.addAll(matchAllList);
6970                } else {
6971                    // Browser/generic handling case.  If there's a default browser, go straight
6972                    // to that (but only if there is no other higher-priority match).
6973                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6974                    int maxMatchPrio = 0;
6975                    ResolveInfo defaultBrowserMatch = null;
6976                    final int numCandidates = matchAllList.size();
6977                    for (int n = 0; n < numCandidates; n++) {
6978                        ResolveInfo info = matchAllList.get(n);
6979                        // track the highest overall match priority...
6980                        if (info.priority > maxMatchPrio) {
6981                            maxMatchPrio = info.priority;
6982                        }
6983                        // ...and the highest-priority default browser match
6984                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6985                            if (defaultBrowserMatch == null
6986                                    || (defaultBrowserMatch.priority < info.priority)) {
6987                                if (debug) {
6988                                    Slog.v(TAG, "Considering default browser match " + info);
6989                                }
6990                                defaultBrowserMatch = info;
6991                            }
6992                        }
6993                    }
6994                    if (defaultBrowserMatch != null
6995                            && defaultBrowserMatch.priority >= maxMatchPrio
6996                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6997                    {
6998                        if (debug) {
6999                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7000                        }
7001                        result.add(defaultBrowserMatch);
7002                    } else {
7003                        result.addAll(matchAllList);
7004                    }
7005                }
7006
7007                // If there is nothing selected, add all candidates and remove the ones that the user
7008                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7009                if (result.size() == 0) {
7010                    result.addAll(candidates);
7011                    result.removeAll(neverList);
7012                }
7013            }
7014        }
7015        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7016            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7017                    result.size());
7018            for (ResolveInfo info : result) {
7019                Slog.v(TAG, "  + " + info.activityInfo);
7020            }
7021        }
7022        return result;
7023    }
7024
7025    // Returns a packed value as a long:
7026    //
7027    // high 'int'-sized word: link status: undefined/ask/never/always.
7028    // low 'int'-sized word: relative priority among 'always' results.
7029    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7030        long result = ps.getDomainVerificationStatusForUser(userId);
7031        // if none available, get the master status
7032        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7033            if (ps.getIntentFilterVerificationInfo() != null) {
7034                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7035            }
7036        }
7037        return result;
7038    }
7039
7040    private ResolveInfo querySkipCurrentProfileIntents(
7041            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7042            int flags, int sourceUserId) {
7043        if (matchingFilters != null) {
7044            int size = matchingFilters.size();
7045            for (int i = 0; i < size; i ++) {
7046                CrossProfileIntentFilter filter = matchingFilters.get(i);
7047                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7048                    // Checking if there are activities in the target user that can handle the
7049                    // intent.
7050                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7051                            resolvedType, flags, sourceUserId);
7052                    if (resolveInfo != null) {
7053                        return resolveInfo;
7054                    }
7055                }
7056            }
7057        }
7058        return null;
7059    }
7060
7061    // Return matching ResolveInfo in target user if any.
7062    private ResolveInfo queryCrossProfileIntents(
7063            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7064            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7065        if (matchingFilters != null) {
7066            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7067            // match the same intent. For performance reasons, it is better not to
7068            // run queryIntent twice for the same userId
7069            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7070            int size = matchingFilters.size();
7071            for (int i = 0; i < size; i++) {
7072                CrossProfileIntentFilter filter = matchingFilters.get(i);
7073                int targetUserId = filter.getTargetUserId();
7074                boolean skipCurrentProfile =
7075                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7076                boolean skipCurrentProfileIfNoMatchFound =
7077                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7078                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7079                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7080                    // Checking if there are activities in the target user that can handle the
7081                    // intent.
7082                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7083                            resolvedType, flags, sourceUserId);
7084                    if (resolveInfo != null) return resolveInfo;
7085                    alreadyTriedUserIds.put(targetUserId, true);
7086                }
7087            }
7088        }
7089        return null;
7090    }
7091
7092    /**
7093     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7094     * will forward the intent to the filter's target user.
7095     * Otherwise, returns null.
7096     */
7097    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7098            String resolvedType, int flags, int sourceUserId) {
7099        int targetUserId = filter.getTargetUserId();
7100        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7101                resolvedType, flags, targetUserId);
7102        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7103            // If all the matches in the target profile are suspended, return null.
7104            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7105                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7106                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7107                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7108                            targetUserId);
7109                }
7110            }
7111        }
7112        return null;
7113    }
7114
7115    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7116            int sourceUserId, int targetUserId) {
7117        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7118        long ident = Binder.clearCallingIdentity();
7119        boolean targetIsProfile;
7120        try {
7121            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7122        } finally {
7123            Binder.restoreCallingIdentity(ident);
7124        }
7125        String className;
7126        if (targetIsProfile) {
7127            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7128        } else {
7129            className = FORWARD_INTENT_TO_PARENT;
7130        }
7131        ComponentName forwardingActivityComponentName = new ComponentName(
7132                mAndroidApplication.packageName, className);
7133        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7134                sourceUserId);
7135        if (!targetIsProfile) {
7136            forwardingActivityInfo.showUserIcon = targetUserId;
7137            forwardingResolveInfo.noResourceId = true;
7138        }
7139        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7140        forwardingResolveInfo.priority = 0;
7141        forwardingResolveInfo.preferredOrder = 0;
7142        forwardingResolveInfo.match = 0;
7143        forwardingResolveInfo.isDefault = true;
7144        forwardingResolveInfo.filter = filter;
7145        forwardingResolveInfo.targetUserId = targetUserId;
7146        return forwardingResolveInfo;
7147    }
7148
7149    @Override
7150    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7151            Intent[] specifics, String[] specificTypes, Intent intent,
7152            String resolvedType, int flags, int userId) {
7153        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7154                specificTypes, intent, resolvedType, flags, userId));
7155    }
7156
7157    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7158            Intent[] specifics, String[] specificTypes, Intent intent,
7159            String resolvedType, int flags, int userId) {
7160        if (!sUserManager.exists(userId)) return Collections.emptyList();
7161        final int callingUid = Binder.getCallingUid();
7162        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7163                false /*includeInstantApps*/);
7164        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7165                false /*requireFullPermission*/, false /*checkShell*/,
7166                "query intent activity options");
7167        final String resultsAction = intent.getAction();
7168
7169        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7170                | PackageManager.GET_RESOLVED_FILTER, userId);
7171
7172        if (DEBUG_INTENT_MATCHING) {
7173            Log.v(TAG, "Query " + intent + ": " + results);
7174        }
7175
7176        int specificsPos = 0;
7177        int N;
7178
7179        // todo: note that the algorithm used here is O(N^2).  This
7180        // isn't a problem in our current environment, but if we start running
7181        // into situations where we have more than 5 or 10 matches then this
7182        // should probably be changed to something smarter...
7183
7184        // First we go through and resolve each of the specific items
7185        // that were supplied, taking care of removing any corresponding
7186        // duplicate items in the generic resolve list.
7187        if (specifics != null) {
7188            for (int i=0; i<specifics.length; i++) {
7189                final Intent sintent = specifics[i];
7190                if (sintent == null) {
7191                    continue;
7192                }
7193
7194                if (DEBUG_INTENT_MATCHING) {
7195                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7196                }
7197
7198                String action = sintent.getAction();
7199                if (resultsAction != null && resultsAction.equals(action)) {
7200                    // If this action was explicitly requested, then don't
7201                    // remove things that have it.
7202                    action = null;
7203                }
7204
7205                ResolveInfo ri = null;
7206                ActivityInfo ai = null;
7207
7208                ComponentName comp = sintent.getComponent();
7209                if (comp == null) {
7210                    ri = resolveIntent(
7211                        sintent,
7212                        specificTypes != null ? specificTypes[i] : null,
7213                            flags, userId);
7214                    if (ri == null) {
7215                        continue;
7216                    }
7217                    if (ri == mResolveInfo) {
7218                        // ACK!  Must do something better with this.
7219                    }
7220                    ai = ri.activityInfo;
7221                    comp = new ComponentName(ai.applicationInfo.packageName,
7222                            ai.name);
7223                } else {
7224                    ai = getActivityInfo(comp, flags, userId);
7225                    if (ai == null) {
7226                        continue;
7227                    }
7228                }
7229
7230                // Look for any generic query activities that are duplicates
7231                // of this specific one, and remove them from the results.
7232                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7233                N = results.size();
7234                int j;
7235                for (j=specificsPos; j<N; j++) {
7236                    ResolveInfo sri = results.get(j);
7237                    if ((sri.activityInfo.name.equals(comp.getClassName())
7238                            && sri.activityInfo.applicationInfo.packageName.equals(
7239                                    comp.getPackageName()))
7240                        || (action != null && sri.filter.matchAction(action))) {
7241                        results.remove(j);
7242                        if (DEBUG_INTENT_MATCHING) Log.v(
7243                            TAG, "Removing duplicate item from " + j
7244                            + " due to specific " + specificsPos);
7245                        if (ri == null) {
7246                            ri = sri;
7247                        }
7248                        j--;
7249                        N--;
7250                    }
7251                }
7252
7253                // Add this specific item to its proper place.
7254                if (ri == null) {
7255                    ri = new ResolveInfo();
7256                    ri.activityInfo = ai;
7257                }
7258                results.add(specificsPos, ri);
7259                ri.specificIndex = i;
7260                specificsPos++;
7261            }
7262        }
7263
7264        // Now we go through the remaining generic results and remove any
7265        // duplicate actions that are found here.
7266        N = results.size();
7267        for (int i=specificsPos; i<N-1; i++) {
7268            final ResolveInfo rii = results.get(i);
7269            if (rii.filter == null) {
7270                continue;
7271            }
7272
7273            // Iterate over all of the actions of this result's intent
7274            // filter...  typically this should be just one.
7275            final Iterator<String> it = rii.filter.actionsIterator();
7276            if (it == null) {
7277                continue;
7278            }
7279            while (it.hasNext()) {
7280                final String action = it.next();
7281                if (resultsAction != null && resultsAction.equals(action)) {
7282                    // If this action was explicitly requested, then don't
7283                    // remove things that have it.
7284                    continue;
7285                }
7286                for (int j=i+1; j<N; j++) {
7287                    final ResolveInfo rij = results.get(j);
7288                    if (rij.filter != null && rij.filter.hasAction(action)) {
7289                        results.remove(j);
7290                        if (DEBUG_INTENT_MATCHING) Log.v(
7291                            TAG, "Removing duplicate item from " + j
7292                            + " due to action " + action + " at " + i);
7293                        j--;
7294                        N--;
7295                    }
7296                }
7297            }
7298
7299            // If the caller didn't request filter information, drop it now
7300            // so we don't have to marshall/unmarshall it.
7301            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7302                rii.filter = null;
7303            }
7304        }
7305
7306        // Filter out the caller activity if so requested.
7307        if (caller != null) {
7308            N = results.size();
7309            for (int i=0; i<N; i++) {
7310                ActivityInfo ainfo = results.get(i).activityInfo;
7311                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7312                        && caller.getClassName().equals(ainfo.name)) {
7313                    results.remove(i);
7314                    break;
7315                }
7316            }
7317        }
7318
7319        // If the caller didn't request filter information,
7320        // drop them now so we don't have to
7321        // marshall/unmarshall it.
7322        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7323            N = results.size();
7324            for (int i=0; i<N; i++) {
7325                results.get(i).filter = null;
7326            }
7327        }
7328
7329        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7330        return results;
7331    }
7332
7333    @Override
7334    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7335            String resolvedType, int flags, int userId) {
7336        return new ParceledListSlice<>(
7337                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7338                        false /*allowDynamicSplits*/));
7339    }
7340
7341    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7342            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7343        if (!sUserManager.exists(userId)) return Collections.emptyList();
7344        final int callingUid = Binder.getCallingUid();
7345        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7346                false /*requireFullPermission*/, false /*checkShell*/,
7347                "query intent receivers");
7348        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7349        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7350                false /*includeInstantApps*/);
7351        ComponentName comp = intent.getComponent();
7352        if (comp == null) {
7353            if (intent.getSelector() != null) {
7354                intent = intent.getSelector();
7355                comp = intent.getComponent();
7356            }
7357        }
7358        if (comp != null) {
7359            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7360            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7361            if (ai != null) {
7362                // When specifying an explicit component, we prevent the activity from being
7363                // used when either 1) the calling package is normal and the activity is within
7364                // an instant application or 2) the calling package is ephemeral and the
7365                // activity is not visible to instant applications.
7366                final boolean matchInstantApp =
7367                        (flags & PackageManager.MATCH_INSTANT) != 0;
7368                final boolean matchVisibleToInstantAppOnly =
7369                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7370                final boolean matchExplicitlyVisibleOnly =
7371                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7372                final boolean isCallerInstantApp =
7373                        instantAppPkgName != null;
7374                final boolean isTargetSameInstantApp =
7375                        comp.getPackageName().equals(instantAppPkgName);
7376                final boolean isTargetInstantApp =
7377                        (ai.applicationInfo.privateFlags
7378                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7379                final boolean isTargetVisibleToInstantApp =
7380                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7381                final boolean isTargetExplicitlyVisibleToInstantApp =
7382                        isTargetVisibleToInstantApp
7383                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7384                final boolean isTargetHiddenFromInstantApp =
7385                        !isTargetVisibleToInstantApp
7386                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7387                final boolean blockResolution =
7388                        !isTargetSameInstantApp
7389                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7390                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7391                                        && isTargetHiddenFromInstantApp));
7392                if (!blockResolution) {
7393                    ResolveInfo ri = new ResolveInfo();
7394                    ri.activityInfo = ai;
7395                    list.add(ri);
7396                }
7397            }
7398            return applyPostResolutionFilter(
7399                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7400        }
7401
7402        // reader
7403        synchronized (mPackages) {
7404            String pkgName = intent.getPackage();
7405            if (pkgName == null) {
7406                final List<ResolveInfo> result =
7407                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7408                return applyPostResolutionFilter(
7409                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7410            }
7411            final PackageParser.Package pkg = mPackages.get(pkgName);
7412            if (pkg != null) {
7413                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7414                        intent, resolvedType, flags, pkg.receivers, userId);
7415                return applyPostResolutionFilter(
7416                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7417            }
7418            return Collections.emptyList();
7419        }
7420    }
7421
7422    @Override
7423    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7424        final int callingUid = Binder.getCallingUid();
7425        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7426    }
7427
7428    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7429            int userId, int callingUid) {
7430        if (!sUserManager.exists(userId)) return null;
7431        flags = updateFlagsForResolve(
7432                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7433        List<ResolveInfo> query = queryIntentServicesInternal(
7434                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7435        if (query != null) {
7436            if (query.size() >= 1) {
7437                // If there is more than one service with the same priority,
7438                // just arbitrarily pick the first one.
7439                return query.get(0);
7440            }
7441        }
7442        return null;
7443    }
7444
7445    @Override
7446    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7447            String resolvedType, int flags, int userId) {
7448        final int callingUid = Binder.getCallingUid();
7449        return new ParceledListSlice<>(queryIntentServicesInternal(
7450                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7451    }
7452
7453    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7454            String resolvedType, int flags, int userId, int callingUid,
7455            boolean includeInstantApps) {
7456        if (!sUserManager.exists(userId)) return Collections.emptyList();
7457        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7458                false /*requireFullPermission*/, false /*checkShell*/,
7459                "query intent receivers");
7460        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7461        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7462        ComponentName comp = intent.getComponent();
7463        if (comp == null) {
7464            if (intent.getSelector() != null) {
7465                intent = intent.getSelector();
7466                comp = intent.getComponent();
7467            }
7468        }
7469        if (comp != null) {
7470            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7471            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7472            if (si != null) {
7473                // When specifying an explicit component, we prevent the service from being
7474                // used when either 1) the service is in an instant application and the
7475                // caller is not the same instant application or 2) the calling package is
7476                // ephemeral and the activity is not visible to ephemeral applications.
7477                final boolean matchInstantApp =
7478                        (flags & PackageManager.MATCH_INSTANT) != 0;
7479                final boolean matchVisibleToInstantAppOnly =
7480                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7481                final boolean isCallerInstantApp =
7482                        instantAppPkgName != null;
7483                final boolean isTargetSameInstantApp =
7484                        comp.getPackageName().equals(instantAppPkgName);
7485                final boolean isTargetInstantApp =
7486                        (si.applicationInfo.privateFlags
7487                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7488                final boolean isTargetHiddenFromInstantApp =
7489                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7490                final boolean blockResolution =
7491                        !isTargetSameInstantApp
7492                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7493                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7494                                        && isTargetHiddenFromInstantApp));
7495                if (!blockResolution) {
7496                    final ResolveInfo ri = new ResolveInfo();
7497                    ri.serviceInfo = si;
7498                    list.add(ri);
7499                }
7500            }
7501            return list;
7502        }
7503
7504        // reader
7505        synchronized (mPackages) {
7506            String pkgName = intent.getPackage();
7507            if (pkgName == null) {
7508                return applyPostServiceResolutionFilter(
7509                        mServices.queryIntent(intent, resolvedType, flags, userId),
7510                        instantAppPkgName);
7511            }
7512            final PackageParser.Package pkg = mPackages.get(pkgName);
7513            if (pkg != null) {
7514                return applyPostServiceResolutionFilter(
7515                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7516                                userId),
7517                        instantAppPkgName);
7518            }
7519            return Collections.emptyList();
7520        }
7521    }
7522
7523    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7524            String instantAppPkgName) {
7525        if (instantAppPkgName == null) {
7526            return resolveInfos;
7527        }
7528        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7529            final ResolveInfo info = resolveInfos.get(i);
7530            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7531            // allow services that are defined in the provided package
7532            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7533                if (info.serviceInfo.splitName != null
7534                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7535                                info.serviceInfo.splitName)) {
7536                    // requested service is defined in a split that hasn't been installed yet.
7537                    // add the installer to the resolve list
7538                    if (DEBUG_EPHEMERAL) {
7539                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7540                    }
7541                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7542                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7543                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7544                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7545                            null /*failureIntent*/);
7546                    // make sure this resolver is the default
7547                    installerInfo.isDefault = true;
7548                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7549                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7550                    // add a non-generic filter
7551                    installerInfo.filter = new IntentFilter();
7552                    // load resources from the correct package
7553                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7554                    resolveInfos.set(i, installerInfo);
7555                }
7556                continue;
7557            }
7558            // allow services that have been explicitly exposed to ephemeral apps
7559            if (!isEphemeralApp
7560                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7561                continue;
7562            }
7563            resolveInfos.remove(i);
7564        }
7565        return resolveInfos;
7566    }
7567
7568    @Override
7569    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7570            String resolvedType, int flags, int userId) {
7571        return new ParceledListSlice<>(
7572                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7573    }
7574
7575    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7576            Intent intent, String resolvedType, int flags, int userId) {
7577        if (!sUserManager.exists(userId)) return Collections.emptyList();
7578        final int callingUid = Binder.getCallingUid();
7579        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7580        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7581                false /*includeInstantApps*/);
7582        ComponentName comp = intent.getComponent();
7583        if (comp == null) {
7584            if (intent.getSelector() != null) {
7585                intent = intent.getSelector();
7586                comp = intent.getComponent();
7587            }
7588        }
7589        if (comp != null) {
7590            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7591            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7592            if (pi != null) {
7593                // When specifying an explicit component, we prevent the provider from being
7594                // used when either 1) the provider is in an instant application and the
7595                // caller is not the same instant application or 2) the calling package is an
7596                // instant application and the provider is not visible to instant applications.
7597                final boolean matchInstantApp =
7598                        (flags & PackageManager.MATCH_INSTANT) != 0;
7599                final boolean matchVisibleToInstantAppOnly =
7600                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7601                final boolean isCallerInstantApp =
7602                        instantAppPkgName != null;
7603                final boolean isTargetSameInstantApp =
7604                        comp.getPackageName().equals(instantAppPkgName);
7605                final boolean isTargetInstantApp =
7606                        (pi.applicationInfo.privateFlags
7607                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7608                final boolean isTargetHiddenFromInstantApp =
7609                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7610                final boolean blockResolution =
7611                        !isTargetSameInstantApp
7612                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7613                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7614                                        && isTargetHiddenFromInstantApp));
7615                if (!blockResolution) {
7616                    final ResolveInfo ri = new ResolveInfo();
7617                    ri.providerInfo = pi;
7618                    list.add(ri);
7619                }
7620            }
7621            return list;
7622        }
7623
7624        // reader
7625        synchronized (mPackages) {
7626            String pkgName = intent.getPackage();
7627            if (pkgName == null) {
7628                return applyPostContentProviderResolutionFilter(
7629                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7630                        instantAppPkgName);
7631            }
7632            final PackageParser.Package pkg = mPackages.get(pkgName);
7633            if (pkg != null) {
7634                return applyPostContentProviderResolutionFilter(
7635                        mProviders.queryIntentForPackage(
7636                        intent, resolvedType, flags, pkg.providers, userId),
7637                        instantAppPkgName);
7638            }
7639            return Collections.emptyList();
7640        }
7641    }
7642
7643    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7644            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7645        if (instantAppPkgName == null) {
7646            return resolveInfos;
7647        }
7648        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7649            final ResolveInfo info = resolveInfos.get(i);
7650            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7651            // allow providers that are defined in the provided package
7652            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7653                if (info.providerInfo.splitName != null
7654                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7655                                info.providerInfo.splitName)) {
7656                    // requested provider is defined in a split that hasn't been installed yet.
7657                    // add the installer to the resolve list
7658                    if (DEBUG_EPHEMERAL) {
7659                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7660                    }
7661                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7662                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7663                            info.providerInfo.packageName, info.providerInfo.splitName,
7664                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7665                            null /*failureIntent*/);
7666                    // make sure this resolver is the default
7667                    installerInfo.isDefault = true;
7668                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7669                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7670                    // add a non-generic filter
7671                    installerInfo.filter = new IntentFilter();
7672                    // load resources from the correct package
7673                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7674                    resolveInfos.set(i, installerInfo);
7675                }
7676                continue;
7677            }
7678            // allow providers that have been explicitly exposed to instant applications
7679            if (!isEphemeralApp
7680                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7681                continue;
7682            }
7683            resolveInfos.remove(i);
7684        }
7685        return resolveInfos;
7686    }
7687
7688    @Override
7689    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7690        final int callingUid = Binder.getCallingUid();
7691        if (getInstantAppPackageName(callingUid) != null) {
7692            return ParceledListSlice.emptyList();
7693        }
7694        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7695        flags = updateFlagsForPackage(flags, userId, null);
7696        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7697        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7698                true /* requireFullPermission */, false /* checkShell */,
7699                "get installed packages");
7700
7701        // writer
7702        synchronized (mPackages) {
7703            ArrayList<PackageInfo> list;
7704            if (listUninstalled) {
7705                list = new ArrayList<>(mSettings.mPackages.size());
7706                for (PackageSetting ps : mSettings.mPackages.values()) {
7707                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7708                        continue;
7709                    }
7710                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7711                        continue;
7712                    }
7713                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7714                    if (pi != null) {
7715                        list.add(pi);
7716                    }
7717                }
7718            } else {
7719                list = new ArrayList<>(mPackages.size());
7720                for (PackageParser.Package p : mPackages.values()) {
7721                    final PackageSetting ps = (PackageSetting) p.mExtras;
7722                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7723                        continue;
7724                    }
7725                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7726                        continue;
7727                    }
7728                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7729                            p.mExtras, flags, userId);
7730                    if (pi != null) {
7731                        list.add(pi);
7732                    }
7733                }
7734            }
7735
7736            return new ParceledListSlice<>(list);
7737        }
7738    }
7739
7740    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7741            String[] permissions, boolean[] tmp, int flags, int userId) {
7742        int numMatch = 0;
7743        final PermissionsState permissionsState = ps.getPermissionsState();
7744        for (int i=0; i<permissions.length; i++) {
7745            final String permission = permissions[i];
7746            if (permissionsState.hasPermission(permission, userId)) {
7747                tmp[i] = true;
7748                numMatch++;
7749            } else {
7750                tmp[i] = false;
7751            }
7752        }
7753        if (numMatch == 0) {
7754            return;
7755        }
7756        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7757
7758        // The above might return null in cases of uninstalled apps or install-state
7759        // skew across users/profiles.
7760        if (pi != null) {
7761            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7762                if (numMatch == permissions.length) {
7763                    pi.requestedPermissions = permissions;
7764                } else {
7765                    pi.requestedPermissions = new String[numMatch];
7766                    numMatch = 0;
7767                    for (int i=0; i<permissions.length; i++) {
7768                        if (tmp[i]) {
7769                            pi.requestedPermissions[numMatch] = permissions[i];
7770                            numMatch++;
7771                        }
7772                    }
7773                }
7774            }
7775            list.add(pi);
7776        }
7777    }
7778
7779    @Override
7780    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7781            String[] permissions, int flags, int userId) {
7782        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7783        flags = updateFlagsForPackage(flags, userId, permissions);
7784        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7785                true /* requireFullPermission */, false /* checkShell */,
7786                "get packages holding permissions");
7787        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7788
7789        // writer
7790        synchronized (mPackages) {
7791            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7792            boolean[] tmpBools = new boolean[permissions.length];
7793            if (listUninstalled) {
7794                for (PackageSetting ps : mSettings.mPackages.values()) {
7795                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7796                            userId);
7797                }
7798            } else {
7799                for (PackageParser.Package pkg : mPackages.values()) {
7800                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7801                    if (ps != null) {
7802                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7803                                userId);
7804                    }
7805                }
7806            }
7807
7808            return new ParceledListSlice<PackageInfo>(list);
7809        }
7810    }
7811
7812    @Override
7813    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7814        final int callingUid = Binder.getCallingUid();
7815        if (getInstantAppPackageName(callingUid) != null) {
7816            return ParceledListSlice.emptyList();
7817        }
7818        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7819        flags = updateFlagsForApplication(flags, userId, null);
7820        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7821
7822        // writer
7823        synchronized (mPackages) {
7824            ArrayList<ApplicationInfo> list;
7825            if (listUninstalled) {
7826                list = new ArrayList<>(mSettings.mPackages.size());
7827                for (PackageSetting ps : mSettings.mPackages.values()) {
7828                    ApplicationInfo ai;
7829                    int effectiveFlags = flags;
7830                    if (ps.isSystem()) {
7831                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7832                    }
7833                    if (ps.pkg != null) {
7834                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7835                            continue;
7836                        }
7837                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7838                            continue;
7839                        }
7840                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7841                                ps.readUserState(userId), userId);
7842                        if (ai != null) {
7843                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7844                        }
7845                    } else {
7846                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7847                        // and already converts to externally visible package name
7848                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7849                                callingUid, effectiveFlags, userId);
7850                    }
7851                    if (ai != null) {
7852                        list.add(ai);
7853                    }
7854                }
7855            } else {
7856                list = new ArrayList<>(mPackages.size());
7857                for (PackageParser.Package p : mPackages.values()) {
7858                    if (p.mExtras != null) {
7859                        PackageSetting ps = (PackageSetting) p.mExtras;
7860                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7861                            continue;
7862                        }
7863                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7864                            continue;
7865                        }
7866                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7867                                ps.readUserState(userId), userId);
7868                        if (ai != null) {
7869                            ai.packageName = resolveExternalPackageNameLPr(p);
7870                            list.add(ai);
7871                        }
7872                    }
7873                }
7874            }
7875
7876            return new ParceledListSlice<>(list);
7877        }
7878    }
7879
7880    @Override
7881    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7882        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7883            return null;
7884        }
7885        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7886            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7887                    "getEphemeralApplications");
7888        }
7889        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7890                true /* requireFullPermission */, false /* checkShell */,
7891                "getEphemeralApplications");
7892        synchronized (mPackages) {
7893            List<InstantAppInfo> instantApps = mInstantAppRegistry
7894                    .getInstantAppsLPr(userId);
7895            if (instantApps != null) {
7896                return new ParceledListSlice<>(instantApps);
7897            }
7898        }
7899        return null;
7900    }
7901
7902    @Override
7903    public boolean isInstantApp(String packageName, int userId) {
7904        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7905                true /* requireFullPermission */, false /* checkShell */,
7906                "isInstantApp");
7907        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7908            return false;
7909        }
7910
7911        synchronized (mPackages) {
7912            int callingUid = Binder.getCallingUid();
7913            if (Process.isIsolated(callingUid)) {
7914                callingUid = mIsolatedOwners.get(callingUid);
7915            }
7916            final PackageSetting ps = mSettings.mPackages.get(packageName);
7917            PackageParser.Package pkg = mPackages.get(packageName);
7918            final boolean returnAllowed =
7919                    ps != null
7920                    && (isCallerSameApp(packageName, callingUid)
7921                            || canViewInstantApps(callingUid, userId)
7922                            || mInstantAppRegistry.isInstantAccessGranted(
7923                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7924            if (returnAllowed) {
7925                return ps.getInstantApp(userId);
7926            }
7927        }
7928        return false;
7929    }
7930
7931    @Override
7932    public byte[] getInstantAppCookie(String packageName, int userId) {
7933        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7934            return null;
7935        }
7936
7937        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7938                true /* requireFullPermission */, false /* checkShell */,
7939                "getInstantAppCookie");
7940        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7941            return null;
7942        }
7943        synchronized (mPackages) {
7944            return mInstantAppRegistry.getInstantAppCookieLPw(
7945                    packageName, userId);
7946        }
7947    }
7948
7949    @Override
7950    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7951        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7952            return true;
7953        }
7954
7955        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7956                true /* requireFullPermission */, true /* checkShell */,
7957                "setInstantAppCookie");
7958        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7959            return false;
7960        }
7961        synchronized (mPackages) {
7962            return mInstantAppRegistry.setInstantAppCookieLPw(
7963                    packageName, cookie, userId);
7964        }
7965    }
7966
7967    @Override
7968    public Bitmap getInstantAppIcon(String packageName, int userId) {
7969        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7970            return null;
7971        }
7972
7973        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7974            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7975                    "getInstantAppIcon");
7976        }
7977        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7978                true /* requireFullPermission */, false /* checkShell */,
7979                "getInstantAppIcon");
7980
7981        synchronized (mPackages) {
7982            return mInstantAppRegistry.getInstantAppIconLPw(
7983                    packageName, userId);
7984        }
7985    }
7986
7987    private boolean isCallerSameApp(String packageName, int uid) {
7988        PackageParser.Package pkg = mPackages.get(packageName);
7989        return pkg != null
7990                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7991    }
7992
7993    @Override
7994    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7995        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7996            return ParceledListSlice.emptyList();
7997        }
7998        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7999    }
8000
8001    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8002        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8003
8004        // reader
8005        synchronized (mPackages) {
8006            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8007            final int userId = UserHandle.getCallingUserId();
8008            while (i.hasNext()) {
8009                final PackageParser.Package p = i.next();
8010                if (p.applicationInfo == null) continue;
8011
8012                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8013                        && !p.applicationInfo.isDirectBootAware();
8014                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8015                        && p.applicationInfo.isDirectBootAware();
8016
8017                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8018                        && (!mSafeMode || isSystemApp(p))
8019                        && (matchesUnaware || matchesAware)) {
8020                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8021                    if (ps != null) {
8022                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8023                                ps.readUserState(userId), userId);
8024                        if (ai != null) {
8025                            finalList.add(ai);
8026                        }
8027                    }
8028                }
8029            }
8030        }
8031
8032        return finalList;
8033    }
8034
8035    @Override
8036    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8037        return resolveContentProviderInternal(name, flags, userId);
8038    }
8039
8040    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8041        if (!sUserManager.exists(userId)) return null;
8042        flags = updateFlagsForComponent(flags, userId, name);
8043        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8044        // reader
8045        synchronized (mPackages) {
8046            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8047            PackageSetting ps = provider != null
8048                    ? mSettings.mPackages.get(provider.owner.packageName)
8049                    : null;
8050            if (ps != null) {
8051                final boolean isInstantApp = ps.getInstantApp(userId);
8052                // normal application; filter out instant application provider
8053                if (instantAppPkgName == null && isInstantApp) {
8054                    return null;
8055                }
8056                // instant application; filter out other instant applications
8057                if (instantAppPkgName != null
8058                        && isInstantApp
8059                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8060                    return null;
8061                }
8062                // instant application; filter out non-exposed provider
8063                if (instantAppPkgName != null
8064                        && !isInstantApp
8065                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8066                    return null;
8067                }
8068                // provider not enabled
8069                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8070                    return null;
8071                }
8072                return PackageParser.generateProviderInfo(
8073                        provider, flags, ps.readUserState(userId), userId);
8074            }
8075            return null;
8076        }
8077    }
8078
8079    /**
8080     * @deprecated
8081     */
8082    @Deprecated
8083    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8084        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8085            return;
8086        }
8087        // reader
8088        synchronized (mPackages) {
8089            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8090                    .entrySet().iterator();
8091            final int userId = UserHandle.getCallingUserId();
8092            while (i.hasNext()) {
8093                Map.Entry<String, PackageParser.Provider> entry = i.next();
8094                PackageParser.Provider p = entry.getValue();
8095                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8096
8097                if (ps != null && p.syncable
8098                        && (!mSafeMode || (p.info.applicationInfo.flags
8099                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8100                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8101                            ps.readUserState(userId), userId);
8102                    if (info != null) {
8103                        outNames.add(entry.getKey());
8104                        outInfo.add(info);
8105                    }
8106                }
8107            }
8108        }
8109    }
8110
8111    @Override
8112    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8113            int uid, int flags, String metaDataKey) {
8114        final int callingUid = Binder.getCallingUid();
8115        final int userId = processName != null ? UserHandle.getUserId(uid)
8116                : UserHandle.getCallingUserId();
8117        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8118        flags = updateFlagsForComponent(flags, userId, processName);
8119        ArrayList<ProviderInfo> finalList = null;
8120        // reader
8121        synchronized (mPackages) {
8122            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8123            while (i.hasNext()) {
8124                final PackageParser.Provider p = i.next();
8125                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8126                if (ps != null && p.info.authority != null
8127                        && (processName == null
8128                                || (p.info.processName.equals(processName)
8129                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8130                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8131
8132                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8133                    // parameter.
8134                    if (metaDataKey != null
8135                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8136                        continue;
8137                    }
8138                    final ComponentName component =
8139                            new ComponentName(p.info.packageName, p.info.name);
8140                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8141                        continue;
8142                    }
8143                    if (finalList == null) {
8144                        finalList = new ArrayList<ProviderInfo>(3);
8145                    }
8146                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8147                            ps.readUserState(userId), userId);
8148                    if (info != null) {
8149                        finalList.add(info);
8150                    }
8151                }
8152            }
8153        }
8154
8155        if (finalList != null) {
8156            Collections.sort(finalList, mProviderInitOrderSorter);
8157            return new ParceledListSlice<ProviderInfo>(finalList);
8158        }
8159
8160        return ParceledListSlice.emptyList();
8161    }
8162
8163    @Override
8164    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8165        // reader
8166        synchronized (mPackages) {
8167            final int callingUid = Binder.getCallingUid();
8168            final int callingUserId = UserHandle.getUserId(callingUid);
8169            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8170            if (ps == null) return null;
8171            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8172                return null;
8173            }
8174            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8175            return PackageParser.generateInstrumentationInfo(i, flags);
8176        }
8177    }
8178
8179    @Override
8180    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8181            String targetPackage, int flags) {
8182        final int callingUid = Binder.getCallingUid();
8183        final int callingUserId = UserHandle.getUserId(callingUid);
8184        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8185        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8186            return ParceledListSlice.emptyList();
8187        }
8188        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8189    }
8190
8191    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8192            int flags) {
8193        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8194
8195        // reader
8196        synchronized (mPackages) {
8197            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8198            while (i.hasNext()) {
8199                final PackageParser.Instrumentation p = i.next();
8200                if (targetPackage == null
8201                        || targetPackage.equals(p.info.targetPackage)) {
8202                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8203                            flags);
8204                    if (ii != null) {
8205                        finalList.add(ii);
8206                    }
8207                }
8208            }
8209        }
8210
8211        return finalList;
8212    }
8213
8214    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8215        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8216        try {
8217            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8218        } finally {
8219            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8220        }
8221    }
8222
8223    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8224        final File[] files = scanDir.listFiles();
8225        if (ArrayUtils.isEmpty(files)) {
8226            Log.d(TAG, "No files in app dir " + scanDir);
8227            return;
8228        }
8229
8230        if (DEBUG_PACKAGE_SCANNING) {
8231            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8232                    + " flags=0x" + Integer.toHexString(parseFlags));
8233        }
8234        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8235                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8236                mParallelPackageParserCallback)) {
8237            // Submit files for parsing in parallel
8238            int fileCount = 0;
8239            for (File file : files) {
8240                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8241                        && !PackageInstallerService.isStageName(file.getName());
8242                if (!isPackage) {
8243                    // Ignore entries which are not packages
8244                    continue;
8245                }
8246                parallelPackageParser.submit(file, parseFlags);
8247                fileCount++;
8248            }
8249
8250            // Process results one by one
8251            for (; fileCount > 0; fileCount--) {
8252                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8253                Throwable throwable = parseResult.throwable;
8254                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8255
8256                if (throwable == null) {
8257                    // TODO(toddke): move lower in the scan chain
8258                    // Static shared libraries have synthetic package names
8259                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8260                        renameStaticSharedLibraryPackage(parseResult.pkg);
8261                    }
8262                    try {
8263                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8264                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8265                                    currentTime, null);
8266                        }
8267                    } catch (PackageManagerException e) {
8268                        errorCode = e.error;
8269                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8270                    }
8271                } else if (throwable instanceof PackageParser.PackageParserException) {
8272                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8273                            throwable;
8274                    errorCode = e.error;
8275                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8276                } else {
8277                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8278                            + parseResult.scanFile, throwable);
8279                }
8280
8281                // Delete invalid userdata apps
8282                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8283                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8284                    logCriticalInfo(Log.WARN,
8285                            "Deleting invalid package at " + parseResult.scanFile);
8286                    removeCodePathLI(parseResult.scanFile);
8287                }
8288            }
8289        }
8290    }
8291
8292    public static void reportSettingsProblem(int priority, String msg) {
8293        logCriticalInfo(priority, msg);
8294    }
8295
8296    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8297            final @ParseFlags int parseFlags, boolean forceCollect) throws PackageManagerException {
8298        // When upgrading from pre-N MR1, verify the package time stamp using the package
8299        // directory and not the APK file.
8300        final long lastModifiedTime = mIsPreNMR1Upgrade
8301                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8302        if (ps != null && !forceCollect
8303                && ps.codePathString.equals(pkg.codePath)
8304                && ps.timeStamp == lastModifiedTime
8305                && !isCompatSignatureUpdateNeeded(pkg)
8306                && !isRecoverSignatureUpdateNeeded(pkg)) {
8307            if (ps.signatures.mSigningDetails.signatures != null
8308                    && ps.signatures.mSigningDetails.signatures.length != 0
8309                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8310                            != SignatureSchemeVersion.UNKNOWN) {
8311                // Optimization: reuse the existing cached signing data
8312                // if the package appears to be unchanged.
8313                pkg.mSigningDetails =
8314                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8315                return;
8316            }
8317
8318            Slog.w(TAG, "PackageSetting for " + ps.name
8319                    + " is missing signatures.  Collecting certs again to recover them.");
8320        } else {
8321            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8322                    (forceCollect ? " (forced)" : ""));
8323        }
8324
8325        try {
8326            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8327            PackageParser.collectCertificates(pkg, parseFlags);
8328        } catch (PackageParserException e) {
8329            throw PackageManagerException.from(e);
8330        } finally {
8331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8332        }
8333    }
8334
8335    /**
8336     *  Traces a package scan.
8337     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8338     */
8339    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8340            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8341        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8342        try {
8343            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8344        } finally {
8345            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8346        }
8347    }
8348
8349    /**
8350     *  Scans a package and returns the newly parsed package.
8351     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8352     */
8353    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8354            long currentTime, UserHandle user) throws PackageManagerException {
8355        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8356        PackageParser pp = new PackageParser();
8357        pp.setSeparateProcesses(mSeparateProcesses);
8358        pp.setOnlyCoreApps(mOnlyCore);
8359        pp.setDisplayMetrics(mMetrics);
8360        pp.setCallback(mPackageParserCallback);
8361
8362        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8363        final PackageParser.Package pkg;
8364        try {
8365            pkg = pp.parsePackage(scanFile, parseFlags);
8366        } catch (PackageParserException e) {
8367            throw PackageManagerException.from(e);
8368        } finally {
8369            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8370        }
8371
8372        // Static shared libraries have synthetic package names
8373        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8374            renameStaticSharedLibraryPackage(pkg);
8375        }
8376
8377        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8378    }
8379
8380    /**
8381     *  Scans a package and returns the newly parsed package.
8382     *  @throws PackageManagerException on a parse error.
8383     */
8384    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8385            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8386            @Nullable UserHandle user)
8387                    throws PackageManagerException {
8388        // If the package has children and this is the first dive in the function
8389        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8390        // packages (parent and children) would be successfully scanned before the
8391        // actual scan since scanning mutates internal state and we want to atomically
8392        // install the package and its children.
8393        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8394            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8395                scanFlags |= SCAN_CHECK_ONLY;
8396            }
8397        } else {
8398            scanFlags &= ~SCAN_CHECK_ONLY;
8399        }
8400
8401        // Scan the parent
8402        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8403                scanFlags, currentTime, user);
8404
8405        // Scan the children
8406        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8407        for (int i = 0; i < childCount; i++) {
8408            PackageParser.Package childPackage = pkg.childPackages.get(i);
8409            addForInitLI(childPackage, parseFlags, scanFlags,
8410                    currentTime, user);
8411        }
8412
8413
8414        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8415            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8416        }
8417
8418        return scannedPkg;
8419    }
8420
8421    // Temporary to catch potential issues with refactoring
8422    private static boolean REFACTOR_DEBUG = true;
8423    /**
8424     * Adds a new package to the internal data structures during platform initialization.
8425     * <p>After adding, the package is known to the system and available for querying.
8426     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8427     * etc...], additional checks are performed. Basic verification [such as ensuring
8428     * matching signatures, checking version codes, etc...] occurs if the package is
8429     * identical to a previously known package. If the package fails a signature check,
8430     * the version installed on /data will be removed. If the version of the new package
8431     * is less than or equal than the version on /data, it will be ignored.
8432     * <p>Regardless of the package location, the results are applied to the internal
8433     * structures and the package is made available to the rest of the system.
8434     * <p>NOTE: The return value should be removed. It's the passed in package object.
8435     */
8436    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8437            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8438            @Nullable UserHandle user)
8439                    throws PackageManagerException {
8440        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8441        final String renamedPkgName;
8442        final PackageSetting disabledPkgSetting;
8443        final boolean isSystemPkgUpdated;
8444        final boolean pkgAlreadyExists;
8445        PackageSetting pkgSetting;
8446
8447        // NOTE: installPackageLI() has the same code to setup the package's
8448        // application info. This probably should be done lower in the call
8449        // stack [such as scanPackageOnly()]. However, we verify the application
8450        // info prior to that [in scanPackageNew()] and thus have to setup
8451        // the application info early.
8452        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8453        pkg.setApplicationInfoCodePath(pkg.codePath);
8454        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8455        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8456        pkg.setApplicationInfoResourcePath(pkg.codePath);
8457        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8458        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8459
8460        synchronized (mPackages) {
8461            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8462            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8463if (REFACTOR_DEBUG) {
8464Slog.e("TODD",
8465        "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName));
8466}
8467            if (realPkgName != null) {
8468                ensurePackageRenamed(pkg, renamedPkgName);
8469            }
8470            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8471            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8472            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8473            pkgAlreadyExists = pkgSetting != null;
8474            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8475            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8476            isSystemPkgUpdated = disabledPkgSetting != null;
8477
8478            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8479                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8480            }
8481if (REFACTOR_DEBUG) {
8482Slog.e("TODD",
8483        "SSP? " + scanSystemPartition
8484        + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"")
8485        + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():""));
8486}
8487
8488            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8489                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8490                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8491                    : null;
8492            if (DEBUG_PACKAGE_SCANNING
8493                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8494                    && sharedUserSetting != null) {
8495                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8496                        + " (uid=" + sharedUserSetting.userId + "):"
8497                        + " packages=" + sharedUserSetting.packages);
8498if (REFACTOR_DEBUG) {
8499Slog.e("TODD",
8500        "Shared UserID " + pkg.mSharedUserId
8501        + " (uid=" + sharedUserSetting.userId + "):"
8502        + " packages=" + sharedUserSetting.packages);
8503}
8504            }
8505
8506            if (scanSystemPartition) {
8507                // Potentially prune child packages. If the application on the /system
8508                // partition has been updated via OTA, but, is still disabled by a
8509                // version on /data, cycle through all of its children packages and
8510                // remove children that are no longer defined.
8511                if (isSystemPkgUpdated) {
8512if (REFACTOR_DEBUG) {
8513Slog.e("TODD",
8514        "Disable child packages");
8515}
8516                    final int scannedChildCount = (pkg.childPackages != null)
8517                            ? pkg.childPackages.size() : 0;
8518                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8519                            ? disabledPkgSetting.childPackageNames.size() : 0;
8520                    for (int i = 0; i < disabledChildCount; i++) {
8521                        String disabledChildPackageName =
8522                                disabledPkgSetting.childPackageNames.get(i);
8523                        boolean disabledPackageAvailable = false;
8524                        for (int j = 0; j < scannedChildCount; j++) {
8525                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8526                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8527if (REFACTOR_DEBUG) {
8528Slog.e("TODD",
8529        "Ignore " + disabledChildPackageName);
8530}
8531                                disabledPackageAvailable = true;
8532                                break;
8533                            }
8534                        }
8535                        if (!disabledPackageAvailable) {
8536if (REFACTOR_DEBUG) {
8537Slog.e("TODD",
8538        "Disable " + disabledChildPackageName);
8539}
8540                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8541                        }
8542                    }
8543                    // we're updating the disabled package, so, scan it as the package setting
8544                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8545                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8546                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8547                            (pkg == mPlatformPackage), user);
8548if (REFACTOR_DEBUG) {
8549Slog.e("TODD",
8550        "Scan disabled system package");
8551Slog.e("TODD",
8552        "Pre: " + request.pkgSetting.dumpState_temp());
8553}
8554final ScanResult result =
8555                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8556if (REFACTOR_DEBUG) {
8557Slog.e("TODD",
8558        "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan"));
8559}
8560                }
8561            }
8562        }
8563
8564        final boolean newPkgChangedPaths =
8565                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8566if (REFACTOR_DEBUG) {
8567Slog.e("TODD",
8568        "paths changed? " + newPkgChangedPaths
8569        + "; old: " + pkg.codePath
8570        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString));
8571}
8572        final boolean newPkgVersionGreater =
8573                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8574if (REFACTOR_DEBUG) {
8575Slog.e("TODD",
8576        "version greater? " + newPkgVersionGreater
8577        + "; old: " + pkg.getLongVersionCode()
8578        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode));
8579}
8580        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8581                && newPkgChangedPaths && newPkgVersionGreater;
8582if (REFACTOR_DEBUG) {
8583    Slog.e("TODD",
8584            "system better? " + isSystemPkgBetter);
8585}
8586        if (isSystemPkgBetter) {
8587            // The version of the application on /system is greater than the version on
8588            // /data. Switch back to the application on /system.
8589            // It's safe to assume the application on /system will correctly scan. If not,
8590            // there won't be a working copy of the application.
8591            synchronized (mPackages) {
8592                // just remove the loaded entries from package lists
8593                mPackages.remove(pkgSetting.name);
8594            }
8595
8596            logCriticalInfo(Log.WARN,
8597                    "System package updated;"
8598                    + " name: " + pkgSetting.name
8599                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8600                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8601if (REFACTOR_DEBUG) {
8602Slog.e("TODD",
8603        "System package changed;"
8604        + " name: " + pkgSetting.name
8605        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8606        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8607}
8608
8609            final InstallArgs args = createInstallArgsForExisting(
8610                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8611                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8612            args.cleanUpResourcesLI();
8613            synchronized (mPackages) {
8614                mSettings.enableSystemPackageLPw(pkgSetting.name);
8615            }
8616        }
8617
8618        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8619if (REFACTOR_DEBUG) {
8620Slog.e("TODD",
8621        "THROW exception; system pkg version not good enough");
8622}
8623            // The version of the application on the /system partition is less than or
8624            // equal to the version on the /data partition. Throw an exception and use
8625            // the application already installed on the /data partition.
8626            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8627                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8628                    + " better than this " + pkg.getLongVersionCode());
8629        }
8630
8631        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8632        // force the verification. Full apk verification will happen unless apk verity is set up for
8633        // the file. In that case, only small part of the apk is verified upfront.
8634        collectCertificatesLI(pkgSetting, pkg, parseFlags,
8635                PackageManagerServiceUtils.isApkVerificationForced(disabledPkgSetting));
8636
8637        boolean shouldHideSystemApp = false;
8638        // A new application appeared on /system, but, we already have a copy of
8639        // the application installed on /data.
8640        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8641                && !pkgSetting.isSystem()) {
8642            // if the signatures don't match, wipe the installed application and its data
8643            if (compareSignatures(pkgSetting.signatures.mSigningDetails.signatures,
8644                    pkg.mSigningDetails.signatures)
8645                            != PackageManager.SIGNATURE_MATCH) {
8646                logCriticalInfo(Log.WARN,
8647                        "System package signature mismatch;"
8648                        + " name: " + pkgSetting.name);
8649if (REFACTOR_DEBUG) {
8650Slog.e("TODD",
8651        "System package signature mismatch;"
8652        + " name: " + pkgSetting.name);
8653}
8654                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8655                        "scanPackageInternalLI")) {
8656                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8657                }
8658                pkgSetting = null;
8659            } else if (newPkgVersionGreater) {
8660                // The application on /system is newer than the application on /data.
8661                // Simply remove the application on /data [keeping application data]
8662                // and replace it with the version on /system.
8663                logCriticalInfo(Log.WARN,
8664                        "System package enabled;"
8665                        + " name: " + pkgSetting.name
8666                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8667                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8668if (REFACTOR_DEBUG) {
8669Slog.e("TODD",
8670        "System package enabled;"
8671        + " name: " + pkgSetting.name
8672        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8673        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8674}
8675                InstallArgs args = createInstallArgsForExisting(
8676                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8677                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8678                synchronized (mInstallLock) {
8679                    args.cleanUpResourcesLI();
8680                }
8681            } else {
8682                // The application on /system is older than the application on /data. Hide
8683                // the application on /system and the version on /data will be scanned later
8684                // and re-added like an update.
8685                shouldHideSystemApp = true;
8686                logCriticalInfo(Log.INFO,
8687                        "System package disabled;"
8688                        + " name: " + pkgSetting.name
8689                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8690                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8691if (REFACTOR_DEBUG) {
8692Slog.e("TODD",
8693        "System package disabled;"
8694        + " name: " + pkgSetting.name
8695        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8696        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8697}
8698            }
8699        }
8700
8701if (REFACTOR_DEBUG) {
8702Slog.e("TODD",
8703        "Scan package");
8704Slog.e("TODD",
8705        "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8706}
8707        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8708                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8709if (REFACTOR_DEBUG) {
8710pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8711Slog.e("TODD",
8712        "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8713}
8714
8715        if (shouldHideSystemApp) {
8716if (REFACTOR_DEBUG) {
8717Slog.e("TODD",
8718        "Disable package: " + pkg.packageName);
8719}
8720            synchronized (mPackages) {
8721                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8722            }
8723        }
8724        return scannedPkg;
8725    }
8726
8727    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8728        // Derive the new package synthetic package name
8729        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8730                + pkg.staticSharedLibVersion);
8731    }
8732
8733    private static String fixProcessName(String defProcessName,
8734            String processName) {
8735        if (processName == null) {
8736            return defProcessName;
8737        }
8738        return processName;
8739    }
8740
8741    /**
8742     * Enforces that only the system UID or root's UID can call a method exposed
8743     * via Binder.
8744     *
8745     * @param message used as message if SecurityException is thrown
8746     * @throws SecurityException if the caller is not system or root
8747     */
8748    private static final void enforceSystemOrRoot(String message) {
8749        final int uid = Binder.getCallingUid();
8750        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8751            throw new SecurityException(message);
8752        }
8753    }
8754
8755    @Override
8756    public void performFstrimIfNeeded() {
8757        enforceSystemOrRoot("Only the system can request fstrim");
8758
8759        // Before everything else, see whether we need to fstrim.
8760        try {
8761            IStorageManager sm = PackageHelper.getStorageManager();
8762            if (sm != null) {
8763                boolean doTrim = false;
8764                final long interval = android.provider.Settings.Global.getLong(
8765                        mContext.getContentResolver(),
8766                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8767                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8768                if (interval > 0) {
8769                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8770                    if (timeSinceLast > interval) {
8771                        doTrim = true;
8772                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8773                                + "; running immediately");
8774                    }
8775                }
8776                if (doTrim) {
8777                    final boolean dexOptDialogShown;
8778                    synchronized (mPackages) {
8779                        dexOptDialogShown = mDexOptDialogShown;
8780                    }
8781                    if (!isFirstBoot() && dexOptDialogShown) {
8782                        try {
8783                            ActivityManager.getService().showBootMessage(
8784                                    mContext.getResources().getString(
8785                                            R.string.android_upgrading_fstrim), true);
8786                        } catch (RemoteException e) {
8787                        }
8788                    }
8789                    sm.runMaintenance();
8790                }
8791            } else {
8792                Slog.e(TAG, "storageManager service unavailable!");
8793            }
8794        } catch (RemoteException e) {
8795            // Can't happen; StorageManagerService is local
8796        }
8797    }
8798
8799    @Override
8800    public void updatePackagesIfNeeded() {
8801        enforceSystemOrRoot("Only the system can request package update");
8802
8803        // We need to re-extract after an OTA.
8804        boolean causeUpgrade = isUpgrade();
8805
8806        // First boot or factory reset.
8807        // Note: we also handle devices that are upgrading to N right now as if it is their
8808        //       first boot, as they do not have profile data.
8809        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8810
8811        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8812        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8813
8814        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8815            return;
8816        }
8817
8818        List<PackageParser.Package> pkgs;
8819        synchronized (mPackages) {
8820            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8821        }
8822
8823        final long startTime = System.nanoTime();
8824        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8825                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8826                    false /* bootComplete */);
8827
8828        final int elapsedTimeSeconds =
8829                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8830
8831        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8832        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8833        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8834        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8835        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8836    }
8837
8838    /*
8839     * Return the prebuilt profile path given a package base code path.
8840     */
8841    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8842        return pkg.baseCodePath + ".prof";
8843    }
8844
8845    /**
8846     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8847     * containing statistics about the invocation. The array consists of three elements,
8848     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8849     * and {@code numberOfPackagesFailed}.
8850     */
8851    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8852            final String compilerFilter, boolean bootComplete) {
8853
8854        int numberOfPackagesVisited = 0;
8855        int numberOfPackagesOptimized = 0;
8856        int numberOfPackagesSkipped = 0;
8857        int numberOfPackagesFailed = 0;
8858        final int numberOfPackagesToDexopt = pkgs.size();
8859
8860        for (PackageParser.Package pkg : pkgs) {
8861            numberOfPackagesVisited++;
8862
8863            boolean useProfileForDexopt = false;
8864
8865            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8866                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8867                // that are already compiled.
8868                File profileFile = new File(getPrebuildProfilePath(pkg));
8869                // Copy profile if it exists.
8870                if (profileFile.exists()) {
8871                    try {
8872                        // We could also do this lazily before calling dexopt in
8873                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8874                        // is that we don't have a good way to say "do this only once".
8875                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8876                                pkg.applicationInfo.uid, pkg.packageName)) {
8877                            Log.e(TAG, "Installer failed to copy system profile!");
8878                        } else {
8879                            // Disabled as this causes speed-profile compilation during first boot
8880                            // even if things are already compiled.
8881                            // useProfileForDexopt = true;
8882                        }
8883                    } catch (Exception e) {
8884                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8885                                e);
8886                    }
8887                } else {
8888                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8889                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8890                    // minimize the number off apps being speed-profile compiled during first boot.
8891                    // The other paths will not change the filter.
8892                    if (disabledPs != null && disabledPs.pkg.isStub) {
8893                        // The package is the stub one, remove the stub suffix to get the normal
8894                        // package and APK names.
8895                        String systemProfilePath =
8896                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8897                        profileFile = new File(systemProfilePath);
8898                        // If we have a profile for a compressed APK, copy it to the reference
8899                        // location.
8900                        // Note that copying the profile here will cause it to override the
8901                        // reference profile every OTA even though the existing reference profile
8902                        // may have more data. We can't copy during decompression since the
8903                        // directories are not set up at that point.
8904                        if (profileFile.exists()) {
8905                            try {
8906                                // We could also do this lazily before calling dexopt in
8907                                // PackageDexOptimizer to prevent this happening on first boot. The
8908                                // issue is that we don't have a good way to say "do this only
8909                                // once".
8910                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8911                                        pkg.applicationInfo.uid, pkg.packageName)) {
8912                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8913                                } else {
8914                                    useProfileForDexopt = true;
8915                                }
8916                            } catch (Exception e) {
8917                                Log.e(TAG, "Failed to copy profile " +
8918                                        profileFile.getAbsolutePath() + " ", e);
8919                            }
8920                        }
8921                    }
8922                }
8923            }
8924
8925            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8926                if (DEBUG_DEXOPT) {
8927                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8928                }
8929                numberOfPackagesSkipped++;
8930                continue;
8931            }
8932
8933            if (DEBUG_DEXOPT) {
8934                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8935                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8936            }
8937
8938            if (showDialog) {
8939                try {
8940                    ActivityManager.getService().showBootMessage(
8941                            mContext.getResources().getString(R.string.android_upgrading_apk,
8942                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8943                } catch (RemoteException e) {
8944                }
8945                synchronized (mPackages) {
8946                    mDexOptDialogShown = true;
8947                }
8948            }
8949
8950            String pkgCompilerFilter = compilerFilter;
8951            if (useProfileForDexopt) {
8952                // Use background dexopt mode to try and use the profile. Note that this does not
8953                // guarantee usage of the profile.
8954                pkgCompilerFilter =
8955                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8956                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8957            }
8958
8959            // checkProfiles is false to avoid merging profiles during boot which
8960            // might interfere with background compilation (b/28612421).
8961            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8962            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8963            // trade-off worth doing to save boot time work.
8964            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8965            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8966                    pkg.packageName,
8967                    pkgCompilerFilter,
8968                    dexoptFlags));
8969
8970            switch (primaryDexOptStaus) {
8971                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8972                    numberOfPackagesOptimized++;
8973                    break;
8974                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8975                    numberOfPackagesSkipped++;
8976                    break;
8977                case PackageDexOptimizer.DEX_OPT_FAILED:
8978                    numberOfPackagesFailed++;
8979                    break;
8980                default:
8981                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8982                    break;
8983            }
8984        }
8985
8986        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8987                numberOfPackagesFailed };
8988    }
8989
8990    @Override
8991    public void notifyPackageUse(String packageName, int reason) {
8992        synchronized (mPackages) {
8993            final int callingUid = Binder.getCallingUid();
8994            final int callingUserId = UserHandle.getUserId(callingUid);
8995            if (getInstantAppPackageName(callingUid) != null) {
8996                if (!isCallerSameApp(packageName, callingUid)) {
8997                    return;
8998                }
8999            } else {
9000                if (isInstantApp(packageName, callingUserId)) {
9001                    return;
9002                }
9003            }
9004            notifyPackageUseLocked(packageName, reason);
9005        }
9006    }
9007
9008    private void notifyPackageUseLocked(String packageName, int reason) {
9009        final PackageParser.Package p = mPackages.get(packageName);
9010        if (p == null) {
9011            return;
9012        }
9013        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9014    }
9015
9016    @Override
9017    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9018            List<String> classPaths, String loaderIsa) {
9019        int userId = UserHandle.getCallingUserId();
9020        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9021        if (ai == null) {
9022            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9023                + loadingPackageName + ", user=" + userId);
9024            return;
9025        }
9026        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9027    }
9028
9029    @Override
9030    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9031            IDexModuleRegisterCallback callback) {
9032        int userId = UserHandle.getCallingUserId();
9033        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9034        DexManager.RegisterDexModuleResult result;
9035        if (ai == null) {
9036            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9037                     " calling user. package=" + packageName + ", user=" + userId);
9038            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9039        } else {
9040            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9041        }
9042
9043        if (callback != null) {
9044            mHandler.post(() -> {
9045                try {
9046                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9047                } catch (RemoteException e) {
9048                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9049                }
9050            });
9051        }
9052    }
9053
9054    /**
9055     * Ask the package manager to perform a dex-opt with the given compiler filter.
9056     *
9057     * Note: exposed only for the shell command to allow moving packages explicitly to a
9058     *       definite state.
9059     */
9060    @Override
9061    public boolean performDexOptMode(String packageName,
9062            boolean checkProfiles, String targetCompilerFilter, boolean force,
9063            boolean bootComplete, String splitName) {
9064        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9065                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9066                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9067        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9068                splitName, flags));
9069    }
9070
9071    /**
9072     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9073     * secondary dex files belonging to the given package.
9074     *
9075     * Note: exposed only for the shell command to allow moving packages explicitly to a
9076     *       definite state.
9077     */
9078    @Override
9079    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9080            boolean force) {
9081        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9082                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9083                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9084                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9085        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9086    }
9087
9088    /*package*/ boolean performDexOpt(DexoptOptions options) {
9089        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9090            return false;
9091        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9092            return false;
9093        }
9094
9095        if (options.isDexoptOnlySecondaryDex()) {
9096            return mDexManager.dexoptSecondaryDex(options);
9097        } else {
9098            int dexoptStatus = performDexOptWithStatus(options);
9099            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9100        }
9101    }
9102
9103    /**
9104     * Perform dexopt on the given package and return one of following result:
9105     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9106     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9107     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9108     */
9109    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9110        return performDexOptTraced(options);
9111    }
9112
9113    private int performDexOptTraced(DexoptOptions options) {
9114        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9115        try {
9116            return performDexOptInternal(options);
9117        } finally {
9118            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9119        }
9120    }
9121
9122    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9123    // if the package can now be considered up to date for the given filter.
9124    private int performDexOptInternal(DexoptOptions options) {
9125        PackageParser.Package p;
9126        synchronized (mPackages) {
9127            p = mPackages.get(options.getPackageName());
9128            if (p == null) {
9129                // Package could not be found. Report failure.
9130                return PackageDexOptimizer.DEX_OPT_FAILED;
9131            }
9132            mPackageUsage.maybeWriteAsync(mPackages);
9133            mCompilerStats.maybeWriteAsync();
9134        }
9135        long callingId = Binder.clearCallingIdentity();
9136        try {
9137            synchronized (mInstallLock) {
9138                return performDexOptInternalWithDependenciesLI(p, options);
9139            }
9140        } finally {
9141            Binder.restoreCallingIdentity(callingId);
9142        }
9143    }
9144
9145    public ArraySet<String> getOptimizablePackages() {
9146        ArraySet<String> pkgs = new ArraySet<String>();
9147        synchronized (mPackages) {
9148            for (PackageParser.Package p : mPackages.values()) {
9149                if (PackageDexOptimizer.canOptimizePackage(p)) {
9150                    pkgs.add(p.packageName);
9151                }
9152            }
9153        }
9154        return pkgs;
9155    }
9156
9157    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9158            DexoptOptions options) {
9159        // Select the dex optimizer based on the force parameter.
9160        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9161        //       allocate an object here.
9162        PackageDexOptimizer pdo = options.isForce()
9163                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9164                : mPackageDexOptimizer;
9165
9166        // Dexopt all dependencies first. Note: we ignore the return value and march on
9167        // on errors.
9168        // Note that we are going to call performDexOpt on those libraries as many times as
9169        // they are referenced in packages. When we do a batch of performDexOpt (for example
9170        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9171        // and the first package that uses the library will dexopt it. The
9172        // others will see that the compiled code for the library is up to date.
9173        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9174        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9175        if (!deps.isEmpty()) {
9176            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9177                    options.getCompilerFilter(), options.getSplitName(),
9178                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9179            for (PackageParser.Package depPackage : deps) {
9180                // TODO: Analyze and investigate if we (should) profile libraries.
9181                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9182                        getOrCreateCompilerPackageStats(depPackage),
9183                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9184            }
9185        }
9186        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9187                getOrCreateCompilerPackageStats(p),
9188                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9189    }
9190
9191    /**
9192     * Reconcile the information we have about the secondary dex files belonging to
9193     * {@code packagName} and the actual dex files. For all dex files that were
9194     * deleted, update the internal records and delete the generated oat files.
9195     */
9196    @Override
9197    public void reconcileSecondaryDexFiles(String packageName) {
9198        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9199            return;
9200        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9201            return;
9202        }
9203        mDexManager.reconcileSecondaryDexFiles(packageName);
9204    }
9205
9206    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9207    // a reference there.
9208    /*package*/ DexManager getDexManager() {
9209        return mDexManager;
9210    }
9211
9212    /**
9213     * Execute the background dexopt job immediately.
9214     */
9215    @Override
9216    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9217        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9218            return false;
9219        }
9220        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9221    }
9222
9223    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9224        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9225                || p.usesStaticLibraries != null) {
9226            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9227            Set<String> collectedNames = new HashSet<>();
9228            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9229
9230            retValue.remove(p);
9231
9232            return retValue;
9233        } else {
9234            return Collections.emptyList();
9235        }
9236    }
9237
9238    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9239            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9240        if (!collectedNames.contains(p.packageName)) {
9241            collectedNames.add(p.packageName);
9242            collected.add(p);
9243
9244            if (p.usesLibraries != null) {
9245                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9246                        null, collected, collectedNames);
9247            }
9248            if (p.usesOptionalLibraries != null) {
9249                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9250                        null, collected, collectedNames);
9251            }
9252            if (p.usesStaticLibraries != null) {
9253                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9254                        p.usesStaticLibrariesVersions, collected, collectedNames);
9255            }
9256        }
9257    }
9258
9259    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9260            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9261        final int libNameCount = libs.size();
9262        for (int i = 0; i < libNameCount; i++) {
9263            String libName = libs.get(i);
9264            long version = (versions != null && versions.length == libNameCount)
9265                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9266            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9267            if (libPkg != null) {
9268                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9269            }
9270        }
9271    }
9272
9273    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9274        synchronized (mPackages) {
9275            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9276            if (libEntry != null) {
9277                return mPackages.get(libEntry.apk);
9278            }
9279            return null;
9280        }
9281    }
9282
9283    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9284        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9285        if (versionedLib == null) {
9286            return null;
9287        }
9288        return versionedLib.get(version);
9289    }
9290
9291    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9292        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9293                pkg.staticSharedLibName);
9294        if (versionedLib == null) {
9295            return null;
9296        }
9297        long previousLibVersion = -1;
9298        final int versionCount = versionedLib.size();
9299        for (int i = 0; i < versionCount; i++) {
9300            final long libVersion = versionedLib.keyAt(i);
9301            if (libVersion < pkg.staticSharedLibVersion) {
9302                previousLibVersion = Math.max(previousLibVersion, libVersion);
9303            }
9304        }
9305        if (previousLibVersion >= 0) {
9306            return versionedLib.get(previousLibVersion);
9307        }
9308        return null;
9309    }
9310
9311    public void shutdown() {
9312        mPackageUsage.writeNow(mPackages);
9313        mCompilerStats.writeNow();
9314        mDexManager.writePackageDexUsageNow();
9315    }
9316
9317    @Override
9318    public void dumpProfiles(String packageName) {
9319        PackageParser.Package pkg;
9320        synchronized (mPackages) {
9321            pkg = mPackages.get(packageName);
9322            if (pkg == null) {
9323                throw new IllegalArgumentException("Unknown package: " + packageName);
9324            }
9325        }
9326        /* Only the shell, root, or the app user should be able to dump profiles. */
9327        int callingUid = Binder.getCallingUid();
9328        if (callingUid != Process.SHELL_UID &&
9329            callingUid != Process.ROOT_UID &&
9330            callingUid != pkg.applicationInfo.uid) {
9331            throw new SecurityException("dumpProfiles");
9332        }
9333
9334        synchronized (mInstallLock) {
9335            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9336            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9337            try {
9338                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9339                String codePaths = TextUtils.join(";", allCodePaths);
9340                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9341            } catch (InstallerException e) {
9342                Slog.w(TAG, "Failed to dump profiles", e);
9343            }
9344            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9345        }
9346    }
9347
9348    @Override
9349    public void forceDexOpt(String packageName) {
9350        enforceSystemOrRoot("forceDexOpt");
9351
9352        PackageParser.Package pkg;
9353        synchronized (mPackages) {
9354            pkg = mPackages.get(packageName);
9355            if (pkg == null) {
9356                throw new IllegalArgumentException("Unknown package: " + packageName);
9357            }
9358        }
9359
9360        synchronized (mInstallLock) {
9361            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9362
9363            // Whoever is calling forceDexOpt wants a compiled package.
9364            // Don't use profiles since that may cause compilation to be skipped.
9365            final int res = performDexOptInternalWithDependenciesLI(
9366                    pkg,
9367                    new DexoptOptions(packageName,
9368                            getDefaultCompilerFilter(),
9369                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9370
9371            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9372            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9373                throw new IllegalStateException("Failed to dexopt: " + res);
9374            }
9375        }
9376    }
9377
9378    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9379        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9380            Slog.w(TAG, "Unable to update from " + oldPkg.name
9381                    + " to " + newPkg.packageName
9382                    + ": old package not in system partition");
9383            return false;
9384        } else if (mPackages.get(oldPkg.name) != null) {
9385            Slog.w(TAG, "Unable to update from " + oldPkg.name
9386                    + " to " + newPkg.packageName
9387                    + ": old package still exists");
9388            return false;
9389        }
9390        return true;
9391    }
9392
9393    void removeCodePathLI(File codePath) {
9394        if (codePath.isDirectory()) {
9395            try {
9396                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9397            } catch (InstallerException e) {
9398                Slog.w(TAG, "Failed to remove code path", e);
9399            }
9400        } else {
9401            codePath.delete();
9402        }
9403    }
9404
9405    private int[] resolveUserIds(int userId) {
9406        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9407    }
9408
9409    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9410        if (pkg == null) {
9411            Slog.wtf(TAG, "Package was null!", new Throwable());
9412            return;
9413        }
9414        clearAppDataLeafLIF(pkg, userId, flags);
9415        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9416        for (int i = 0; i < childCount; i++) {
9417            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9418        }
9419    }
9420
9421    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9422        final PackageSetting ps;
9423        synchronized (mPackages) {
9424            ps = mSettings.mPackages.get(pkg.packageName);
9425        }
9426        for (int realUserId : resolveUserIds(userId)) {
9427            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9428            try {
9429                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9430                        ceDataInode);
9431            } catch (InstallerException e) {
9432                Slog.w(TAG, String.valueOf(e));
9433            }
9434        }
9435    }
9436
9437    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9438        if (pkg == null) {
9439            Slog.wtf(TAG, "Package was null!", new Throwable());
9440            return;
9441        }
9442        destroyAppDataLeafLIF(pkg, userId, flags);
9443        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9444        for (int i = 0; i < childCount; i++) {
9445            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9446        }
9447    }
9448
9449    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9450        final PackageSetting ps;
9451        synchronized (mPackages) {
9452            ps = mSettings.mPackages.get(pkg.packageName);
9453        }
9454        for (int realUserId : resolveUserIds(userId)) {
9455            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9456            try {
9457                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9458                        ceDataInode);
9459            } catch (InstallerException e) {
9460                Slog.w(TAG, String.valueOf(e));
9461            }
9462            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9463        }
9464    }
9465
9466    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9467        if (pkg == null) {
9468            Slog.wtf(TAG, "Package was null!", new Throwable());
9469            return;
9470        }
9471        destroyAppProfilesLeafLIF(pkg);
9472        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9473        for (int i = 0; i < childCount; i++) {
9474            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9475        }
9476    }
9477
9478    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9479        try {
9480            mInstaller.destroyAppProfiles(pkg.packageName);
9481        } catch (InstallerException e) {
9482            Slog.w(TAG, String.valueOf(e));
9483        }
9484    }
9485
9486    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9487        if (pkg == null) {
9488            Slog.wtf(TAG, "Package was null!", new Throwable());
9489            return;
9490        }
9491        clearAppProfilesLeafLIF(pkg);
9492        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9493        for (int i = 0; i < childCount; i++) {
9494            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9495        }
9496    }
9497
9498    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9499        try {
9500            mInstaller.clearAppProfiles(pkg.packageName);
9501        } catch (InstallerException e) {
9502            Slog.w(TAG, String.valueOf(e));
9503        }
9504    }
9505
9506    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9507            long lastUpdateTime) {
9508        // Set parent install/update time
9509        PackageSetting ps = (PackageSetting) pkg.mExtras;
9510        if (ps != null) {
9511            ps.firstInstallTime = firstInstallTime;
9512            ps.lastUpdateTime = lastUpdateTime;
9513        }
9514        // Set children install/update time
9515        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9516        for (int i = 0; i < childCount; i++) {
9517            PackageParser.Package childPkg = pkg.childPackages.get(i);
9518            ps = (PackageSetting) childPkg.mExtras;
9519            if (ps != null) {
9520                ps.firstInstallTime = firstInstallTime;
9521                ps.lastUpdateTime = lastUpdateTime;
9522            }
9523        }
9524    }
9525
9526    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9527            SharedLibraryEntry file,
9528            PackageParser.Package changingLib) {
9529        if (file.path != null) {
9530            usesLibraryFiles.add(file.path);
9531            return;
9532        }
9533        PackageParser.Package p = mPackages.get(file.apk);
9534        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9535            // If we are doing this while in the middle of updating a library apk,
9536            // then we need to make sure to use that new apk for determining the
9537            // dependencies here.  (We haven't yet finished committing the new apk
9538            // to the package manager state.)
9539            if (p == null || p.packageName.equals(changingLib.packageName)) {
9540                p = changingLib;
9541            }
9542        }
9543        if (p != null) {
9544            usesLibraryFiles.addAll(p.getAllCodePaths());
9545            if (p.usesLibraryFiles != null) {
9546                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9547            }
9548        }
9549    }
9550
9551    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9552            PackageParser.Package changingLib) throws PackageManagerException {
9553        if (pkg == null) {
9554            return;
9555        }
9556        // The collection used here must maintain the order of addition (so
9557        // that libraries are searched in the correct order) and must have no
9558        // duplicates.
9559        Set<String> usesLibraryFiles = null;
9560        if (pkg.usesLibraries != null) {
9561            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9562                    null, null, pkg.packageName, changingLib, true,
9563                    pkg.applicationInfo.targetSdkVersion, null);
9564        }
9565        if (pkg.usesStaticLibraries != null) {
9566            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9567                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9568                    pkg.packageName, changingLib, true,
9569                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9570        }
9571        if (pkg.usesOptionalLibraries != null) {
9572            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9573                    null, null, pkg.packageName, changingLib, false,
9574                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9575        }
9576        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9577            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9578        } else {
9579            pkg.usesLibraryFiles = null;
9580        }
9581    }
9582
9583    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9584            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9585            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9586            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9587            throws PackageManagerException {
9588        final int libCount = requestedLibraries.size();
9589        for (int i = 0; i < libCount; i++) {
9590            final String libName = requestedLibraries.get(i);
9591            final long libVersion = requiredVersions != null ? requiredVersions[i]
9592                    : SharedLibraryInfo.VERSION_UNDEFINED;
9593            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9594            if (libEntry == null) {
9595                if (required) {
9596                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9597                            "Package " + packageName + " requires unavailable shared library "
9598                                    + libName + "; failing!");
9599                } else if (DEBUG_SHARED_LIBRARIES) {
9600                    Slog.i(TAG, "Package " + packageName
9601                            + " desires unavailable shared library "
9602                            + libName + "; ignoring!");
9603                }
9604            } else {
9605                if (requiredVersions != null && requiredCertDigests != null) {
9606                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9607                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9608                            "Package " + packageName + " requires unavailable static shared"
9609                                    + " library " + libName + " version "
9610                                    + libEntry.info.getLongVersion() + "; failing!");
9611                    }
9612
9613                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9614                    if (libPkg == null) {
9615                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9616                                "Package " + packageName + " requires unavailable static shared"
9617                                        + " library; failing!");
9618                    }
9619
9620                    final String[] expectedCertDigests = requiredCertDigests[i];
9621                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9622                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9623                            ? PackageUtils.computeSignaturesSha256Digests(
9624                            libPkg.mSigningDetails.signatures)
9625                            : PackageUtils.computeSignaturesSha256Digests(
9626                                    new Signature[]{libPkg.mSigningDetails.signatures[0]});
9627
9628                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9629                    // target O we don't parse the "additional-certificate" tags similarly
9630                    // how we only consider all certs only for apps targeting O (see above).
9631                    // Therefore, the size check is safe to make.
9632                    if (expectedCertDigests.length != libCertDigests.length) {
9633                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9634                                "Package " + packageName + " requires differently signed" +
9635                                        " static shared library; failing!");
9636                    }
9637
9638                    // Use a predictable order as signature order may vary
9639                    Arrays.sort(libCertDigests);
9640                    Arrays.sort(expectedCertDigests);
9641
9642                    final int certCount = libCertDigests.length;
9643                    for (int j = 0; j < certCount; j++) {
9644                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9645                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9646                                    "Package " + packageName + " requires differently signed" +
9647                                            " static shared library; failing!");
9648                        }
9649                    }
9650                }
9651
9652                if (outUsedLibraries == null) {
9653                    // Use LinkedHashSet to preserve the order of files added to
9654                    // usesLibraryFiles while eliminating duplicates.
9655                    outUsedLibraries = new LinkedHashSet<>();
9656                }
9657                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9658            }
9659        }
9660        return outUsedLibraries;
9661    }
9662
9663    private static boolean hasString(List<String> list, List<String> which) {
9664        if (list == null) {
9665            return false;
9666        }
9667        for (int i=list.size()-1; i>=0; i--) {
9668            for (int j=which.size()-1; j>=0; j--) {
9669                if (which.get(j).equals(list.get(i))) {
9670                    return true;
9671                }
9672            }
9673        }
9674        return false;
9675    }
9676
9677    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9678            PackageParser.Package changingPkg) {
9679        ArrayList<PackageParser.Package> res = null;
9680        for (PackageParser.Package pkg : mPackages.values()) {
9681            if (changingPkg != null
9682                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9683                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9684                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9685                            changingPkg.staticSharedLibName)) {
9686                return null;
9687            }
9688            if (res == null) {
9689                res = new ArrayList<>();
9690            }
9691            res.add(pkg);
9692            try {
9693                updateSharedLibrariesLPr(pkg, changingPkg);
9694            } catch (PackageManagerException e) {
9695                // If a system app update or an app and a required lib missing we
9696                // delete the package and for updated system apps keep the data as
9697                // it is better for the user to reinstall than to be in an limbo
9698                // state. Also libs disappearing under an app should never happen
9699                // - just in case.
9700                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9701                    final int flags = pkg.isUpdatedSystemApp()
9702                            ? PackageManager.DELETE_KEEP_DATA : 0;
9703                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9704                            flags , null, true, null);
9705                }
9706                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9707            }
9708        }
9709        return res;
9710    }
9711
9712    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9713            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9714            @Nullable UserHandle user) throws PackageManagerException {
9715        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9716        // If the package has children and this is the first dive in the function
9717        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9718        // whether all packages (parent and children) would be successfully scanned
9719        // before the actual scan since scanning mutates internal state and we want
9720        // to atomically install the package and its children.
9721        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9722            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9723                scanFlags |= SCAN_CHECK_ONLY;
9724            }
9725        } else {
9726            scanFlags &= ~SCAN_CHECK_ONLY;
9727        }
9728
9729        final PackageParser.Package scannedPkg;
9730        try {
9731            // Scan the parent
9732            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9733            // Scan the children
9734            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9735            for (int i = 0; i < childCount; i++) {
9736                PackageParser.Package childPkg = pkg.childPackages.get(i);
9737                scanPackageNewLI(childPkg, parseFlags,
9738                        scanFlags, currentTime, user);
9739            }
9740        } finally {
9741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9742        }
9743
9744        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9745            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9746        }
9747
9748        return scannedPkg;
9749    }
9750
9751    /** The result of a package scan. */
9752    private static class ScanResult {
9753        /** Whether or not the package scan was successful */
9754        public final boolean success;
9755        /**
9756         * The final package settings. This may be the same object passed in
9757         * the {@link ScanRequest}, but, with modified values.
9758         */
9759        @Nullable public final PackageSetting pkgSetting;
9760        /** ABI code paths that have changed in the package scan */
9761        @Nullable public final List<String> changedAbiCodePath;
9762        public ScanResult(
9763                boolean success,
9764                @Nullable PackageSetting pkgSetting,
9765                @Nullable List<String> changedAbiCodePath) {
9766            this.success = success;
9767            this.pkgSetting = pkgSetting;
9768            this.changedAbiCodePath = changedAbiCodePath;
9769        }
9770    }
9771
9772    /** A package to be scanned */
9773    private static class ScanRequest {
9774        /** The parsed package */
9775        @NonNull public final PackageParser.Package pkg;
9776        /** Shared user settings, if the package has a shared user */
9777        @Nullable public final SharedUserSetting sharedUserSetting;
9778        /**
9779         * Package settings of the currently installed version.
9780         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9781         * during scan.
9782         */
9783        @Nullable public final PackageSetting pkgSetting;
9784        /** A copy of the settings for the currently installed version */
9785        @Nullable public final PackageSetting oldPkgSetting;
9786        /** Package settings for the disabled version on the /system partition */
9787        @Nullable public final PackageSetting disabledPkgSetting;
9788        /** Package settings for the installed version under its original package name */
9789        @Nullable public final PackageSetting originalPkgSetting;
9790        /** The real package name of a renamed application */
9791        @Nullable public final String realPkgName;
9792        public final @ParseFlags int parseFlags;
9793        public final @ScanFlags int scanFlags;
9794        /** The user for which the package is being scanned */
9795        @Nullable public final UserHandle user;
9796        /** Whether or not the platform package is being scanned */
9797        public final boolean isPlatformPackage;
9798        public ScanRequest(
9799                @NonNull PackageParser.Package pkg,
9800                @Nullable SharedUserSetting sharedUserSetting,
9801                @Nullable PackageSetting pkgSetting,
9802                @Nullable PackageSetting disabledPkgSetting,
9803                @Nullable PackageSetting originalPkgSetting,
9804                @Nullable String realPkgName,
9805                @ParseFlags int parseFlags,
9806                @ScanFlags int scanFlags,
9807                boolean isPlatformPackage,
9808                @Nullable UserHandle user) {
9809            this.pkg = pkg;
9810            this.pkgSetting = pkgSetting;
9811            this.sharedUserSetting = sharedUserSetting;
9812            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9813            this.disabledPkgSetting = disabledPkgSetting;
9814            this.originalPkgSetting = originalPkgSetting;
9815            this.realPkgName = realPkgName;
9816            this.parseFlags = parseFlags;
9817            this.scanFlags = scanFlags;
9818            this.isPlatformPackage = isPlatformPackage;
9819            this.user = user;
9820        }
9821    }
9822
9823    /**
9824     * Returns the actual scan flags depending upon the state of the other settings.
9825     * <p>Updated system applications will not have the following flags set
9826     * by default and need to be adjusted after the fact:
9827     * <ul>
9828     * <li>{@link #SCAN_AS_SYSTEM}</li>
9829     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9830     * <li>{@link #SCAN_AS_OEM}</li>
9831     * <li>{@link #SCAN_AS_VENDOR}</li>
9832     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9833     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9834     * </ul>
9835     */
9836    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9837            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9838            PackageParser.Package pkg) {
9839        if (disabledPkgSetting != null) {
9840            // updated system application, must at least have SCAN_AS_SYSTEM
9841            scanFlags |= SCAN_AS_SYSTEM;
9842            if ((disabledPkgSetting.pkgPrivateFlags
9843                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9844                scanFlags |= SCAN_AS_PRIVILEGED;
9845            }
9846            if ((disabledPkgSetting.pkgPrivateFlags
9847                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9848                scanFlags |= SCAN_AS_OEM;
9849            }
9850            if ((disabledPkgSetting.pkgPrivateFlags
9851                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9852                scanFlags |= SCAN_AS_VENDOR;
9853            }
9854        }
9855        if (pkgSetting != null) {
9856            final int userId = ((user == null) ? 0 : user.getIdentifier());
9857            if (pkgSetting.getInstantApp(userId)) {
9858                scanFlags |= SCAN_AS_INSTANT_APP;
9859            }
9860            if (pkgSetting.getVirtulalPreload(userId)) {
9861                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9862            }
9863        }
9864
9865        // Scan as privileged apps that share a user with a priv-app.
9866        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9867                && (pkg.mSharedUserId != null)) {
9868            SharedUserSetting sharedUserSetting = null;
9869            try {
9870                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9871            } catch (PackageManagerException ignore) {}
9872            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9873                // Exempt SharedUsers signed with the platform key.
9874                // TODO(b/72378145) Fix this exemption. Force signature apps
9875                // to whitelist their privileged permissions just like other
9876                // priv-apps.
9877                synchronized (mPackages) {
9878                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9879                    if (!pkg.packageName.equals("android")
9880                            && (compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9881                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9882                        scanFlags |= SCAN_AS_PRIVILEGED;
9883                    }
9884                }
9885            }
9886        }
9887
9888        return scanFlags;
9889    }
9890
9891    @GuardedBy("mInstallLock")
9892    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9893            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9894            @Nullable UserHandle user) throws PackageManagerException {
9895
9896        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9897        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9898        if (realPkgName != null) {
9899            ensurePackageRenamed(pkg, renamedPkgName);
9900        }
9901        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9902        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9903        final PackageSetting disabledPkgSetting =
9904                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9905
9906        if (mTransferedPackages.contains(pkg.packageName)) {
9907            Slog.w(TAG, "Package " + pkg.packageName
9908                    + " was transferred to another, but its .apk remains");
9909        }
9910
9911        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9912        synchronized (mPackages) {
9913            applyPolicy(pkg, parseFlags, scanFlags);
9914            assertPackageIsValid(pkg, parseFlags, scanFlags);
9915
9916            SharedUserSetting sharedUserSetting = null;
9917            if (pkg.mSharedUserId != null) {
9918                // SIDE EFFECTS; may potentially allocate a new shared user
9919                sharedUserSetting = mSettings.getSharedUserLPw(
9920                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9921                if (DEBUG_PACKAGE_SCANNING) {
9922                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9923                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9924                                + " (uid=" + sharedUserSetting.userId + "):"
9925                                + " packages=" + sharedUserSetting.packages);
9926                }
9927            }
9928
9929            boolean scanSucceeded = false;
9930            try {
9931                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9932                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9933                        (pkg == mPlatformPackage), user);
9934                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9935                if (result.success) {
9936                    commitScanResultsLocked(request, result);
9937                }
9938                scanSucceeded = true;
9939            } finally {
9940                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9941                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9942                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9943                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9944                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9945                  }
9946            }
9947        }
9948        return pkg;
9949    }
9950
9951    /**
9952     * Commits the package scan and modifies system state.
9953     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9954     * of committing the package, leaving the system in an inconsistent state.
9955     * This needs to be fixed so, once we get to this point, no errors are
9956     * possible and the system is not left in an inconsistent state.
9957     */
9958    @GuardedBy("mPackages")
9959    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9960            throws PackageManagerException {
9961        final PackageParser.Package pkg = request.pkg;
9962        final @ParseFlags int parseFlags = request.parseFlags;
9963        final @ScanFlags int scanFlags = request.scanFlags;
9964        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9965        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9966        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
9967        final UserHandle user = request.user;
9968        final String realPkgName = request.realPkgName;
9969        final PackageSetting pkgSetting = result.pkgSetting;
9970        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9971        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9972
9973        if (newPkgSettingCreated) {
9974            if (originalPkgSetting != null) {
9975                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
9976            }
9977            // THROWS: when we can't allocate a user id. add call to check if there's
9978            // enough space to ensure we won't throw; otherwise, don't modify state
9979            mSettings.addUserToSettingLPw(pkgSetting);
9980
9981            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
9982                mTransferedPackages.add(originalPkgSetting.name);
9983            }
9984        }
9985        // TODO(toddke): Consider a method specifically for modifying the Package object
9986        // post scan; or, moving this stuff out of the Package object since it has nothing
9987        // to do with the package on disk.
9988        // We need to have this here because addUserToSettingLPw() is sometimes responsible
9989        // for creating the application ID. If we did this earlier, we would be saving the
9990        // correct ID.
9991        pkg.applicationInfo.uid = pkgSetting.appId;
9992
9993        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9994
9995        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
9996            mTransferedPackages.add(pkg.packageName);
9997        }
9998
9999        // THROWS: when requested libraries that can't be found. it only changes
10000        // the state of the passed in pkg object, so, move to the top of the method
10001        // and allow it to abort
10002        if ((scanFlags & SCAN_BOOTING) == 0
10003                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10004            // Check all shared libraries and map to their actual file path.
10005            // We only do this here for apps not on a system dir, because those
10006            // are the only ones that can fail an install due to this.  We
10007            // will take care of the system apps by updating all of their
10008            // library paths after the scan is done. Also during the initial
10009            // scan don't update any libs as we do this wholesale after all
10010            // apps are scanned to avoid dependency based scanning.
10011            updateSharedLibrariesLPr(pkg, null);
10012        }
10013
10014        // All versions of a static shared library are referenced with the same
10015        // package name. Internally, we use a synthetic package name to allow
10016        // multiple versions of the same shared library to be installed. So,
10017        // we need to generate the synthetic package name of the latest shared
10018        // library in order to compare signatures.
10019        PackageSetting signatureCheckPs = pkgSetting;
10020        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10021            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10022            if (libraryEntry != null) {
10023                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10024            }
10025        }
10026
10027        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10028        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10029            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10030                // We just determined the app is signed correctly, so bring
10031                // over the latest parsed certs.
10032                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10033            } else {
10034                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10035                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10036                            "Package " + pkg.packageName + " upgrade keys do not match the "
10037                                    + "previously installed version");
10038                } else {
10039                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10040                    String msg = "System package " + pkg.packageName
10041                            + " signature changed; retaining data.";
10042                    reportSettingsProblem(Log.WARN, msg);
10043                }
10044            }
10045        } else {
10046            try {
10047                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10048                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10049                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10050                        pkg.mSigningDetails, compareCompat, compareRecover);
10051                // The new KeySets will be re-added later in the scanning process.
10052                if (compatMatch) {
10053                    synchronized (mPackages) {
10054                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10055                    }
10056                }
10057                // We just determined the app is signed correctly, so bring
10058                // over the latest parsed certs.
10059                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10060            } catch (PackageManagerException e) {
10061                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10062                    throw e;
10063                }
10064                // The signature has changed, but this package is in the system
10065                // image...  let's recover!
10066                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10067                // However...  if this package is part of a shared user, but it
10068                // doesn't match the signature of the shared user, let's fail.
10069                // What this means is that you can't change the signatures
10070                // associated with an overall shared user, which doesn't seem all
10071                // that unreasonable.
10072                if (signatureCheckPs.sharedUser != null) {
10073                    if (compareSignatures(
10074                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10075                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10076                        throw new PackageManagerException(
10077                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10078                                "Signature mismatch for shared user: "
10079                                        + pkgSetting.sharedUser);
10080                    }
10081                }
10082                // File a report about this.
10083                String msg = "System package " + pkg.packageName
10084                        + " signature changed; retaining data.";
10085                reportSettingsProblem(Log.WARN, msg);
10086            }
10087        }
10088
10089        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10090            // This package wants to adopt ownership of permissions from
10091            // another package.
10092            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10093                final String origName = pkg.mAdoptPermissions.get(i);
10094                final PackageSetting orig = mSettings.getPackageLPr(origName);
10095                if (orig != null) {
10096                    if (verifyPackageUpdateLPr(orig, pkg)) {
10097                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10098                                + pkg.packageName);
10099                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10100                    }
10101                }
10102            }
10103        }
10104
10105        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10106            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10107                final String codePathString = changedAbiCodePath.get(i);
10108                try {
10109                    mInstaller.rmdex(codePathString,
10110                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10111                } catch (InstallerException ignored) {
10112                }
10113            }
10114        }
10115
10116        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10117            if (oldPkgSetting != null) {
10118                synchronized (mPackages) {
10119                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10120                }
10121            }
10122        } else {
10123            final int userId = user == null ? 0 : user.getIdentifier();
10124            // Modify state for the given package setting
10125            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10126                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10127            if (pkgSetting.getInstantApp(userId)) {
10128                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10129            }
10130        }
10131    }
10132
10133    /**
10134     * Returns the "real" name of the package.
10135     * <p>This may differ from the package's actual name if the application has already
10136     * been installed under one of this package's original names.
10137     */
10138    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10139            @Nullable String renamedPkgName) {
10140        if (isPackageRenamed(pkg, renamedPkgName)) {
10141            return pkg.mRealPackage;
10142        }
10143        return null;
10144    }
10145
10146    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10147    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10148            @Nullable String renamedPkgName) {
10149        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10150    }
10151
10152    /**
10153     * Returns the original package setting.
10154     * <p>A package can migrate its name during an update. In this scenario, a package
10155     * designates a set of names that it considers as one of its original names.
10156     * <p>An original package must be signed identically and it must have the same
10157     * shared user [if any].
10158     */
10159    @GuardedBy("mPackages")
10160    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10161            @Nullable String renamedPkgName) {
10162        if (!isPackageRenamed(pkg, renamedPkgName)) {
10163            return null;
10164        }
10165        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10166            final PackageSetting originalPs =
10167                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10168            if (originalPs != null) {
10169                // the package is already installed under its original name...
10170                // but, should we use it?
10171                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10172                    // the new package is incompatible with the original
10173                    continue;
10174                } else if (originalPs.sharedUser != null) {
10175                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10176                        // the shared user id is incompatible with the original
10177                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10178                                + " to " + pkg.packageName + ": old uid "
10179                                + originalPs.sharedUser.name
10180                                + " differs from " + pkg.mSharedUserId);
10181                        continue;
10182                    }
10183                    // TODO: Add case when shared user id is added [b/28144775]
10184                } else {
10185                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10186                            + pkg.packageName + " to old name " + originalPs.name);
10187                }
10188                return originalPs;
10189            }
10190        }
10191        return null;
10192    }
10193
10194    /**
10195     * Renames the package if it was installed under a different name.
10196     * <p>When we've already installed the package under an original name, update
10197     * the new package so we can continue to have the old name.
10198     */
10199    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10200            @NonNull String renamedPackageName) {
10201        if (pkg.mOriginalPackages == null
10202                || !pkg.mOriginalPackages.contains(renamedPackageName)
10203                || pkg.packageName.equals(renamedPackageName)) {
10204            return;
10205        }
10206        pkg.setPackageName(renamedPackageName);
10207    }
10208
10209    /**
10210     * Just scans the package without any side effects.
10211     * <p>Not entirely true at the moment. There is still one side effect -- this
10212     * method potentially modifies a live {@link PackageSetting} object representing
10213     * the package being scanned. This will be resolved in the future.
10214     *
10215     * @param request Information about the package to be scanned
10216     * @param isUnderFactoryTest Whether or not the device is under factory test
10217     * @param currentTime The current time, in millis
10218     * @return The results of the scan
10219     */
10220    @GuardedBy("mInstallLock")
10221    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10222            boolean isUnderFactoryTest, long currentTime)
10223                    throws PackageManagerException {
10224        final PackageParser.Package pkg = request.pkg;
10225        PackageSetting pkgSetting = request.pkgSetting;
10226        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10227        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10228        final @ParseFlags int parseFlags = request.parseFlags;
10229        final @ScanFlags int scanFlags = request.scanFlags;
10230        final String realPkgName = request.realPkgName;
10231        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10232        final UserHandle user = request.user;
10233        final boolean isPlatformPackage = request.isPlatformPackage;
10234
10235        List<String> changedAbiCodePath = null;
10236
10237        if (DEBUG_PACKAGE_SCANNING) {
10238            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10239                Log.d(TAG, "Scanning package " + pkg.packageName);
10240        }
10241
10242        if (Build.IS_DEBUGGABLE &&
10243                pkg.isPrivileged() &&
10244                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10245            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10246        }
10247
10248        // Initialize package source and resource directories
10249        final File scanFile = new File(pkg.codePath);
10250        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10251        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10252
10253        // We keep references to the derived CPU Abis from settings in oder to reuse
10254        // them in the case where we're not upgrading or booting for the first time.
10255        String primaryCpuAbiFromSettings = null;
10256        String secondaryCpuAbiFromSettings = null;
10257        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10258
10259        if (!needToDeriveAbi) {
10260            if (pkgSetting != null) {
10261                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10262                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10263            } else {
10264                // Re-scanning a system package after uninstalling updates; need to derive ABI
10265                needToDeriveAbi = true;
10266            }
10267        }
10268
10269        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10270            PackageManagerService.reportSettingsProblem(Log.WARN,
10271                    "Package " + pkg.packageName + " shared user changed from "
10272                            + (pkgSetting.sharedUser != null
10273                            ? pkgSetting.sharedUser.name : "<nothing>")
10274                            + " to "
10275                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10276                            + "; replacing with new");
10277            pkgSetting = null;
10278        }
10279
10280        String[] usesStaticLibraries = null;
10281        if (pkg.usesStaticLibraries != null) {
10282            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10283            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10284        }
10285        final boolean createNewPackage = (pkgSetting == null);
10286        if (createNewPackage) {
10287            final String parentPackageName = (pkg.parentPackage != null)
10288                    ? pkg.parentPackage.packageName : null;
10289            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10290            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10291            // REMOVE SharedUserSetting from method; update in a separate call
10292            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10293                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10294                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10295                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10296                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10297                    user, true /*allowInstall*/, instantApp, virtualPreload,
10298                    parentPackageName, pkg.getChildPackageNames(),
10299                    UserManagerService.getInstance(), usesStaticLibraries,
10300                    pkg.usesStaticLibrariesVersions);
10301        } else {
10302            // REMOVE SharedUserSetting from method; update in a separate call.
10303            //
10304            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10305            // secondaryCpuAbi are not known at this point so we always update them
10306            // to null here, only to reset them at a later point.
10307            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10308                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10309                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10310                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10311                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10312                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10313        }
10314        if (createNewPackage && originalPkgSetting != null) {
10315            // This is the initial transition from the original package, so,
10316            // fix up the new package's name now. We must do this after looking
10317            // up the package under its new name, so getPackageLP takes care of
10318            // fiddling things correctly.
10319            pkg.setPackageName(originalPkgSetting.name);
10320
10321            // File a report about this.
10322            String msg = "New package " + pkgSetting.realName
10323                    + " renamed to replace old package " + pkgSetting.name;
10324            reportSettingsProblem(Log.WARN, msg);
10325        }
10326
10327        if (disabledPkgSetting != null) {
10328            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10329        }
10330
10331        SELinuxMMAC.assignSeInfoValue(pkg);
10332
10333        pkg.mExtras = pkgSetting;
10334        pkg.applicationInfo.processName = fixProcessName(
10335                pkg.applicationInfo.packageName,
10336                pkg.applicationInfo.processName);
10337
10338        if (!isPlatformPackage) {
10339            // Get all of our default paths setup
10340            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10341        }
10342
10343        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10344
10345        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10346            if (needToDeriveAbi) {
10347                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10348                final boolean extractNativeLibs = !pkg.isLibrary();
10349                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10350                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10351
10352                // Some system apps still use directory structure for native libraries
10353                // in which case we might end up not detecting abi solely based on apk
10354                // structure. Try to detect abi based on directory structure.
10355                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10356                        pkg.applicationInfo.primaryCpuAbi == null) {
10357                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10358                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10359                }
10360            } else {
10361                // This is not a first boot or an upgrade, don't bother deriving the
10362                // ABI during the scan. Instead, trust the value that was stored in the
10363                // package setting.
10364                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10365                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10366
10367                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10368
10369                if (DEBUG_ABI_SELECTION) {
10370                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10371                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10372                            pkg.applicationInfo.secondaryCpuAbi);
10373                }
10374            }
10375        } else {
10376            if ((scanFlags & SCAN_MOVE) != 0) {
10377                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10378                // but we already have this packages package info in the PackageSetting. We just
10379                // use that and derive the native library path based on the new codepath.
10380                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10381                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10382            }
10383
10384            // Set native library paths again. For moves, the path will be updated based on the
10385            // ABIs we've determined above. For non-moves, the path will be updated based on the
10386            // ABIs we determined during compilation, but the path will depend on the final
10387            // package path (after the rename away from the stage path).
10388            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10389        }
10390
10391        // This is a special case for the "system" package, where the ABI is
10392        // dictated by the zygote configuration (and init.rc). We should keep track
10393        // of this ABI so that we can deal with "normal" applications that run under
10394        // the same UID correctly.
10395        if (isPlatformPackage) {
10396            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10397                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10398        }
10399
10400        // If there's a mismatch between the abi-override in the package setting
10401        // and the abiOverride specified for the install. Warn about this because we
10402        // would've already compiled the app without taking the package setting into
10403        // account.
10404        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10405            if (cpuAbiOverride == null && pkg.packageName != null) {
10406                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10407                        " for package " + pkg.packageName);
10408            }
10409        }
10410
10411        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10412        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10413        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10414
10415        // Copy the derived override back to the parsed package, so that we can
10416        // update the package settings accordingly.
10417        pkg.cpuAbiOverride = cpuAbiOverride;
10418
10419        if (DEBUG_ABI_SELECTION) {
10420            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10421                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10422                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10423        }
10424
10425        // Push the derived path down into PackageSettings so we know what to
10426        // clean up at uninstall time.
10427        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10428
10429        if (DEBUG_ABI_SELECTION) {
10430            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10431                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10432                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10433        }
10434
10435        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10436            // We don't do this here during boot because we can do it all
10437            // at once after scanning all existing packages.
10438            //
10439            // We also do this *before* we perform dexopt on this package, so that
10440            // we can avoid redundant dexopts, and also to make sure we've got the
10441            // code and package path correct.
10442            changedAbiCodePath =
10443                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10444        }
10445
10446        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10447                android.Manifest.permission.FACTORY_TEST)) {
10448            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10449        }
10450
10451        if (isSystemApp(pkg)) {
10452            pkgSetting.isOrphaned = true;
10453        }
10454
10455        // Take care of first install / last update times.
10456        final long scanFileTime = getLastModifiedTime(pkg);
10457        if (currentTime != 0) {
10458            if (pkgSetting.firstInstallTime == 0) {
10459                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10460            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10461                pkgSetting.lastUpdateTime = currentTime;
10462            }
10463        } else if (pkgSetting.firstInstallTime == 0) {
10464            // We need *something*.  Take time time stamp of the file.
10465            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10466        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10467            if (scanFileTime != pkgSetting.timeStamp) {
10468                // A package on the system image has changed; consider this
10469                // to be an update.
10470                pkgSetting.lastUpdateTime = scanFileTime;
10471            }
10472        }
10473        pkgSetting.setTimeStamp(scanFileTime);
10474
10475        pkgSetting.pkg = pkg;
10476        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10477        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10478            pkgSetting.versionCode = pkg.getLongVersionCode();
10479        }
10480        // Update volume if needed
10481        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10482        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10483            Slog.i(PackageManagerService.TAG,
10484                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10485                    + " package " + pkg.packageName
10486                    + " volume from " + pkgSetting.volumeUuid
10487                    + " to " + volumeUuid);
10488            pkgSetting.volumeUuid = volumeUuid;
10489        }
10490
10491        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10492    }
10493
10494    /**
10495     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10496     */
10497    private static boolean apkHasCode(String fileName) {
10498        StrictJarFile jarFile = null;
10499        try {
10500            jarFile = new StrictJarFile(fileName,
10501                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10502            return jarFile.findEntry("classes.dex") != null;
10503        } catch (IOException ignore) {
10504        } finally {
10505            try {
10506                if (jarFile != null) {
10507                    jarFile.close();
10508                }
10509            } catch (IOException ignore) {}
10510        }
10511        return false;
10512    }
10513
10514    /**
10515     * Enforces code policy for the package. This ensures that if an APK has
10516     * declared hasCode="true" in its manifest that the APK actually contains
10517     * code.
10518     *
10519     * @throws PackageManagerException If bytecode could not be found when it should exist
10520     */
10521    private static void assertCodePolicy(PackageParser.Package pkg)
10522            throws PackageManagerException {
10523        final boolean shouldHaveCode =
10524                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10525        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10526            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10527                    "Package " + pkg.baseCodePath + " code is missing");
10528        }
10529
10530        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10531            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10532                final boolean splitShouldHaveCode =
10533                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10534                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10535                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10536                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10537                }
10538            }
10539        }
10540    }
10541
10542    /**
10543     * Applies policy to the parsed package based upon the given policy flags.
10544     * Ensures the package is in a good state.
10545     * <p>
10546     * Implementation detail: This method must NOT have any side effect. It would
10547     * ideally be static, but, it requires locks to read system state.
10548     */
10549    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10550            final @ScanFlags int scanFlags) {
10551        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10552            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10553            if (pkg.applicationInfo.isDirectBootAware()) {
10554                // we're direct boot aware; set for all components
10555                for (PackageParser.Service s : pkg.services) {
10556                    s.info.encryptionAware = s.info.directBootAware = true;
10557                }
10558                for (PackageParser.Provider p : pkg.providers) {
10559                    p.info.encryptionAware = p.info.directBootAware = true;
10560                }
10561                for (PackageParser.Activity a : pkg.activities) {
10562                    a.info.encryptionAware = a.info.directBootAware = true;
10563                }
10564                for (PackageParser.Activity r : pkg.receivers) {
10565                    r.info.encryptionAware = r.info.directBootAware = true;
10566                }
10567            }
10568            if (compressedFileExists(pkg.codePath)) {
10569                pkg.isStub = true;
10570            }
10571        } else {
10572            // non system apps can't be flagged as core
10573            pkg.coreApp = false;
10574            // clear flags not applicable to regular apps
10575            pkg.applicationInfo.flags &=
10576                    ~ApplicationInfo.FLAG_PERSISTENT;
10577            pkg.applicationInfo.privateFlags &=
10578                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10579            pkg.applicationInfo.privateFlags &=
10580                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10581            // clear protected broadcasts
10582            pkg.protectedBroadcasts = null;
10583            // cap permission priorities
10584            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10585                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10586                    pkg.permissionGroups.get(i).info.priority = 0;
10587                }
10588            }
10589        }
10590        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10591            // ignore export request for single user receivers
10592            if (pkg.receivers != null) {
10593                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10594                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10595                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10596                        receiver.info.exported = false;
10597                    }
10598                }
10599            }
10600            // ignore export request for single user services
10601            if (pkg.services != null) {
10602                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10603                    final PackageParser.Service service = pkg.services.get(i);
10604                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10605                        service.info.exported = false;
10606                    }
10607                }
10608            }
10609            // ignore export request for single user providers
10610            if (pkg.providers != null) {
10611                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10612                    final PackageParser.Provider provider = pkg.providers.get(i);
10613                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10614                        provider.info.exported = false;
10615                    }
10616                }
10617            }
10618        }
10619        pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0;
10620
10621        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10622            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10623        }
10624
10625        if ((scanFlags & SCAN_AS_OEM) != 0) {
10626            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10627        }
10628
10629        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10630            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10631        }
10632
10633        if (!isSystemApp(pkg)) {
10634            // Only system apps can use these features.
10635            pkg.mOriginalPackages = null;
10636            pkg.mRealPackage = null;
10637            pkg.mAdoptPermissions = null;
10638        }
10639    }
10640
10641    /**
10642     * Asserts the parsed package is valid according to the given policy. If the
10643     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10644     * <p>
10645     * Implementation detail: This method must NOT have any side effects. It would
10646     * ideally be static, but, it requires locks to read system state.
10647     *
10648     * @throws PackageManagerException If the package fails any of the validation checks
10649     */
10650    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10651            final @ScanFlags int scanFlags)
10652                    throws PackageManagerException {
10653        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10654            assertCodePolicy(pkg);
10655        }
10656
10657        if (pkg.applicationInfo.getCodePath() == null ||
10658                pkg.applicationInfo.getResourcePath() == null) {
10659            // Bail out. The resource and code paths haven't been set.
10660            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10661                    "Code and resource paths haven't been set correctly");
10662        }
10663
10664        // Make sure we're not adding any bogus keyset info
10665        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10666        ksms.assertScannedPackageValid(pkg);
10667
10668        synchronized (mPackages) {
10669            // The special "android" package can only be defined once
10670            if (pkg.packageName.equals("android")) {
10671                if (mAndroidApplication != null) {
10672                    Slog.w(TAG, "*************************************************");
10673                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10674                    Slog.w(TAG, " codePath=" + pkg.codePath);
10675                    Slog.w(TAG, "*************************************************");
10676                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10677                            "Core android package being redefined.  Skipping.");
10678                }
10679            }
10680
10681            // A package name must be unique; don't allow duplicates
10682            if (mPackages.containsKey(pkg.packageName)) {
10683                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10684                        "Application package " + pkg.packageName
10685                        + " already installed.  Skipping duplicate.");
10686            }
10687
10688            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10689                // Static libs have a synthetic package name containing the version
10690                // but we still want the base name to be unique.
10691                if (mPackages.containsKey(pkg.manifestPackageName)) {
10692                    throw new PackageManagerException(
10693                            "Duplicate static shared lib provider package");
10694                }
10695
10696                // Static shared libraries should have at least O target SDK
10697                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10698                    throw new PackageManagerException(
10699                            "Packages declaring static-shared libs must target O SDK or higher");
10700                }
10701
10702                // Package declaring static a shared lib cannot be instant apps
10703                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10704                    throw new PackageManagerException(
10705                            "Packages declaring static-shared libs cannot be instant apps");
10706                }
10707
10708                // Package declaring static a shared lib cannot be renamed since the package
10709                // name is synthetic and apps can't code around package manager internals.
10710                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10711                    throw new PackageManagerException(
10712                            "Packages declaring static-shared libs cannot be renamed");
10713                }
10714
10715                // Package declaring static a shared lib cannot declare child packages
10716                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10717                    throw new PackageManagerException(
10718                            "Packages declaring static-shared libs cannot have child packages");
10719                }
10720
10721                // Package declaring static a shared lib cannot declare dynamic libs
10722                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10723                    throw new PackageManagerException(
10724                            "Packages declaring static-shared libs cannot declare dynamic libs");
10725                }
10726
10727                // Package declaring static a shared lib cannot declare shared users
10728                if (pkg.mSharedUserId != null) {
10729                    throw new PackageManagerException(
10730                            "Packages declaring static-shared libs cannot declare shared users");
10731                }
10732
10733                // Static shared libs cannot declare activities
10734                if (!pkg.activities.isEmpty()) {
10735                    throw new PackageManagerException(
10736                            "Static shared libs cannot declare activities");
10737                }
10738
10739                // Static shared libs cannot declare services
10740                if (!pkg.services.isEmpty()) {
10741                    throw new PackageManagerException(
10742                            "Static shared libs cannot declare services");
10743                }
10744
10745                // Static shared libs cannot declare providers
10746                if (!pkg.providers.isEmpty()) {
10747                    throw new PackageManagerException(
10748                            "Static shared libs cannot declare content providers");
10749                }
10750
10751                // Static shared libs cannot declare receivers
10752                if (!pkg.receivers.isEmpty()) {
10753                    throw new PackageManagerException(
10754                            "Static shared libs cannot declare broadcast receivers");
10755                }
10756
10757                // Static shared libs cannot declare permission groups
10758                if (!pkg.permissionGroups.isEmpty()) {
10759                    throw new PackageManagerException(
10760                            "Static shared libs cannot declare permission groups");
10761                }
10762
10763                // Static shared libs cannot declare permissions
10764                if (!pkg.permissions.isEmpty()) {
10765                    throw new PackageManagerException(
10766                            "Static shared libs cannot declare permissions");
10767                }
10768
10769                // Static shared libs cannot declare protected broadcasts
10770                if (pkg.protectedBroadcasts != null) {
10771                    throw new PackageManagerException(
10772                            "Static shared libs cannot declare protected broadcasts");
10773                }
10774
10775                // Static shared libs cannot be overlay targets
10776                if (pkg.mOverlayTarget != null) {
10777                    throw new PackageManagerException(
10778                            "Static shared libs cannot be overlay targets");
10779                }
10780
10781                // The version codes must be ordered as lib versions
10782                long minVersionCode = Long.MIN_VALUE;
10783                long maxVersionCode = Long.MAX_VALUE;
10784
10785                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10786                        pkg.staticSharedLibName);
10787                if (versionedLib != null) {
10788                    final int versionCount = versionedLib.size();
10789                    for (int i = 0; i < versionCount; i++) {
10790                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10791                        final long libVersionCode = libInfo.getDeclaringPackage()
10792                                .getLongVersionCode();
10793                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10794                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10795                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10796                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10797                        } else {
10798                            minVersionCode = maxVersionCode = libVersionCode;
10799                            break;
10800                        }
10801                    }
10802                }
10803                if (pkg.getLongVersionCode() < minVersionCode
10804                        || pkg.getLongVersionCode() > maxVersionCode) {
10805                    throw new PackageManagerException("Static shared"
10806                            + " lib version codes must be ordered as lib versions");
10807                }
10808            }
10809
10810            // Only privileged apps and updated privileged apps can add child packages.
10811            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10812                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10813                    throw new PackageManagerException("Only privileged apps can add child "
10814                            + "packages. Ignoring package " + pkg.packageName);
10815                }
10816                final int childCount = pkg.childPackages.size();
10817                for (int i = 0; i < childCount; i++) {
10818                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10819                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10820                            childPkg.packageName)) {
10821                        throw new PackageManagerException("Can't override child of "
10822                                + "another disabled app. Ignoring package " + pkg.packageName);
10823                    }
10824                }
10825            }
10826
10827            // If we're only installing presumed-existing packages, require that the
10828            // scanned APK is both already known and at the path previously established
10829            // for it.  Previously unknown packages we pick up normally, but if we have an
10830            // a priori expectation about this package's install presence, enforce it.
10831            // With a singular exception for new system packages. When an OTA contains
10832            // a new system package, we allow the codepath to change from a system location
10833            // to the user-installed location. If we don't allow this change, any newer,
10834            // user-installed version of the application will be ignored.
10835            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10836                if (mExpectingBetter.containsKey(pkg.packageName)) {
10837                    logCriticalInfo(Log.WARN,
10838                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10839                } else {
10840                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10841                    if (known != null) {
10842                        if (DEBUG_PACKAGE_SCANNING) {
10843                            Log.d(TAG, "Examining " + pkg.codePath
10844                                    + " and requiring known paths " + known.codePathString
10845                                    + " & " + known.resourcePathString);
10846                        }
10847                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10848                                || !pkg.applicationInfo.getResourcePath().equals(
10849                                        known.resourcePathString)) {
10850                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10851                                    "Application package " + pkg.packageName
10852                                    + " found at " + pkg.applicationInfo.getCodePath()
10853                                    + " but expected at " + known.codePathString
10854                                    + "; ignoring.");
10855                        }
10856                    } else {
10857                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10858                                "Application package " + pkg.packageName
10859                                + " not found; ignoring.");
10860                    }
10861                }
10862            }
10863
10864            // Verify that this new package doesn't have any content providers
10865            // that conflict with existing packages.  Only do this if the
10866            // package isn't already installed, since we don't want to break
10867            // things that are installed.
10868            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10869                final int N = pkg.providers.size();
10870                int i;
10871                for (i=0; i<N; i++) {
10872                    PackageParser.Provider p = pkg.providers.get(i);
10873                    if (p.info.authority != null) {
10874                        String names[] = p.info.authority.split(";");
10875                        for (int j = 0; j < names.length; j++) {
10876                            if (mProvidersByAuthority.containsKey(names[j])) {
10877                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10878                                final String otherPackageName =
10879                                        ((other != null && other.getComponentName() != null) ?
10880                                                other.getComponentName().getPackageName() : "?");
10881                                throw new PackageManagerException(
10882                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10883                                        "Can't install because provider name " + names[j]
10884                                                + " (in package " + pkg.applicationInfo.packageName
10885                                                + ") is already used by " + otherPackageName);
10886                            }
10887                        }
10888                    }
10889                }
10890            }
10891
10892            // Verify that packages sharing a user with a privileged app are marked as privileged.
10893            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10894                SharedUserSetting sharedUserSetting = null;
10895                try {
10896                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10897                } catch (PackageManagerException ignore) {}
10898                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10899                    // Exempt SharedUsers signed with the platform key.
10900                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10901                    if ((platformPkgSetting.signatures.mSigningDetails
10902                            != PackageParser.SigningDetails.UNKNOWN)
10903                            && (compareSignatures(
10904                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10905                                    pkg.mSigningDetails.signatures)
10906                                            != PackageManager.SIGNATURE_MATCH)) {
10907                        throw new PackageManagerException("Apps that share a user with a " +
10908                                "privileged app must themselves be marked as privileged. " +
10909                                pkg.packageName + " shares privileged user " +
10910                                pkg.mSharedUserId + ".");
10911                    }
10912                }
10913            }
10914        }
10915    }
10916
10917    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
10918            int type, String declaringPackageName, long declaringVersionCode) {
10919        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10920        if (versionedLib == null) {
10921            versionedLib = new LongSparseArray<>();
10922            mSharedLibraries.put(name, versionedLib);
10923            if (type == SharedLibraryInfo.TYPE_STATIC) {
10924                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10925            }
10926        } else if (versionedLib.indexOfKey(version) >= 0) {
10927            return false;
10928        }
10929        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10930                version, type, declaringPackageName, declaringVersionCode);
10931        versionedLib.put(version, libEntry);
10932        return true;
10933    }
10934
10935    private boolean removeSharedLibraryLPw(String name, long version) {
10936        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10937        if (versionedLib == null) {
10938            return false;
10939        }
10940        final int libIdx = versionedLib.indexOfKey(version);
10941        if (libIdx < 0) {
10942            return false;
10943        }
10944        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10945        versionedLib.remove(version);
10946        if (versionedLib.size() <= 0) {
10947            mSharedLibraries.remove(name);
10948            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10949                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10950                        .getPackageName());
10951            }
10952        }
10953        return true;
10954    }
10955
10956    /**
10957     * Adds a scanned package to the system. When this method is finished, the package will
10958     * be available for query, resolution, etc...
10959     */
10960    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10961            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
10962        final String pkgName = pkg.packageName;
10963        if (mCustomResolverComponentName != null &&
10964                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10965            setUpCustomResolverActivity(pkg);
10966        }
10967
10968        if (pkg.packageName.equals("android")) {
10969            synchronized (mPackages) {
10970                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10971                    // Set up information for our fall-back user intent resolution activity.
10972                    mPlatformPackage = pkg;
10973                    pkg.mVersionCode = mSdkVersion;
10974                    pkg.mVersionCodeMajor = 0;
10975                    mAndroidApplication = pkg.applicationInfo;
10976                    if (!mResolverReplaced) {
10977                        mResolveActivity.applicationInfo = mAndroidApplication;
10978                        mResolveActivity.name = ResolverActivity.class.getName();
10979                        mResolveActivity.packageName = mAndroidApplication.packageName;
10980                        mResolveActivity.processName = "system:ui";
10981                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10982                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10983                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10984                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10985                        mResolveActivity.exported = true;
10986                        mResolveActivity.enabled = true;
10987                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10988                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10989                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10990                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10991                                | ActivityInfo.CONFIG_ORIENTATION
10992                                | ActivityInfo.CONFIG_KEYBOARD
10993                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10994                        mResolveInfo.activityInfo = mResolveActivity;
10995                        mResolveInfo.priority = 0;
10996                        mResolveInfo.preferredOrder = 0;
10997                        mResolveInfo.match = 0;
10998                        mResolveComponentName = new ComponentName(
10999                                mAndroidApplication.packageName, mResolveActivity.name);
11000                    }
11001                }
11002            }
11003        }
11004
11005        ArrayList<PackageParser.Package> clientLibPkgs = null;
11006        // writer
11007        synchronized (mPackages) {
11008            boolean hasStaticSharedLibs = false;
11009
11010            // Any app can add new static shared libraries
11011            if (pkg.staticSharedLibName != null) {
11012                // Static shared libs don't allow renaming as they have synthetic package
11013                // names to allow install of multiple versions, so use name from manifest.
11014                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11015                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11016                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11017                    hasStaticSharedLibs = true;
11018                } else {
11019                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11020                                + pkg.staticSharedLibName + " already exists; skipping");
11021                }
11022                // Static shared libs cannot be updated once installed since they
11023                // use synthetic package name which includes the version code, so
11024                // not need to update other packages's shared lib dependencies.
11025            }
11026
11027            if (!hasStaticSharedLibs
11028                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11029                // Only system apps can add new dynamic shared libraries.
11030                if (pkg.libraryNames != null) {
11031                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11032                        String name = pkg.libraryNames.get(i);
11033                        boolean allowed = false;
11034                        if (pkg.isUpdatedSystemApp()) {
11035                            // New library entries can only be added through the
11036                            // system image.  This is important to get rid of a lot
11037                            // of nasty edge cases: for example if we allowed a non-
11038                            // system update of the app to add a library, then uninstalling
11039                            // the update would make the library go away, and assumptions
11040                            // we made such as through app install filtering would now
11041                            // have allowed apps on the device which aren't compatible
11042                            // with it.  Better to just have the restriction here, be
11043                            // conservative, and create many fewer cases that can negatively
11044                            // impact the user experience.
11045                            final PackageSetting sysPs = mSettings
11046                                    .getDisabledSystemPkgLPr(pkg.packageName);
11047                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11048                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11049                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11050                                        allowed = true;
11051                                        break;
11052                                    }
11053                                }
11054                            }
11055                        } else {
11056                            allowed = true;
11057                        }
11058                        if (allowed) {
11059                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11060                                    SharedLibraryInfo.VERSION_UNDEFINED,
11061                                    SharedLibraryInfo.TYPE_DYNAMIC,
11062                                    pkg.packageName, pkg.getLongVersionCode())) {
11063                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11064                                        + name + " already exists; skipping");
11065                            }
11066                        } else {
11067                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11068                                    + name + " that is not declared on system image; skipping");
11069                        }
11070                    }
11071
11072                    if ((scanFlags & SCAN_BOOTING) == 0) {
11073                        // If we are not booting, we need to update any applications
11074                        // that are clients of our shared library.  If we are booting,
11075                        // this will all be done once the scan is complete.
11076                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11077                    }
11078                }
11079            }
11080        }
11081
11082        if ((scanFlags & SCAN_BOOTING) != 0) {
11083            // No apps can run during boot scan, so they don't need to be frozen
11084        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11085            // Caller asked to not kill app, so it's probably not frozen
11086        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11087            // Caller asked us to ignore frozen check for some reason; they
11088            // probably didn't know the package name
11089        } else {
11090            // We're doing major surgery on this package, so it better be frozen
11091            // right now to keep it from launching
11092            checkPackageFrozen(pkgName);
11093        }
11094
11095        // Also need to kill any apps that are dependent on the library.
11096        if (clientLibPkgs != null) {
11097            for (int i=0; i<clientLibPkgs.size(); i++) {
11098                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11099                killApplication(clientPkg.applicationInfo.packageName,
11100                        clientPkg.applicationInfo.uid, "update lib");
11101            }
11102        }
11103
11104        // writer
11105        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11106
11107        synchronized (mPackages) {
11108            // We don't expect installation to fail beyond this point
11109
11110            // Add the new setting to mSettings
11111            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11112            // Add the new setting to mPackages
11113            mPackages.put(pkg.applicationInfo.packageName, pkg);
11114            // Make sure we don't accidentally delete its data.
11115            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11116            while (iter.hasNext()) {
11117                PackageCleanItem item = iter.next();
11118                if (pkgName.equals(item.packageName)) {
11119                    iter.remove();
11120                }
11121            }
11122
11123            // Add the package's KeySets to the global KeySetManagerService
11124            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11125            ksms.addScannedPackageLPw(pkg);
11126
11127            int N = pkg.providers.size();
11128            StringBuilder r = null;
11129            int i;
11130            for (i=0; i<N; i++) {
11131                PackageParser.Provider p = pkg.providers.get(i);
11132                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11133                        p.info.processName);
11134                mProviders.addProvider(p);
11135                p.syncable = p.info.isSyncable;
11136                if (p.info.authority != null) {
11137                    String names[] = p.info.authority.split(";");
11138                    p.info.authority = null;
11139                    for (int j = 0; j < names.length; j++) {
11140                        if (j == 1 && p.syncable) {
11141                            // We only want the first authority for a provider to possibly be
11142                            // syncable, so if we already added this provider using a different
11143                            // authority clear the syncable flag. We copy the provider before
11144                            // changing it because the mProviders object contains a reference
11145                            // to a provider that we don't want to change.
11146                            // Only do this for the second authority since the resulting provider
11147                            // object can be the same for all future authorities for this provider.
11148                            p = new PackageParser.Provider(p);
11149                            p.syncable = false;
11150                        }
11151                        if (!mProvidersByAuthority.containsKey(names[j])) {
11152                            mProvidersByAuthority.put(names[j], p);
11153                            if (p.info.authority == null) {
11154                                p.info.authority = names[j];
11155                            } else {
11156                                p.info.authority = p.info.authority + ";" + names[j];
11157                            }
11158                            if (DEBUG_PACKAGE_SCANNING) {
11159                                if (chatty)
11160                                    Log.d(TAG, "Registered content provider: " + names[j]
11161                                            + ", className = " + p.info.name + ", isSyncable = "
11162                                            + p.info.isSyncable);
11163                            }
11164                        } else {
11165                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11166                            Slog.w(TAG, "Skipping provider name " + names[j] +
11167                                    " (in package " + pkg.applicationInfo.packageName +
11168                                    "): name already used by "
11169                                    + ((other != null && other.getComponentName() != null)
11170                                            ? other.getComponentName().getPackageName() : "?"));
11171                        }
11172                    }
11173                }
11174                if (chatty) {
11175                    if (r == null) {
11176                        r = new StringBuilder(256);
11177                    } else {
11178                        r.append(' ');
11179                    }
11180                    r.append(p.info.name);
11181                }
11182            }
11183            if (r != null) {
11184                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11185            }
11186
11187            N = pkg.services.size();
11188            r = null;
11189            for (i=0; i<N; i++) {
11190                PackageParser.Service s = pkg.services.get(i);
11191                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11192                        s.info.processName);
11193                mServices.addService(s);
11194                if (chatty) {
11195                    if (r == null) {
11196                        r = new StringBuilder(256);
11197                    } else {
11198                        r.append(' ');
11199                    }
11200                    r.append(s.info.name);
11201                }
11202            }
11203            if (r != null) {
11204                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11205            }
11206
11207            N = pkg.receivers.size();
11208            r = null;
11209            for (i=0; i<N; i++) {
11210                PackageParser.Activity a = pkg.receivers.get(i);
11211                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11212                        a.info.processName);
11213                mReceivers.addActivity(a, "receiver");
11214                if (chatty) {
11215                    if (r == null) {
11216                        r = new StringBuilder(256);
11217                    } else {
11218                        r.append(' ');
11219                    }
11220                    r.append(a.info.name);
11221                }
11222            }
11223            if (r != null) {
11224                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11225            }
11226
11227            N = pkg.activities.size();
11228            r = null;
11229            for (i=0; i<N; i++) {
11230                PackageParser.Activity a = pkg.activities.get(i);
11231                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11232                        a.info.processName);
11233                mActivities.addActivity(a, "activity");
11234                if (chatty) {
11235                    if (r == null) {
11236                        r = new StringBuilder(256);
11237                    } else {
11238                        r.append(' ');
11239                    }
11240                    r.append(a.info.name);
11241                }
11242            }
11243            if (r != null) {
11244                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11245            }
11246
11247            // Don't allow ephemeral applications to define new permissions groups.
11248            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11249                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11250                        + " ignored: instant apps cannot define new permission groups.");
11251            } else {
11252                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11253            }
11254
11255            // Don't allow ephemeral applications to define new permissions.
11256            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11257                Slog.w(TAG, "Permissions from package " + pkg.packageName
11258                        + " ignored: instant apps cannot define new permissions.");
11259            } else {
11260                mPermissionManager.addAllPermissions(pkg, chatty);
11261            }
11262
11263            N = pkg.instrumentation.size();
11264            r = null;
11265            for (i=0; i<N; i++) {
11266                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11267                a.info.packageName = pkg.applicationInfo.packageName;
11268                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11269                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11270                a.info.splitNames = pkg.splitNames;
11271                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11272                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11273                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11274                a.info.dataDir = pkg.applicationInfo.dataDir;
11275                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11276                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11277                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11278                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11279                mInstrumentation.put(a.getComponentName(), a);
11280                if (chatty) {
11281                    if (r == null) {
11282                        r = new StringBuilder(256);
11283                    } else {
11284                        r.append(' ');
11285                    }
11286                    r.append(a.info.name);
11287                }
11288            }
11289            if (r != null) {
11290                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11291            }
11292
11293            if (pkg.protectedBroadcasts != null) {
11294                N = pkg.protectedBroadcasts.size();
11295                synchronized (mProtectedBroadcasts) {
11296                    for (i = 0; i < N; i++) {
11297                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11298                    }
11299                }
11300            }
11301        }
11302
11303        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11304    }
11305
11306    /**
11307     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11308     * is derived purely on the basis of the contents of {@code scanFile} and
11309     * {@code cpuAbiOverride}.
11310     *
11311     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11312     */
11313    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11314            boolean extractLibs)
11315                    throws PackageManagerException {
11316        // Give ourselves some initial paths; we'll come back for another
11317        // pass once we've determined ABI below.
11318        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11319
11320        // We would never need to extract libs for forward-locked and external packages,
11321        // since the container service will do it for us. We shouldn't attempt to
11322        // extract libs from system app when it was not updated.
11323        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11324                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11325            extractLibs = false;
11326        }
11327
11328        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11329        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11330
11331        NativeLibraryHelper.Handle handle = null;
11332        try {
11333            handle = NativeLibraryHelper.Handle.create(pkg);
11334            // TODO(multiArch): This can be null for apps that didn't go through the
11335            // usual installation process. We can calculate it again, like we
11336            // do during install time.
11337            //
11338            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11339            // unnecessary.
11340            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11341
11342            // Null out the abis so that they can be recalculated.
11343            pkg.applicationInfo.primaryCpuAbi = null;
11344            pkg.applicationInfo.secondaryCpuAbi = null;
11345            if (isMultiArch(pkg.applicationInfo)) {
11346                // Warn if we've set an abiOverride for multi-lib packages..
11347                // By definition, we need to copy both 32 and 64 bit libraries for
11348                // such packages.
11349                if (pkg.cpuAbiOverride != null
11350                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11351                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11352                }
11353
11354                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11355                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11356                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11357                    if (extractLibs) {
11358                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11359                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11360                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11361                                useIsaSpecificSubdirs);
11362                    } else {
11363                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11364                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11365                    }
11366                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11367                }
11368
11369                // Shared library native code should be in the APK zip aligned
11370                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11371                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11372                            "Shared library native lib extraction not supported");
11373                }
11374
11375                maybeThrowExceptionForMultiArchCopy(
11376                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11377
11378                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11379                    if (extractLibs) {
11380                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11381                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11382                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11383                                useIsaSpecificSubdirs);
11384                    } else {
11385                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11386                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11387                    }
11388                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11389                }
11390
11391                maybeThrowExceptionForMultiArchCopy(
11392                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11393
11394                if (abi64 >= 0) {
11395                    // Shared library native libs should be in the APK zip aligned
11396                    if (extractLibs && pkg.isLibrary()) {
11397                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11398                                "Shared library native lib extraction not supported");
11399                    }
11400                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11401                }
11402
11403                if (abi32 >= 0) {
11404                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11405                    if (abi64 >= 0) {
11406                        if (pkg.use32bitAbi) {
11407                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11408                            pkg.applicationInfo.primaryCpuAbi = abi;
11409                        } else {
11410                            pkg.applicationInfo.secondaryCpuAbi = abi;
11411                        }
11412                    } else {
11413                        pkg.applicationInfo.primaryCpuAbi = abi;
11414                    }
11415                }
11416            } else {
11417                String[] abiList = (cpuAbiOverride != null) ?
11418                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11419
11420                // Enable gross and lame hacks for apps that are built with old
11421                // SDK tools. We must scan their APKs for renderscript bitcode and
11422                // not launch them if it's present. Don't bother checking on devices
11423                // that don't have 64 bit support.
11424                boolean needsRenderScriptOverride = false;
11425                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11426                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11427                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11428                    needsRenderScriptOverride = true;
11429                }
11430
11431                final int copyRet;
11432                if (extractLibs) {
11433                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11434                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11435                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11436                } else {
11437                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11438                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11439                }
11440                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11441
11442                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11443                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11444                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11445                }
11446
11447                if (copyRet >= 0) {
11448                    // Shared libraries that have native libs must be multi-architecture
11449                    if (pkg.isLibrary()) {
11450                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11451                                "Shared library with native libs must be multiarch");
11452                    }
11453                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11454                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11455                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11456                } else if (needsRenderScriptOverride) {
11457                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11458                }
11459            }
11460        } catch (IOException ioe) {
11461            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11462        } finally {
11463            IoUtils.closeQuietly(handle);
11464        }
11465
11466        // Now that we've calculated the ABIs and determined if it's an internal app,
11467        // we will go ahead and populate the nativeLibraryPath.
11468        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11469    }
11470
11471    /**
11472     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11473     * i.e, so that all packages can be run inside a single process if required.
11474     *
11475     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11476     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11477     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11478     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11479     * updating a package that belongs to a shared user.
11480     *
11481     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11482     * adds unnecessary complexity.
11483     */
11484    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11485            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11486        List<String> changedAbiCodePath = null;
11487        String requiredInstructionSet = null;
11488        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11489            requiredInstructionSet = VMRuntime.getInstructionSet(
11490                     scannedPackage.applicationInfo.primaryCpuAbi);
11491        }
11492
11493        PackageSetting requirer = null;
11494        for (PackageSetting ps : packagesForUser) {
11495            // If packagesForUser contains scannedPackage, we skip it. This will happen
11496            // when scannedPackage is an update of an existing package. Without this check,
11497            // we will never be able to change the ABI of any package belonging to a shared
11498            // user, even if it's compatible with other packages.
11499            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11500                if (ps.primaryCpuAbiString == null) {
11501                    continue;
11502                }
11503
11504                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11505                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11506                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11507                    // this but there's not much we can do.
11508                    String errorMessage = "Instruction set mismatch, "
11509                            + ((requirer == null) ? "[caller]" : requirer)
11510                            + " requires " + requiredInstructionSet + " whereas " + ps
11511                            + " requires " + instructionSet;
11512                    Slog.w(TAG, errorMessage);
11513                }
11514
11515                if (requiredInstructionSet == null) {
11516                    requiredInstructionSet = instructionSet;
11517                    requirer = ps;
11518                }
11519            }
11520        }
11521
11522        if (requiredInstructionSet != null) {
11523            String adjustedAbi;
11524            if (requirer != null) {
11525                // requirer != null implies that either scannedPackage was null or that scannedPackage
11526                // did not require an ABI, in which case we have to adjust scannedPackage to match
11527                // the ABI of the set (which is the same as requirer's ABI)
11528                adjustedAbi = requirer.primaryCpuAbiString;
11529                if (scannedPackage != null) {
11530                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11531                }
11532            } else {
11533                // requirer == null implies that we're updating all ABIs in the set to
11534                // match scannedPackage.
11535                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11536            }
11537
11538            for (PackageSetting ps : packagesForUser) {
11539                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11540                    if (ps.primaryCpuAbiString != null) {
11541                        continue;
11542                    }
11543
11544                    ps.primaryCpuAbiString = adjustedAbi;
11545                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11546                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11547                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11548                        if (DEBUG_ABI_SELECTION) {
11549                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11550                                    + " (requirer="
11551                                    + (requirer != null ? requirer.pkg : "null")
11552                                    + ", scannedPackage="
11553                                    + (scannedPackage != null ? scannedPackage : "null")
11554                                    + ")");
11555                        }
11556                        if (changedAbiCodePath == null) {
11557                            changedAbiCodePath = new ArrayList<>();
11558                        }
11559                        changedAbiCodePath.add(ps.codePathString);
11560                    }
11561                }
11562            }
11563        }
11564        return changedAbiCodePath;
11565    }
11566
11567    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11568        synchronized (mPackages) {
11569            mResolverReplaced = true;
11570            // Set up information for custom user intent resolution activity.
11571            mResolveActivity.applicationInfo = pkg.applicationInfo;
11572            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11573            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11574            mResolveActivity.processName = pkg.applicationInfo.packageName;
11575            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11576            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11577                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11578            mResolveActivity.theme = 0;
11579            mResolveActivity.exported = true;
11580            mResolveActivity.enabled = true;
11581            mResolveInfo.activityInfo = mResolveActivity;
11582            mResolveInfo.priority = 0;
11583            mResolveInfo.preferredOrder = 0;
11584            mResolveInfo.match = 0;
11585            mResolveComponentName = mCustomResolverComponentName;
11586            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11587                    mResolveComponentName);
11588        }
11589    }
11590
11591    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11592        if (installerActivity == null) {
11593            if (DEBUG_EPHEMERAL) {
11594                Slog.d(TAG, "Clear ephemeral installer activity");
11595            }
11596            mInstantAppInstallerActivity = null;
11597            return;
11598        }
11599
11600        if (DEBUG_EPHEMERAL) {
11601            Slog.d(TAG, "Set ephemeral installer activity: "
11602                    + installerActivity.getComponentName());
11603        }
11604        // Set up information for ephemeral installer activity
11605        mInstantAppInstallerActivity = installerActivity;
11606        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11607                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11608        mInstantAppInstallerActivity.exported = true;
11609        mInstantAppInstallerActivity.enabled = true;
11610        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11611        mInstantAppInstallerInfo.priority = 0;
11612        mInstantAppInstallerInfo.preferredOrder = 1;
11613        mInstantAppInstallerInfo.isDefault = true;
11614        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11615                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11616    }
11617
11618    private static String calculateBundledApkRoot(final String codePathString) {
11619        final File codePath = new File(codePathString);
11620        final File codeRoot;
11621        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11622            codeRoot = Environment.getRootDirectory();
11623        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11624            codeRoot = Environment.getOemDirectory();
11625        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11626            codeRoot = Environment.getVendorDirectory();
11627        } else {
11628            // Unrecognized code path; take its top real segment as the apk root:
11629            // e.g. /something/app/blah.apk => /something
11630            try {
11631                File f = codePath.getCanonicalFile();
11632                File parent = f.getParentFile();    // non-null because codePath is a file
11633                File tmp;
11634                while ((tmp = parent.getParentFile()) != null) {
11635                    f = parent;
11636                    parent = tmp;
11637                }
11638                codeRoot = f;
11639                Slog.w(TAG, "Unrecognized code path "
11640                        + codePath + " - using " + codeRoot);
11641            } catch (IOException e) {
11642                // Can't canonicalize the code path -- shenanigans?
11643                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11644                return Environment.getRootDirectory().getPath();
11645            }
11646        }
11647        return codeRoot.getPath();
11648    }
11649
11650    /**
11651     * Derive and set the location of native libraries for the given package,
11652     * which varies depending on where and how the package was installed.
11653     */
11654    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11655        final ApplicationInfo info = pkg.applicationInfo;
11656        final String codePath = pkg.codePath;
11657        final File codeFile = new File(codePath);
11658        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11659        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11660
11661        info.nativeLibraryRootDir = null;
11662        info.nativeLibraryRootRequiresIsa = false;
11663        info.nativeLibraryDir = null;
11664        info.secondaryNativeLibraryDir = null;
11665
11666        if (isApkFile(codeFile)) {
11667            // Monolithic install
11668            if (bundledApp) {
11669                // If "/system/lib64/apkname" exists, assume that is the per-package
11670                // native library directory to use; otherwise use "/system/lib/apkname".
11671                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11672                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11673                        getPrimaryInstructionSet(info));
11674
11675                // This is a bundled system app so choose the path based on the ABI.
11676                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11677                // is just the default path.
11678                final String apkName = deriveCodePathName(codePath);
11679                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11680                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11681                        apkName).getAbsolutePath();
11682
11683                if (info.secondaryCpuAbi != null) {
11684                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11685                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11686                            secondaryLibDir, apkName).getAbsolutePath();
11687                }
11688            } else if (asecApp) {
11689                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11690                        .getAbsolutePath();
11691            } else {
11692                final String apkName = deriveCodePathName(codePath);
11693                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11694                        .getAbsolutePath();
11695            }
11696
11697            info.nativeLibraryRootRequiresIsa = false;
11698            info.nativeLibraryDir = info.nativeLibraryRootDir;
11699        } else {
11700            // Cluster install
11701            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11702            info.nativeLibraryRootRequiresIsa = true;
11703
11704            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11705                    getPrimaryInstructionSet(info)).getAbsolutePath();
11706
11707            if (info.secondaryCpuAbi != null) {
11708                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11709                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11710            }
11711        }
11712    }
11713
11714    /**
11715     * Calculate the abis and roots for a bundled app. These can uniquely
11716     * be determined from the contents of the system partition, i.e whether
11717     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11718     * of this information, and instead assume that the system was built
11719     * sensibly.
11720     */
11721    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11722                                           PackageSetting pkgSetting) {
11723        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11724
11725        // If "/system/lib64/apkname" exists, assume that is the per-package
11726        // native library directory to use; otherwise use "/system/lib/apkname".
11727        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11728        setBundledAppAbi(pkg, apkRoot, apkName);
11729        // pkgSetting might be null during rescan following uninstall of updates
11730        // to a bundled app, so accommodate that possibility.  The settings in
11731        // that case will be established later from the parsed package.
11732        //
11733        // If the settings aren't null, sync them up with what we've just derived.
11734        // note that apkRoot isn't stored in the package settings.
11735        if (pkgSetting != null) {
11736            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11737            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11738        }
11739    }
11740
11741    /**
11742     * Deduces the ABI of a bundled app and sets the relevant fields on the
11743     * parsed pkg object.
11744     *
11745     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11746     *        under which system libraries are installed.
11747     * @param apkName the name of the installed package.
11748     */
11749    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11750        final File codeFile = new File(pkg.codePath);
11751
11752        final boolean has64BitLibs;
11753        final boolean has32BitLibs;
11754        if (isApkFile(codeFile)) {
11755            // Monolithic install
11756            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11757            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11758        } else {
11759            // Cluster install
11760            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11761            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11762                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11763                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11764                has64BitLibs = (new File(rootDir, isa)).exists();
11765            } else {
11766                has64BitLibs = false;
11767            }
11768            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11769                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11770                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11771                has32BitLibs = (new File(rootDir, isa)).exists();
11772            } else {
11773                has32BitLibs = false;
11774            }
11775        }
11776
11777        if (has64BitLibs && !has32BitLibs) {
11778            // The package has 64 bit libs, but not 32 bit libs. Its primary
11779            // ABI should be 64 bit. We can safely assume here that the bundled
11780            // native libraries correspond to the most preferred ABI in the list.
11781
11782            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11783            pkg.applicationInfo.secondaryCpuAbi = null;
11784        } else if (has32BitLibs && !has64BitLibs) {
11785            // The package has 32 bit libs but not 64 bit libs. Its primary
11786            // ABI should be 32 bit.
11787
11788            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11789            pkg.applicationInfo.secondaryCpuAbi = null;
11790        } else if (has32BitLibs && has64BitLibs) {
11791            // The application has both 64 and 32 bit bundled libraries. We check
11792            // here that the app declares multiArch support, and warn if it doesn't.
11793            //
11794            // We will be lenient here and record both ABIs. The primary will be the
11795            // ABI that's higher on the list, i.e, a device that's configured to prefer
11796            // 64 bit apps will see a 64 bit primary ABI,
11797
11798            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11799                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11800            }
11801
11802            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11803                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11804                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11805            } else {
11806                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11807                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11808            }
11809        } else {
11810            pkg.applicationInfo.primaryCpuAbi = null;
11811            pkg.applicationInfo.secondaryCpuAbi = null;
11812        }
11813    }
11814
11815    private void killApplication(String pkgName, int appId, String reason) {
11816        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11817    }
11818
11819    private void killApplication(String pkgName, int appId, int userId, String reason) {
11820        // Request the ActivityManager to kill the process(only for existing packages)
11821        // so that we do not end up in a confused state while the user is still using the older
11822        // version of the application while the new one gets installed.
11823        final long token = Binder.clearCallingIdentity();
11824        try {
11825            IActivityManager am = ActivityManager.getService();
11826            if (am != null) {
11827                try {
11828                    am.killApplication(pkgName, appId, userId, reason);
11829                } catch (RemoteException e) {
11830                }
11831            }
11832        } finally {
11833            Binder.restoreCallingIdentity(token);
11834        }
11835    }
11836
11837    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11838        // Remove the parent package setting
11839        PackageSetting ps = (PackageSetting) pkg.mExtras;
11840        if (ps != null) {
11841            removePackageLI(ps, chatty);
11842        }
11843        // Remove the child package setting
11844        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11845        for (int i = 0; i < childCount; i++) {
11846            PackageParser.Package childPkg = pkg.childPackages.get(i);
11847            ps = (PackageSetting) childPkg.mExtras;
11848            if (ps != null) {
11849                removePackageLI(ps, chatty);
11850            }
11851        }
11852    }
11853
11854    void removePackageLI(PackageSetting ps, boolean chatty) {
11855        if (DEBUG_INSTALL) {
11856            if (chatty)
11857                Log.d(TAG, "Removing package " + ps.name);
11858        }
11859
11860        // writer
11861        synchronized (mPackages) {
11862            mPackages.remove(ps.name);
11863            final PackageParser.Package pkg = ps.pkg;
11864            if (pkg != null) {
11865                cleanPackageDataStructuresLILPw(pkg, chatty);
11866            }
11867        }
11868    }
11869
11870    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11871        if (DEBUG_INSTALL) {
11872            if (chatty)
11873                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11874        }
11875
11876        // writer
11877        synchronized (mPackages) {
11878            // Remove the parent package
11879            mPackages.remove(pkg.applicationInfo.packageName);
11880            cleanPackageDataStructuresLILPw(pkg, chatty);
11881
11882            // Remove the child packages
11883            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11884            for (int i = 0; i < childCount; i++) {
11885                PackageParser.Package childPkg = pkg.childPackages.get(i);
11886                mPackages.remove(childPkg.applicationInfo.packageName);
11887                cleanPackageDataStructuresLILPw(childPkg, chatty);
11888            }
11889        }
11890    }
11891
11892    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11893        int N = pkg.providers.size();
11894        StringBuilder r = null;
11895        int i;
11896        for (i=0; i<N; i++) {
11897            PackageParser.Provider p = pkg.providers.get(i);
11898            mProviders.removeProvider(p);
11899            if (p.info.authority == null) {
11900
11901                /* There was another ContentProvider with this authority when
11902                 * this app was installed so this authority is null,
11903                 * Ignore it as we don't have to unregister the provider.
11904                 */
11905                continue;
11906            }
11907            String names[] = p.info.authority.split(";");
11908            for (int j = 0; j < names.length; j++) {
11909                if (mProvidersByAuthority.get(names[j]) == p) {
11910                    mProvidersByAuthority.remove(names[j]);
11911                    if (DEBUG_REMOVE) {
11912                        if (chatty)
11913                            Log.d(TAG, "Unregistered content provider: " + names[j]
11914                                    + ", className = " + p.info.name + ", isSyncable = "
11915                                    + p.info.isSyncable);
11916                    }
11917                }
11918            }
11919            if (DEBUG_REMOVE && chatty) {
11920                if (r == null) {
11921                    r = new StringBuilder(256);
11922                } else {
11923                    r.append(' ');
11924                }
11925                r.append(p.info.name);
11926            }
11927        }
11928        if (r != null) {
11929            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11930        }
11931
11932        N = pkg.services.size();
11933        r = null;
11934        for (i=0; i<N; i++) {
11935            PackageParser.Service s = pkg.services.get(i);
11936            mServices.removeService(s);
11937            if (chatty) {
11938                if (r == null) {
11939                    r = new StringBuilder(256);
11940                } else {
11941                    r.append(' ');
11942                }
11943                r.append(s.info.name);
11944            }
11945        }
11946        if (r != null) {
11947            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11948        }
11949
11950        N = pkg.receivers.size();
11951        r = null;
11952        for (i=0; i<N; i++) {
11953            PackageParser.Activity a = pkg.receivers.get(i);
11954            mReceivers.removeActivity(a, "receiver");
11955            if (DEBUG_REMOVE && chatty) {
11956                if (r == null) {
11957                    r = new StringBuilder(256);
11958                } else {
11959                    r.append(' ');
11960                }
11961                r.append(a.info.name);
11962            }
11963        }
11964        if (r != null) {
11965            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11966        }
11967
11968        N = pkg.activities.size();
11969        r = null;
11970        for (i=0; i<N; i++) {
11971            PackageParser.Activity a = pkg.activities.get(i);
11972            mActivities.removeActivity(a, "activity");
11973            if (DEBUG_REMOVE && chatty) {
11974                if (r == null) {
11975                    r = new StringBuilder(256);
11976                } else {
11977                    r.append(' ');
11978                }
11979                r.append(a.info.name);
11980            }
11981        }
11982        if (r != null) {
11983            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11984        }
11985
11986        mPermissionManager.removeAllPermissions(pkg, chatty);
11987
11988        N = pkg.instrumentation.size();
11989        r = null;
11990        for (i=0; i<N; i++) {
11991            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11992            mInstrumentation.remove(a.getComponentName());
11993            if (DEBUG_REMOVE && chatty) {
11994                if (r == null) {
11995                    r = new StringBuilder(256);
11996                } else {
11997                    r.append(' ');
11998                }
11999                r.append(a.info.name);
12000            }
12001        }
12002        if (r != null) {
12003            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12004        }
12005
12006        r = null;
12007        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12008            // Only system apps can hold shared libraries.
12009            if (pkg.libraryNames != null) {
12010                for (i = 0; i < pkg.libraryNames.size(); i++) {
12011                    String name = pkg.libraryNames.get(i);
12012                    if (removeSharedLibraryLPw(name, 0)) {
12013                        if (DEBUG_REMOVE && chatty) {
12014                            if (r == null) {
12015                                r = new StringBuilder(256);
12016                            } else {
12017                                r.append(' ');
12018                            }
12019                            r.append(name);
12020                        }
12021                    }
12022                }
12023            }
12024        }
12025
12026        r = null;
12027
12028        // Any package can hold static shared libraries.
12029        if (pkg.staticSharedLibName != null) {
12030            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12031                if (DEBUG_REMOVE && chatty) {
12032                    if (r == null) {
12033                        r = new StringBuilder(256);
12034                    } else {
12035                        r.append(' ');
12036                    }
12037                    r.append(pkg.staticSharedLibName);
12038                }
12039            }
12040        }
12041
12042        if (r != null) {
12043            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12044        }
12045    }
12046
12047
12048    final class ActivityIntentResolver
12049            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12050        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12051                boolean defaultOnly, int userId) {
12052            if (!sUserManager.exists(userId)) return null;
12053            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12054            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12055        }
12056
12057        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12058                int userId) {
12059            if (!sUserManager.exists(userId)) return null;
12060            mFlags = flags;
12061            return super.queryIntent(intent, resolvedType,
12062                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12063                    userId);
12064        }
12065
12066        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12067                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12068            if (!sUserManager.exists(userId)) return null;
12069            if (packageActivities == null) {
12070                return null;
12071            }
12072            mFlags = flags;
12073            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12074            final int N = packageActivities.size();
12075            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12076                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12077
12078            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12079            for (int i = 0; i < N; ++i) {
12080                intentFilters = packageActivities.get(i).intents;
12081                if (intentFilters != null && intentFilters.size() > 0) {
12082                    PackageParser.ActivityIntentInfo[] array =
12083                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12084                    intentFilters.toArray(array);
12085                    listCut.add(array);
12086                }
12087            }
12088            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12089        }
12090
12091        /**
12092         * Finds a privileged activity that matches the specified activity names.
12093         */
12094        private PackageParser.Activity findMatchingActivity(
12095                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12096            for (PackageParser.Activity sysActivity : activityList) {
12097                if (sysActivity.info.name.equals(activityInfo.name)) {
12098                    return sysActivity;
12099                }
12100                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12101                    return sysActivity;
12102                }
12103                if (sysActivity.info.targetActivity != null) {
12104                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12105                        return sysActivity;
12106                    }
12107                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12108                        return sysActivity;
12109                    }
12110                }
12111            }
12112            return null;
12113        }
12114
12115        public class IterGenerator<E> {
12116            public Iterator<E> generate(ActivityIntentInfo info) {
12117                return null;
12118            }
12119        }
12120
12121        public class ActionIterGenerator extends IterGenerator<String> {
12122            @Override
12123            public Iterator<String> generate(ActivityIntentInfo info) {
12124                return info.actionsIterator();
12125            }
12126        }
12127
12128        public class CategoriesIterGenerator extends IterGenerator<String> {
12129            @Override
12130            public Iterator<String> generate(ActivityIntentInfo info) {
12131                return info.categoriesIterator();
12132            }
12133        }
12134
12135        public class SchemesIterGenerator extends IterGenerator<String> {
12136            @Override
12137            public Iterator<String> generate(ActivityIntentInfo info) {
12138                return info.schemesIterator();
12139            }
12140        }
12141
12142        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12143            @Override
12144            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12145                return info.authoritiesIterator();
12146            }
12147        }
12148
12149        /**
12150         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12151         * MODIFIED. Do not pass in a list that should not be changed.
12152         */
12153        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12154                IterGenerator<T> generator, Iterator<T> searchIterator) {
12155            // loop through the set of actions; every one must be found in the intent filter
12156            while (searchIterator.hasNext()) {
12157                // we must have at least one filter in the list to consider a match
12158                if (intentList.size() == 0) {
12159                    break;
12160                }
12161
12162                final T searchAction = searchIterator.next();
12163
12164                // loop through the set of intent filters
12165                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12166                while (intentIter.hasNext()) {
12167                    final ActivityIntentInfo intentInfo = intentIter.next();
12168                    boolean selectionFound = false;
12169
12170                    // loop through the intent filter's selection criteria; at least one
12171                    // of them must match the searched criteria
12172                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12173                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12174                        final T intentSelection = intentSelectionIter.next();
12175                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12176                            selectionFound = true;
12177                            break;
12178                        }
12179                    }
12180
12181                    // the selection criteria wasn't found in this filter's set; this filter
12182                    // is not a potential match
12183                    if (!selectionFound) {
12184                        intentIter.remove();
12185                    }
12186                }
12187            }
12188        }
12189
12190        private boolean isProtectedAction(ActivityIntentInfo filter) {
12191            final Iterator<String> actionsIter = filter.actionsIterator();
12192            while (actionsIter != null && actionsIter.hasNext()) {
12193                final String filterAction = actionsIter.next();
12194                if (PROTECTED_ACTIONS.contains(filterAction)) {
12195                    return true;
12196                }
12197            }
12198            return false;
12199        }
12200
12201        /**
12202         * Adjusts the priority of the given intent filter according to policy.
12203         * <p>
12204         * <ul>
12205         * <li>The priority for non privileged applications is capped to '0'</li>
12206         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12207         * <li>The priority for unbundled updates to privileged applications is capped to the
12208         *      priority defined on the system partition</li>
12209         * </ul>
12210         * <p>
12211         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12212         * allowed to obtain any priority on any action.
12213         */
12214        private void adjustPriority(
12215                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12216            // nothing to do; priority is fine as-is
12217            if (intent.getPriority() <= 0) {
12218                return;
12219            }
12220
12221            final ActivityInfo activityInfo = intent.activity.info;
12222            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12223
12224            final boolean privilegedApp =
12225                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12226            if (!privilegedApp) {
12227                // non-privileged applications can never define a priority >0
12228                if (DEBUG_FILTERS) {
12229                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12230                            + " package: " + applicationInfo.packageName
12231                            + " activity: " + intent.activity.className
12232                            + " origPrio: " + intent.getPriority());
12233                }
12234                intent.setPriority(0);
12235                return;
12236            }
12237
12238            if (systemActivities == null) {
12239                // the system package is not disabled; we're parsing the system partition
12240                if (isProtectedAction(intent)) {
12241                    if (mDeferProtectedFilters) {
12242                        // We can't deal with these just yet. No component should ever obtain a
12243                        // >0 priority for a protected actions, with ONE exception -- the setup
12244                        // wizard. The setup wizard, however, cannot be known until we're able to
12245                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12246                        // until all intent filters have been processed. Chicken, meet egg.
12247                        // Let the filter temporarily have a high priority and rectify the
12248                        // priorities after all system packages have been scanned.
12249                        mProtectedFilters.add(intent);
12250                        if (DEBUG_FILTERS) {
12251                            Slog.i(TAG, "Protected action; save for later;"
12252                                    + " package: " + applicationInfo.packageName
12253                                    + " activity: " + intent.activity.className
12254                                    + " origPrio: " + intent.getPriority());
12255                        }
12256                        return;
12257                    } else {
12258                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12259                            Slog.i(TAG, "No setup wizard;"
12260                                + " All protected intents capped to priority 0");
12261                        }
12262                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12263                            if (DEBUG_FILTERS) {
12264                                Slog.i(TAG, "Found setup wizard;"
12265                                    + " allow priority " + intent.getPriority() + ";"
12266                                    + " package: " + intent.activity.info.packageName
12267                                    + " activity: " + intent.activity.className
12268                                    + " priority: " + intent.getPriority());
12269                            }
12270                            // setup wizard gets whatever it wants
12271                            return;
12272                        }
12273                        if (DEBUG_FILTERS) {
12274                            Slog.i(TAG, "Protected action; cap priority to 0;"
12275                                    + " package: " + intent.activity.info.packageName
12276                                    + " activity: " + intent.activity.className
12277                                    + " origPrio: " + intent.getPriority());
12278                        }
12279                        intent.setPriority(0);
12280                        return;
12281                    }
12282                }
12283                // privileged apps on the system image get whatever priority they request
12284                return;
12285            }
12286
12287            // privileged app unbundled update ... try to find the same activity
12288            final PackageParser.Activity foundActivity =
12289                    findMatchingActivity(systemActivities, activityInfo);
12290            if (foundActivity == null) {
12291                // this is a new activity; it cannot obtain >0 priority
12292                if (DEBUG_FILTERS) {
12293                    Slog.i(TAG, "New activity; cap priority to 0;"
12294                            + " package: " + applicationInfo.packageName
12295                            + " activity: " + intent.activity.className
12296                            + " origPrio: " + intent.getPriority());
12297                }
12298                intent.setPriority(0);
12299                return;
12300            }
12301
12302            // found activity, now check for filter equivalence
12303
12304            // a shallow copy is enough; we modify the list, not its contents
12305            final List<ActivityIntentInfo> intentListCopy =
12306                    new ArrayList<>(foundActivity.intents);
12307            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12308
12309            // find matching action subsets
12310            final Iterator<String> actionsIterator = intent.actionsIterator();
12311            if (actionsIterator != null) {
12312                getIntentListSubset(
12313                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12314                if (intentListCopy.size() == 0) {
12315                    // no more intents to match; we're not equivalent
12316                    if (DEBUG_FILTERS) {
12317                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12318                                + " package: " + applicationInfo.packageName
12319                                + " activity: " + intent.activity.className
12320                                + " origPrio: " + intent.getPriority());
12321                    }
12322                    intent.setPriority(0);
12323                    return;
12324                }
12325            }
12326
12327            // find matching category subsets
12328            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12329            if (categoriesIterator != null) {
12330                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12331                        categoriesIterator);
12332                if (intentListCopy.size() == 0) {
12333                    // no more intents to match; we're not equivalent
12334                    if (DEBUG_FILTERS) {
12335                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12336                                + " package: " + applicationInfo.packageName
12337                                + " activity: " + intent.activity.className
12338                                + " origPrio: " + intent.getPriority());
12339                    }
12340                    intent.setPriority(0);
12341                    return;
12342                }
12343            }
12344
12345            // find matching schemes subsets
12346            final Iterator<String> schemesIterator = intent.schemesIterator();
12347            if (schemesIterator != null) {
12348                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12349                        schemesIterator);
12350                if (intentListCopy.size() == 0) {
12351                    // no more intents to match; we're not equivalent
12352                    if (DEBUG_FILTERS) {
12353                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12354                                + " package: " + applicationInfo.packageName
12355                                + " activity: " + intent.activity.className
12356                                + " origPrio: " + intent.getPriority());
12357                    }
12358                    intent.setPriority(0);
12359                    return;
12360                }
12361            }
12362
12363            // find matching authorities subsets
12364            final Iterator<IntentFilter.AuthorityEntry>
12365                    authoritiesIterator = intent.authoritiesIterator();
12366            if (authoritiesIterator != null) {
12367                getIntentListSubset(intentListCopy,
12368                        new AuthoritiesIterGenerator(),
12369                        authoritiesIterator);
12370                if (intentListCopy.size() == 0) {
12371                    // no more intents to match; we're not equivalent
12372                    if (DEBUG_FILTERS) {
12373                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12374                                + " package: " + applicationInfo.packageName
12375                                + " activity: " + intent.activity.className
12376                                + " origPrio: " + intent.getPriority());
12377                    }
12378                    intent.setPriority(0);
12379                    return;
12380                }
12381            }
12382
12383            // we found matching filter(s); app gets the max priority of all intents
12384            int cappedPriority = 0;
12385            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12386                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12387            }
12388            if (intent.getPriority() > cappedPriority) {
12389                if (DEBUG_FILTERS) {
12390                    Slog.i(TAG, "Found matching filter(s);"
12391                            + " cap priority to " + cappedPriority + ";"
12392                            + " package: " + applicationInfo.packageName
12393                            + " activity: " + intent.activity.className
12394                            + " origPrio: " + intent.getPriority());
12395                }
12396                intent.setPriority(cappedPriority);
12397                return;
12398            }
12399            // all this for nothing; the requested priority was <= what was on the system
12400        }
12401
12402        public final void addActivity(PackageParser.Activity a, String type) {
12403            mActivities.put(a.getComponentName(), a);
12404            if (DEBUG_SHOW_INFO)
12405                Log.v(
12406                TAG, "  " + type + " " +
12407                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12408            if (DEBUG_SHOW_INFO)
12409                Log.v(TAG, "    Class=" + a.info.name);
12410            final int NI = a.intents.size();
12411            for (int j=0; j<NI; j++) {
12412                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12413                if ("activity".equals(type)) {
12414                    final PackageSetting ps =
12415                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12416                    final List<PackageParser.Activity> systemActivities =
12417                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12418                    adjustPriority(systemActivities, intent);
12419                }
12420                if (DEBUG_SHOW_INFO) {
12421                    Log.v(TAG, "    IntentFilter:");
12422                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12423                }
12424                if (!intent.debugCheck()) {
12425                    Log.w(TAG, "==> For Activity " + a.info.name);
12426                }
12427                addFilter(intent);
12428            }
12429        }
12430
12431        public final void removeActivity(PackageParser.Activity a, String type) {
12432            mActivities.remove(a.getComponentName());
12433            if (DEBUG_SHOW_INFO) {
12434                Log.v(TAG, "  " + type + " "
12435                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12436                                : a.info.name) + ":");
12437                Log.v(TAG, "    Class=" + a.info.name);
12438            }
12439            final int NI = a.intents.size();
12440            for (int j=0; j<NI; j++) {
12441                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12442                if (DEBUG_SHOW_INFO) {
12443                    Log.v(TAG, "    IntentFilter:");
12444                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12445                }
12446                removeFilter(intent);
12447            }
12448        }
12449
12450        @Override
12451        protected boolean allowFilterResult(
12452                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12453            ActivityInfo filterAi = filter.activity.info;
12454            for (int i=dest.size()-1; i>=0; i--) {
12455                ActivityInfo destAi = dest.get(i).activityInfo;
12456                if (destAi.name == filterAi.name
12457                        && destAi.packageName == filterAi.packageName) {
12458                    return false;
12459                }
12460            }
12461            return true;
12462        }
12463
12464        @Override
12465        protected ActivityIntentInfo[] newArray(int size) {
12466            return new ActivityIntentInfo[size];
12467        }
12468
12469        @Override
12470        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12471            if (!sUserManager.exists(userId)) return true;
12472            PackageParser.Package p = filter.activity.owner;
12473            if (p != null) {
12474                PackageSetting ps = (PackageSetting)p.mExtras;
12475                if (ps != null) {
12476                    // System apps are never considered stopped for purposes of
12477                    // filtering, because there may be no way for the user to
12478                    // actually re-launch them.
12479                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12480                            && ps.getStopped(userId);
12481                }
12482            }
12483            return false;
12484        }
12485
12486        @Override
12487        protected boolean isPackageForFilter(String packageName,
12488                PackageParser.ActivityIntentInfo info) {
12489            return packageName.equals(info.activity.owner.packageName);
12490        }
12491
12492        @Override
12493        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12494                int match, int userId) {
12495            if (!sUserManager.exists(userId)) return null;
12496            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12497                return null;
12498            }
12499            final PackageParser.Activity activity = info.activity;
12500            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12501            if (ps == null) {
12502                return null;
12503            }
12504            final PackageUserState userState = ps.readUserState(userId);
12505            ActivityInfo ai =
12506                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12507            if (ai == null) {
12508                return null;
12509            }
12510            final boolean matchExplicitlyVisibleOnly =
12511                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12512            final boolean matchVisibleToInstantApp =
12513                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12514            final boolean componentVisible =
12515                    matchVisibleToInstantApp
12516                    && info.isVisibleToInstantApp()
12517                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12518            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12519            // throw out filters that aren't visible to ephemeral apps
12520            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12521                return null;
12522            }
12523            // throw out instant app filters if we're not explicitly requesting them
12524            if (!matchInstantApp && userState.instantApp) {
12525                return null;
12526            }
12527            // throw out instant app filters if updates are available; will trigger
12528            // instant app resolution
12529            if (userState.instantApp && ps.isUpdateAvailable()) {
12530                return null;
12531            }
12532            final ResolveInfo res = new ResolveInfo();
12533            res.activityInfo = ai;
12534            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12535                res.filter = info;
12536            }
12537            if (info != null) {
12538                res.handleAllWebDataURI = info.handleAllWebDataURI();
12539            }
12540            res.priority = info.getPriority();
12541            res.preferredOrder = activity.owner.mPreferredOrder;
12542            //System.out.println("Result: " + res.activityInfo.className +
12543            //                   " = " + res.priority);
12544            res.match = match;
12545            res.isDefault = info.hasDefault;
12546            res.labelRes = info.labelRes;
12547            res.nonLocalizedLabel = info.nonLocalizedLabel;
12548            if (userNeedsBadging(userId)) {
12549                res.noResourceId = true;
12550            } else {
12551                res.icon = info.icon;
12552            }
12553            res.iconResourceId = info.icon;
12554            res.system = res.activityInfo.applicationInfo.isSystemApp();
12555            res.isInstantAppAvailable = userState.instantApp;
12556            return res;
12557        }
12558
12559        @Override
12560        protected void sortResults(List<ResolveInfo> results) {
12561            Collections.sort(results, mResolvePrioritySorter);
12562        }
12563
12564        @Override
12565        protected void dumpFilter(PrintWriter out, String prefix,
12566                PackageParser.ActivityIntentInfo filter) {
12567            out.print(prefix); out.print(
12568                    Integer.toHexString(System.identityHashCode(filter.activity)));
12569                    out.print(' ');
12570                    filter.activity.printComponentShortName(out);
12571                    out.print(" filter ");
12572                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12573        }
12574
12575        @Override
12576        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12577            return filter.activity;
12578        }
12579
12580        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12581            PackageParser.Activity activity = (PackageParser.Activity)label;
12582            out.print(prefix); out.print(
12583                    Integer.toHexString(System.identityHashCode(activity)));
12584                    out.print(' ');
12585                    activity.printComponentShortName(out);
12586            if (count > 1) {
12587                out.print(" ("); out.print(count); out.print(" filters)");
12588            }
12589            out.println();
12590        }
12591
12592        // Keys are String (activity class name), values are Activity.
12593        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12594                = new ArrayMap<ComponentName, PackageParser.Activity>();
12595        private int mFlags;
12596    }
12597
12598    private final class ServiceIntentResolver
12599            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12600        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12601                boolean defaultOnly, int userId) {
12602            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12603            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12604        }
12605
12606        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12607                int userId) {
12608            if (!sUserManager.exists(userId)) return null;
12609            mFlags = flags;
12610            return super.queryIntent(intent, resolvedType,
12611                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12612                    userId);
12613        }
12614
12615        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12616                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12617            if (!sUserManager.exists(userId)) return null;
12618            if (packageServices == null) {
12619                return null;
12620            }
12621            mFlags = flags;
12622            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12623            final int N = packageServices.size();
12624            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12625                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12626
12627            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12628            for (int i = 0; i < N; ++i) {
12629                intentFilters = packageServices.get(i).intents;
12630                if (intentFilters != null && intentFilters.size() > 0) {
12631                    PackageParser.ServiceIntentInfo[] array =
12632                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12633                    intentFilters.toArray(array);
12634                    listCut.add(array);
12635                }
12636            }
12637            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12638        }
12639
12640        public final void addService(PackageParser.Service s) {
12641            mServices.put(s.getComponentName(), s);
12642            if (DEBUG_SHOW_INFO) {
12643                Log.v(TAG, "  "
12644                        + (s.info.nonLocalizedLabel != null
12645                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12646                Log.v(TAG, "    Class=" + s.info.name);
12647            }
12648            final int NI = s.intents.size();
12649            int j;
12650            for (j=0; j<NI; j++) {
12651                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12652                if (DEBUG_SHOW_INFO) {
12653                    Log.v(TAG, "    IntentFilter:");
12654                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12655                }
12656                if (!intent.debugCheck()) {
12657                    Log.w(TAG, "==> For Service " + s.info.name);
12658                }
12659                addFilter(intent);
12660            }
12661        }
12662
12663        public final void removeService(PackageParser.Service s) {
12664            mServices.remove(s.getComponentName());
12665            if (DEBUG_SHOW_INFO) {
12666                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12667                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12668                Log.v(TAG, "    Class=" + s.info.name);
12669            }
12670            final int NI = s.intents.size();
12671            int j;
12672            for (j=0; j<NI; j++) {
12673                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12674                if (DEBUG_SHOW_INFO) {
12675                    Log.v(TAG, "    IntentFilter:");
12676                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12677                }
12678                removeFilter(intent);
12679            }
12680        }
12681
12682        @Override
12683        protected boolean allowFilterResult(
12684                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12685            ServiceInfo filterSi = filter.service.info;
12686            for (int i=dest.size()-1; i>=0; i--) {
12687                ServiceInfo destAi = dest.get(i).serviceInfo;
12688                if (destAi.name == filterSi.name
12689                        && destAi.packageName == filterSi.packageName) {
12690                    return false;
12691                }
12692            }
12693            return true;
12694        }
12695
12696        @Override
12697        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12698            return new PackageParser.ServiceIntentInfo[size];
12699        }
12700
12701        @Override
12702        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12703            if (!sUserManager.exists(userId)) return true;
12704            PackageParser.Package p = filter.service.owner;
12705            if (p != null) {
12706                PackageSetting ps = (PackageSetting)p.mExtras;
12707                if (ps != null) {
12708                    // System apps are never considered stopped for purposes of
12709                    // filtering, because there may be no way for the user to
12710                    // actually re-launch them.
12711                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12712                            && ps.getStopped(userId);
12713                }
12714            }
12715            return false;
12716        }
12717
12718        @Override
12719        protected boolean isPackageForFilter(String packageName,
12720                PackageParser.ServiceIntentInfo info) {
12721            return packageName.equals(info.service.owner.packageName);
12722        }
12723
12724        @Override
12725        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12726                int match, int userId) {
12727            if (!sUserManager.exists(userId)) return null;
12728            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12729            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12730                return null;
12731            }
12732            final PackageParser.Service service = info.service;
12733            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12734            if (ps == null) {
12735                return null;
12736            }
12737            final PackageUserState userState = ps.readUserState(userId);
12738            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12739                    userState, userId);
12740            if (si == null) {
12741                return null;
12742            }
12743            final boolean matchVisibleToInstantApp =
12744                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12745            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12746            // throw out filters that aren't visible to ephemeral apps
12747            if (matchVisibleToInstantApp
12748                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12749                return null;
12750            }
12751            // throw out ephemeral filters if we're not explicitly requesting them
12752            if (!isInstantApp && userState.instantApp) {
12753                return null;
12754            }
12755            // throw out instant app filters if updates are available; will trigger
12756            // instant app resolution
12757            if (userState.instantApp && ps.isUpdateAvailable()) {
12758                return null;
12759            }
12760            final ResolveInfo res = new ResolveInfo();
12761            res.serviceInfo = si;
12762            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12763                res.filter = filter;
12764            }
12765            res.priority = info.getPriority();
12766            res.preferredOrder = service.owner.mPreferredOrder;
12767            res.match = match;
12768            res.isDefault = info.hasDefault;
12769            res.labelRes = info.labelRes;
12770            res.nonLocalizedLabel = info.nonLocalizedLabel;
12771            res.icon = info.icon;
12772            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12773            return res;
12774        }
12775
12776        @Override
12777        protected void sortResults(List<ResolveInfo> results) {
12778            Collections.sort(results, mResolvePrioritySorter);
12779        }
12780
12781        @Override
12782        protected void dumpFilter(PrintWriter out, String prefix,
12783                PackageParser.ServiceIntentInfo filter) {
12784            out.print(prefix); out.print(
12785                    Integer.toHexString(System.identityHashCode(filter.service)));
12786                    out.print(' ');
12787                    filter.service.printComponentShortName(out);
12788                    out.print(" filter ");
12789                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12790                    if (filter.service.info.permission != null) {
12791                        out.print(" permission "); out.println(filter.service.info.permission);
12792                    } else {
12793                        out.println();
12794                    }
12795        }
12796
12797        @Override
12798        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12799            return filter.service;
12800        }
12801
12802        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12803            PackageParser.Service service = (PackageParser.Service)label;
12804            out.print(prefix); out.print(
12805                    Integer.toHexString(System.identityHashCode(service)));
12806                    out.print(' ');
12807                    service.printComponentShortName(out);
12808            if (count > 1) {
12809                out.print(" ("); out.print(count); out.print(" filters)");
12810            }
12811            out.println();
12812        }
12813
12814//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12815//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12816//            final List<ResolveInfo> retList = Lists.newArrayList();
12817//            while (i.hasNext()) {
12818//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12819//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12820//                    retList.add(resolveInfo);
12821//                }
12822//            }
12823//            return retList;
12824//        }
12825
12826        // Keys are String (activity class name), values are Activity.
12827        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12828                = new ArrayMap<ComponentName, PackageParser.Service>();
12829        private int mFlags;
12830    }
12831
12832    private final class ProviderIntentResolver
12833            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12834        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12835                boolean defaultOnly, int userId) {
12836            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12837            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12838        }
12839
12840        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12841                int userId) {
12842            if (!sUserManager.exists(userId))
12843                return null;
12844            mFlags = flags;
12845            return super.queryIntent(intent, resolvedType,
12846                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12847                    userId);
12848        }
12849
12850        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12851                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12852            if (!sUserManager.exists(userId))
12853                return null;
12854            if (packageProviders == null) {
12855                return null;
12856            }
12857            mFlags = flags;
12858            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12859            final int N = packageProviders.size();
12860            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12861                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12862
12863            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12864            for (int i = 0; i < N; ++i) {
12865                intentFilters = packageProviders.get(i).intents;
12866                if (intentFilters != null && intentFilters.size() > 0) {
12867                    PackageParser.ProviderIntentInfo[] array =
12868                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12869                    intentFilters.toArray(array);
12870                    listCut.add(array);
12871                }
12872            }
12873            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12874        }
12875
12876        public final void addProvider(PackageParser.Provider p) {
12877            if (mProviders.containsKey(p.getComponentName())) {
12878                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12879                return;
12880            }
12881
12882            mProviders.put(p.getComponentName(), p);
12883            if (DEBUG_SHOW_INFO) {
12884                Log.v(TAG, "  "
12885                        + (p.info.nonLocalizedLabel != null
12886                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12887                Log.v(TAG, "    Class=" + p.info.name);
12888            }
12889            final int NI = p.intents.size();
12890            int j;
12891            for (j = 0; j < NI; j++) {
12892                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12893                if (DEBUG_SHOW_INFO) {
12894                    Log.v(TAG, "    IntentFilter:");
12895                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12896                }
12897                if (!intent.debugCheck()) {
12898                    Log.w(TAG, "==> For Provider " + p.info.name);
12899                }
12900                addFilter(intent);
12901            }
12902        }
12903
12904        public final void removeProvider(PackageParser.Provider p) {
12905            mProviders.remove(p.getComponentName());
12906            if (DEBUG_SHOW_INFO) {
12907                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12908                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12909                Log.v(TAG, "    Class=" + p.info.name);
12910            }
12911            final int NI = p.intents.size();
12912            int j;
12913            for (j = 0; j < NI; j++) {
12914                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12915                if (DEBUG_SHOW_INFO) {
12916                    Log.v(TAG, "    IntentFilter:");
12917                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12918                }
12919                removeFilter(intent);
12920            }
12921        }
12922
12923        @Override
12924        protected boolean allowFilterResult(
12925                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12926            ProviderInfo filterPi = filter.provider.info;
12927            for (int i = dest.size() - 1; i >= 0; i--) {
12928                ProviderInfo destPi = dest.get(i).providerInfo;
12929                if (destPi.name == filterPi.name
12930                        && destPi.packageName == filterPi.packageName) {
12931                    return false;
12932                }
12933            }
12934            return true;
12935        }
12936
12937        @Override
12938        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12939            return new PackageParser.ProviderIntentInfo[size];
12940        }
12941
12942        @Override
12943        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12944            if (!sUserManager.exists(userId))
12945                return true;
12946            PackageParser.Package p = filter.provider.owner;
12947            if (p != null) {
12948                PackageSetting ps = (PackageSetting) p.mExtras;
12949                if (ps != null) {
12950                    // System apps are never considered stopped for purposes of
12951                    // filtering, because there may be no way for the user to
12952                    // actually re-launch them.
12953                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12954                            && ps.getStopped(userId);
12955                }
12956            }
12957            return false;
12958        }
12959
12960        @Override
12961        protected boolean isPackageForFilter(String packageName,
12962                PackageParser.ProviderIntentInfo info) {
12963            return packageName.equals(info.provider.owner.packageName);
12964        }
12965
12966        @Override
12967        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12968                int match, int userId) {
12969            if (!sUserManager.exists(userId))
12970                return null;
12971            final PackageParser.ProviderIntentInfo info = filter;
12972            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12973                return null;
12974            }
12975            final PackageParser.Provider provider = info.provider;
12976            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12977            if (ps == null) {
12978                return null;
12979            }
12980            final PackageUserState userState = ps.readUserState(userId);
12981            final boolean matchVisibleToInstantApp =
12982                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12983            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12984            // throw out filters that aren't visible to instant applications
12985            if (matchVisibleToInstantApp
12986                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12987                return null;
12988            }
12989            // throw out instant application filters if we're not explicitly requesting them
12990            if (!isInstantApp && userState.instantApp) {
12991                return null;
12992            }
12993            // throw out instant application filters if updates are available; will trigger
12994            // instant application resolution
12995            if (userState.instantApp && ps.isUpdateAvailable()) {
12996                return null;
12997            }
12998            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12999                    userState, userId);
13000            if (pi == null) {
13001                return null;
13002            }
13003            final ResolveInfo res = new ResolveInfo();
13004            res.providerInfo = pi;
13005            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13006                res.filter = filter;
13007            }
13008            res.priority = info.getPriority();
13009            res.preferredOrder = provider.owner.mPreferredOrder;
13010            res.match = match;
13011            res.isDefault = info.hasDefault;
13012            res.labelRes = info.labelRes;
13013            res.nonLocalizedLabel = info.nonLocalizedLabel;
13014            res.icon = info.icon;
13015            res.system = res.providerInfo.applicationInfo.isSystemApp();
13016            return res;
13017        }
13018
13019        @Override
13020        protected void sortResults(List<ResolveInfo> results) {
13021            Collections.sort(results, mResolvePrioritySorter);
13022        }
13023
13024        @Override
13025        protected void dumpFilter(PrintWriter out, String prefix,
13026                PackageParser.ProviderIntentInfo filter) {
13027            out.print(prefix);
13028            out.print(
13029                    Integer.toHexString(System.identityHashCode(filter.provider)));
13030            out.print(' ');
13031            filter.provider.printComponentShortName(out);
13032            out.print(" filter ");
13033            out.println(Integer.toHexString(System.identityHashCode(filter)));
13034        }
13035
13036        @Override
13037        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13038            return filter.provider;
13039        }
13040
13041        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13042            PackageParser.Provider provider = (PackageParser.Provider)label;
13043            out.print(prefix); out.print(
13044                    Integer.toHexString(System.identityHashCode(provider)));
13045                    out.print(' ');
13046                    provider.printComponentShortName(out);
13047            if (count > 1) {
13048                out.print(" ("); out.print(count); out.print(" filters)");
13049            }
13050            out.println();
13051        }
13052
13053        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13054                = new ArrayMap<ComponentName, PackageParser.Provider>();
13055        private int mFlags;
13056    }
13057
13058    static final class EphemeralIntentResolver
13059            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13060        /**
13061         * The result that has the highest defined order. Ordering applies on a
13062         * per-package basis. Mapping is from package name to Pair of order and
13063         * EphemeralResolveInfo.
13064         * <p>
13065         * NOTE: This is implemented as a field variable for convenience and efficiency.
13066         * By having a field variable, we're able to track filter ordering as soon as
13067         * a non-zero order is defined. Otherwise, multiple loops across the result set
13068         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13069         * this needs to be contained entirely within {@link #filterResults}.
13070         */
13071        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13072
13073        @Override
13074        protected AuxiliaryResolveInfo[] newArray(int size) {
13075            return new AuxiliaryResolveInfo[size];
13076        }
13077
13078        @Override
13079        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13080            return true;
13081        }
13082
13083        @Override
13084        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13085                int userId) {
13086            if (!sUserManager.exists(userId)) {
13087                return null;
13088            }
13089            final String packageName = responseObj.resolveInfo.getPackageName();
13090            final Integer order = responseObj.getOrder();
13091            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13092                    mOrderResult.get(packageName);
13093            // ordering is enabled and this item's order isn't high enough
13094            if (lastOrderResult != null && lastOrderResult.first >= order) {
13095                return null;
13096            }
13097            final InstantAppResolveInfo res = responseObj.resolveInfo;
13098            if (order > 0) {
13099                // non-zero order, enable ordering
13100                mOrderResult.put(packageName, new Pair<>(order, res));
13101            }
13102            return responseObj;
13103        }
13104
13105        @Override
13106        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13107            // only do work if ordering is enabled [most of the time it won't be]
13108            if (mOrderResult.size() == 0) {
13109                return;
13110            }
13111            int resultSize = results.size();
13112            for (int i = 0; i < resultSize; i++) {
13113                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13114                final String packageName = info.getPackageName();
13115                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13116                if (savedInfo == null) {
13117                    // package doesn't having ordering
13118                    continue;
13119                }
13120                if (savedInfo.second == info) {
13121                    // circled back to the highest ordered item; remove from order list
13122                    mOrderResult.remove(packageName);
13123                    if (mOrderResult.size() == 0) {
13124                        // no more ordered items
13125                        break;
13126                    }
13127                    continue;
13128                }
13129                // item has a worse order, remove it from the result list
13130                results.remove(i);
13131                resultSize--;
13132                i--;
13133            }
13134        }
13135    }
13136
13137    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13138            new Comparator<ResolveInfo>() {
13139        public int compare(ResolveInfo r1, ResolveInfo r2) {
13140            int v1 = r1.priority;
13141            int v2 = r2.priority;
13142            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13143            if (v1 != v2) {
13144                return (v1 > v2) ? -1 : 1;
13145            }
13146            v1 = r1.preferredOrder;
13147            v2 = r2.preferredOrder;
13148            if (v1 != v2) {
13149                return (v1 > v2) ? -1 : 1;
13150            }
13151            if (r1.isDefault != r2.isDefault) {
13152                return r1.isDefault ? -1 : 1;
13153            }
13154            v1 = r1.match;
13155            v2 = r2.match;
13156            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13157            if (v1 != v2) {
13158                return (v1 > v2) ? -1 : 1;
13159            }
13160            if (r1.system != r2.system) {
13161                return r1.system ? -1 : 1;
13162            }
13163            if (r1.activityInfo != null) {
13164                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13165            }
13166            if (r1.serviceInfo != null) {
13167                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13168            }
13169            if (r1.providerInfo != null) {
13170                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13171            }
13172            return 0;
13173        }
13174    };
13175
13176    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13177            new Comparator<ProviderInfo>() {
13178        public int compare(ProviderInfo p1, ProviderInfo p2) {
13179            final int v1 = p1.initOrder;
13180            final int v2 = p2.initOrder;
13181            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13182        }
13183    };
13184
13185    @Override
13186    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13187            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13188            final int[] userIds, int[] instantUserIds) {
13189        mHandler.post(new Runnable() {
13190            @Override
13191            public void run() {
13192                try {
13193                    final IActivityManager am = ActivityManager.getService();
13194                    if (am == null) return;
13195                    final int[] resolvedUserIds;
13196                    if (userIds == null) {
13197                        resolvedUserIds = am.getRunningUserIds();
13198                    } else {
13199                        resolvedUserIds = userIds;
13200                    }
13201                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13202                            resolvedUserIds, false);
13203                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13204                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13205                                instantUserIds, true);
13206                    }
13207                } catch (RemoteException ex) {
13208                }
13209            }
13210        });
13211    }
13212
13213    @Override
13214    public void notifyPackageAdded(String packageName) {
13215        final PackageListObserver[] observers;
13216        synchronized (mPackages) {
13217            if (mPackageListObservers.size() == 0) {
13218                return;
13219            }
13220            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13221        }
13222        for (int i = observers.length - 1; i >= 0; --i) {
13223            observers[i].onPackageAdded(packageName);
13224        }
13225    }
13226
13227    @Override
13228    public void notifyPackageRemoved(String packageName) {
13229        final PackageListObserver[] observers;
13230        synchronized (mPackages) {
13231            if (mPackageListObservers.size() == 0) {
13232                return;
13233            }
13234            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13235        }
13236        for (int i = observers.length - 1; i >= 0; --i) {
13237            observers[i].onPackageRemoved(packageName);
13238        }
13239    }
13240
13241    /**
13242     * Sends a broadcast for the given action.
13243     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13244     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13245     * the system and applications allowed to see instant applications to receive package
13246     * lifecycle events for instant applications.
13247     */
13248    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13249            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13250            int[] userIds, boolean isInstantApp)
13251                    throws RemoteException {
13252        for (int id : userIds) {
13253            final Intent intent = new Intent(action,
13254                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13255            final String[] requiredPermissions =
13256                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13257            if (extras != null) {
13258                intent.putExtras(extras);
13259            }
13260            if (targetPkg != null) {
13261                intent.setPackage(targetPkg);
13262            }
13263            // Modify the UID when posting to other users
13264            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13265            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13266                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13267                intent.putExtra(Intent.EXTRA_UID, uid);
13268            }
13269            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13270            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13271            if (DEBUG_BROADCASTS) {
13272                RuntimeException here = new RuntimeException("here");
13273                here.fillInStackTrace();
13274                Slog.d(TAG, "Sending to user " + id + ": "
13275                        + intent.toShortString(false, true, false, false)
13276                        + " " + intent.getExtras(), here);
13277            }
13278            am.broadcastIntent(null, intent, null, finishedReceiver,
13279                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13280                    null, finishedReceiver != null, false, id);
13281        }
13282    }
13283
13284    /**
13285     * Check if the external storage media is available. This is true if there
13286     * is a mounted external storage medium or if the external storage is
13287     * emulated.
13288     */
13289    private boolean isExternalMediaAvailable() {
13290        return mMediaMounted || Environment.isExternalStorageEmulated();
13291    }
13292
13293    @Override
13294    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13295        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13296            return null;
13297        }
13298        if (!isExternalMediaAvailable()) {
13299                // If the external storage is no longer mounted at this point,
13300                // the caller may not have been able to delete all of this
13301                // packages files and can not delete any more.  Bail.
13302            return null;
13303        }
13304        synchronized (mPackages) {
13305            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13306            if (lastPackage != null) {
13307                pkgs.remove(lastPackage);
13308            }
13309            if (pkgs.size() > 0) {
13310                return pkgs.get(0);
13311            }
13312        }
13313        return null;
13314    }
13315
13316    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13317        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13318                userId, andCode ? 1 : 0, packageName);
13319        if (mSystemReady) {
13320            msg.sendToTarget();
13321        } else {
13322            if (mPostSystemReadyMessages == null) {
13323                mPostSystemReadyMessages = new ArrayList<>();
13324            }
13325            mPostSystemReadyMessages.add(msg);
13326        }
13327    }
13328
13329    void startCleaningPackages() {
13330        // reader
13331        if (!isExternalMediaAvailable()) {
13332            return;
13333        }
13334        synchronized (mPackages) {
13335            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13336                return;
13337            }
13338        }
13339        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13340        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13341        IActivityManager am = ActivityManager.getService();
13342        if (am != null) {
13343            int dcsUid = -1;
13344            synchronized (mPackages) {
13345                if (!mDefaultContainerWhitelisted) {
13346                    mDefaultContainerWhitelisted = true;
13347                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13348                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13349                }
13350            }
13351            try {
13352                if (dcsUid > 0) {
13353                    am.backgroundWhitelistUid(dcsUid);
13354                }
13355                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13356                        UserHandle.USER_SYSTEM);
13357            } catch (RemoteException e) {
13358            }
13359        }
13360    }
13361
13362    /**
13363     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13364     * it is acting on behalf on an enterprise or the user).
13365     *
13366     * Note that the ordering of the conditionals in this method is important. The checks we perform
13367     * are as follows, in this order:
13368     *
13369     * 1) If the install is being performed by a system app, we can trust the app to have set the
13370     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13371     *    what it is.
13372     * 2) If the install is being performed by a device or profile owner app, the install reason
13373     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13374     *    set the install reason correctly. If the app targets an older SDK version where install
13375     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13376     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13377     * 3) In all other cases, the install is being performed by a regular app that is neither part
13378     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13379     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13380     *    set to enterprise policy and if so, change it to unknown instead.
13381     */
13382    private int fixUpInstallReason(String installerPackageName, int installerUid,
13383            int installReason) {
13384        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13385                == PERMISSION_GRANTED) {
13386            // If the install is being performed by a system app, we trust that app to have set the
13387            // install reason correctly.
13388            return installReason;
13389        }
13390
13391        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13392            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13393        if (dpm != null) {
13394            ComponentName owner = null;
13395            try {
13396                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13397                if (owner == null) {
13398                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13399                }
13400            } catch (RemoteException e) {
13401            }
13402            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13403                // If the install is being performed by a device or profile owner, the install
13404                // reason should be enterprise policy.
13405                return PackageManager.INSTALL_REASON_POLICY;
13406            }
13407        }
13408
13409        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13410            // If the install is being performed by a regular app (i.e. neither system app nor
13411            // device or profile owner), we have no reason to believe that the app is acting on
13412            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13413            // change it to unknown instead.
13414            return PackageManager.INSTALL_REASON_UNKNOWN;
13415        }
13416
13417        // If the install is being performed by a regular app and the install reason was set to any
13418        // value but enterprise policy, leave the install reason unchanged.
13419        return installReason;
13420    }
13421
13422    void installStage(String packageName, File stagedDir,
13423            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13424            String installerPackageName, int installerUid, UserHandle user,
13425            PackageParser.SigningDetails signingDetails) {
13426        if (DEBUG_EPHEMERAL) {
13427            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13428                Slog.d(TAG, "Ephemeral install of " + packageName);
13429            }
13430        }
13431        final VerificationInfo verificationInfo = new VerificationInfo(
13432                sessionParams.originatingUri, sessionParams.referrerUri,
13433                sessionParams.originatingUid, installerUid);
13434
13435        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13436
13437        final Message msg = mHandler.obtainMessage(INIT_COPY);
13438        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13439                sessionParams.installReason);
13440        final InstallParams params = new InstallParams(origin, null, observer,
13441                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13442                verificationInfo, user, sessionParams.abiOverride,
13443                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13444        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13445        msg.obj = params;
13446
13447        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13448                System.identityHashCode(msg.obj));
13449        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13450                System.identityHashCode(msg.obj));
13451
13452        mHandler.sendMessage(msg);
13453    }
13454
13455    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13456            int userId) {
13457        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13458        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13459        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13460        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13461        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13462                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13463
13464        // Send a session commit broadcast
13465        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13466        info.installReason = pkgSetting.getInstallReason(userId);
13467        info.appPackageName = packageName;
13468        sendSessionCommitBroadcast(info, userId);
13469    }
13470
13471    @Override
13472    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13473            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13474        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13475            return;
13476        }
13477        Bundle extras = new Bundle(1);
13478        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13479        final int uid = UserHandle.getUid(
13480                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13481        extras.putInt(Intent.EXTRA_UID, uid);
13482
13483        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13484                packageName, extras, 0, null, null, userIds, instantUserIds);
13485        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13486            mHandler.post(() -> {
13487                        for (int userId : userIds) {
13488                            sendBootCompletedBroadcastToSystemApp(
13489                                    packageName, includeStopped, userId);
13490                        }
13491                    }
13492            );
13493        }
13494    }
13495
13496    /**
13497     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13498     * automatically without needing an explicit launch.
13499     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13500     */
13501    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13502            int userId) {
13503        // If user is not running, the app didn't miss any broadcast
13504        if (!mUserManagerInternal.isUserRunning(userId)) {
13505            return;
13506        }
13507        final IActivityManager am = ActivityManager.getService();
13508        try {
13509            // Deliver LOCKED_BOOT_COMPLETED first
13510            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13511                    .setPackage(packageName);
13512            if (includeStopped) {
13513                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13514            }
13515            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13516            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13517                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13518
13519            // Deliver BOOT_COMPLETED only if user is unlocked
13520            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13521                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13522                if (includeStopped) {
13523                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13524                }
13525                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13526                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13527            }
13528        } catch (RemoteException e) {
13529            throw e.rethrowFromSystemServer();
13530        }
13531    }
13532
13533    @Override
13534    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13535            int userId) {
13536        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13537        PackageSetting pkgSetting;
13538        final int callingUid = Binder.getCallingUid();
13539        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13540                true /* requireFullPermission */, true /* checkShell */,
13541                "setApplicationHiddenSetting for user " + userId);
13542
13543        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13544            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13545            return false;
13546        }
13547
13548        long callingId = Binder.clearCallingIdentity();
13549        try {
13550            boolean sendAdded = false;
13551            boolean sendRemoved = false;
13552            // writer
13553            synchronized (mPackages) {
13554                pkgSetting = mSettings.mPackages.get(packageName);
13555                if (pkgSetting == null) {
13556                    return false;
13557                }
13558                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13559                    return false;
13560                }
13561                // Do not allow "android" is being disabled
13562                if ("android".equals(packageName)) {
13563                    Slog.w(TAG, "Cannot hide package: android");
13564                    return false;
13565                }
13566                // Cannot hide static shared libs as they are considered
13567                // a part of the using app (emulating static linking). Also
13568                // static libs are installed always on internal storage.
13569                PackageParser.Package pkg = mPackages.get(packageName);
13570                if (pkg != null && pkg.staticSharedLibName != null) {
13571                    Slog.w(TAG, "Cannot hide package: " + packageName
13572                            + " providing static shared library: "
13573                            + pkg.staticSharedLibName);
13574                    return false;
13575                }
13576                // Only allow protected packages to hide themselves.
13577                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13578                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13579                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13580                    return false;
13581                }
13582
13583                if (pkgSetting.getHidden(userId) != hidden) {
13584                    pkgSetting.setHidden(hidden, userId);
13585                    mSettings.writePackageRestrictionsLPr(userId);
13586                    if (hidden) {
13587                        sendRemoved = true;
13588                    } else {
13589                        sendAdded = true;
13590                    }
13591                }
13592            }
13593            if (sendAdded) {
13594                sendPackageAddedForUser(packageName, pkgSetting, userId);
13595                return true;
13596            }
13597            if (sendRemoved) {
13598                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13599                        "hiding pkg");
13600                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13601                return true;
13602            }
13603        } finally {
13604            Binder.restoreCallingIdentity(callingId);
13605        }
13606        return false;
13607    }
13608
13609    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13610            int userId) {
13611        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13612        info.removedPackage = packageName;
13613        info.installerPackageName = pkgSetting.installerPackageName;
13614        info.removedUsers = new int[] {userId};
13615        info.broadcastUsers = new int[] {userId};
13616        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13617        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13618    }
13619
13620    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13621        if (pkgList.length > 0) {
13622            Bundle extras = new Bundle(1);
13623            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13624
13625            sendPackageBroadcast(
13626                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13627                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13628                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13629                    new int[] {userId}, null);
13630        }
13631    }
13632
13633    /**
13634     * Returns true if application is not found or there was an error. Otherwise it returns
13635     * the hidden state of the package for the given user.
13636     */
13637    @Override
13638    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13639        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13640        final int callingUid = Binder.getCallingUid();
13641        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13642                true /* requireFullPermission */, false /* checkShell */,
13643                "getApplicationHidden for user " + userId);
13644        PackageSetting ps;
13645        long callingId = Binder.clearCallingIdentity();
13646        try {
13647            // writer
13648            synchronized (mPackages) {
13649                ps = mSettings.mPackages.get(packageName);
13650                if (ps == null) {
13651                    return true;
13652                }
13653                if (filterAppAccessLPr(ps, callingUid, userId)) {
13654                    return true;
13655                }
13656                return ps.getHidden(userId);
13657            }
13658        } finally {
13659            Binder.restoreCallingIdentity(callingId);
13660        }
13661    }
13662
13663    /**
13664     * @hide
13665     */
13666    @Override
13667    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13668            int installReason) {
13669        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13670                null);
13671        PackageSetting pkgSetting;
13672        final int callingUid = Binder.getCallingUid();
13673        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13674                true /* requireFullPermission */, true /* checkShell */,
13675                "installExistingPackage for user " + userId);
13676        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13677            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13678        }
13679
13680        long callingId = Binder.clearCallingIdentity();
13681        try {
13682            boolean installed = false;
13683            final boolean instantApp =
13684                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13685            final boolean fullApp =
13686                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13687
13688            // writer
13689            synchronized (mPackages) {
13690                pkgSetting = mSettings.mPackages.get(packageName);
13691                if (pkgSetting == null) {
13692                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13693                }
13694                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13695                    // only allow the existing package to be used if it's installed as a full
13696                    // application for at least one user
13697                    boolean installAllowed = false;
13698                    for (int checkUserId : sUserManager.getUserIds()) {
13699                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13700                        if (installAllowed) {
13701                            break;
13702                        }
13703                    }
13704                    if (!installAllowed) {
13705                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13706                    }
13707                }
13708                if (!pkgSetting.getInstalled(userId)) {
13709                    pkgSetting.setInstalled(true, userId);
13710                    pkgSetting.setHidden(false, userId);
13711                    pkgSetting.setInstallReason(installReason, userId);
13712                    mSettings.writePackageRestrictionsLPr(userId);
13713                    mSettings.writeKernelMappingLPr(pkgSetting);
13714                    installed = true;
13715                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13716                    // upgrade app from instant to full; we don't allow app downgrade
13717                    installed = true;
13718                }
13719                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13720            }
13721
13722            if (installed) {
13723                if (pkgSetting.pkg != null) {
13724                    synchronized (mInstallLock) {
13725                        // We don't need to freeze for a brand new install
13726                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13727                    }
13728                }
13729                sendPackageAddedForUser(packageName, pkgSetting, userId);
13730                synchronized (mPackages) {
13731                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13732                }
13733            }
13734        } finally {
13735            Binder.restoreCallingIdentity(callingId);
13736        }
13737
13738        return PackageManager.INSTALL_SUCCEEDED;
13739    }
13740
13741    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13742            boolean instantApp, boolean fullApp) {
13743        // no state specified; do nothing
13744        if (!instantApp && !fullApp) {
13745            return;
13746        }
13747        if (userId != UserHandle.USER_ALL) {
13748            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13749                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13750            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13751                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13752            }
13753        } else {
13754            for (int currentUserId : sUserManager.getUserIds()) {
13755                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13756                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13757                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13758                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13759                }
13760            }
13761        }
13762    }
13763
13764    boolean isUserRestricted(int userId, String restrictionKey) {
13765        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13766        if (restrictions.getBoolean(restrictionKey, false)) {
13767            Log.w(TAG, "User is restricted: " + restrictionKey);
13768            return true;
13769        }
13770        return false;
13771    }
13772
13773    @Override
13774    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13775            int userId) {
13776        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13777        final int callingUid = Binder.getCallingUid();
13778        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13779                true /* requireFullPermission */, true /* checkShell */,
13780                "setPackagesSuspended for user " + userId);
13781
13782        if (ArrayUtils.isEmpty(packageNames)) {
13783            return packageNames;
13784        }
13785
13786        // List of package names for whom the suspended state has changed.
13787        List<String> changedPackages = new ArrayList<>(packageNames.length);
13788        // List of package names for whom the suspended state is not set as requested in this
13789        // method.
13790        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13791        long callingId = Binder.clearCallingIdentity();
13792        try {
13793            for (int i = 0; i < packageNames.length; i++) {
13794                String packageName = packageNames[i];
13795                boolean changed = false;
13796                final int appId;
13797                synchronized (mPackages) {
13798                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13799                    if (pkgSetting == null
13800                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13801                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13802                                + "\". Skipping suspending/un-suspending.");
13803                        unactionedPackages.add(packageName);
13804                        continue;
13805                    }
13806                    appId = pkgSetting.appId;
13807                    if (pkgSetting.getSuspended(userId) != suspended) {
13808                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13809                            unactionedPackages.add(packageName);
13810                            continue;
13811                        }
13812                        pkgSetting.setSuspended(suspended, userId);
13813                        mSettings.writePackageRestrictionsLPr(userId);
13814                        changed = true;
13815                        changedPackages.add(packageName);
13816                    }
13817                }
13818
13819                if (changed && suspended) {
13820                    killApplication(packageName, UserHandle.getUid(userId, appId),
13821                            "suspending package");
13822                }
13823            }
13824        } finally {
13825            Binder.restoreCallingIdentity(callingId);
13826        }
13827
13828        if (!changedPackages.isEmpty()) {
13829            sendPackagesSuspendedForUser(changedPackages.toArray(
13830                    new String[changedPackages.size()]), userId, suspended);
13831        }
13832
13833        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13834    }
13835
13836    @Override
13837    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13838        final int callingUid = Binder.getCallingUid();
13839        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13840                true /* requireFullPermission */, false /* checkShell */,
13841                "isPackageSuspendedForUser for user " + userId);
13842        synchronized (mPackages) {
13843            final PackageSetting ps = mSettings.mPackages.get(packageName);
13844            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13845                throw new IllegalArgumentException("Unknown target package: " + packageName);
13846            }
13847            return ps.getSuspended(userId);
13848        }
13849    }
13850
13851    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13852        if (isPackageDeviceAdmin(packageName, userId)) {
13853            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13854                    + "\": has an active device admin");
13855            return false;
13856        }
13857
13858        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13859        if (packageName.equals(activeLauncherPackageName)) {
13860            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13861                    + "\": contains the active launcher");
13862            return false;
13863        }
13864
13865        if (packageName.equals(mRequiredInstallerPackage)) {
13866            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13867                    + "\": required for package installation");
13868            return false;
13869        }
13870
13871        if (packageName.equals(mRequiredUninstallerPackage)) {
13872            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13873                    + "\": required for package uninstallation");
13874            return false;
13875        }
13876
13877        if (packageName.equals(mRequiredVerifierPackage)) {
13878            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13879                    + "\": required for package verification");
13880            return false;
13881        }
13882
13883        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13884            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13885                    + "\": is the default dialer");
13886            return false;
13887        }
13888
13889        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13890            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13891                    + "\": protected package");
13892            return false;
13893        }
13894
13895        // Cannot suspend static shared libs as they are considered
13896        // a part of the using app (emulating static linking). Also
13897        // static libs are installed always on internal storage.
13898        PackageParser.Package pkg = mPackages.get(packageName);
13899        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13900            Slog.w(TAG, "Cannot suspend package: " + packageName
13901                    + " providing static shared library: "
13902                    + pkg.staticSharedLibName);
13903            return false;
13904        }
13905
13906        return true;
13907    }
13908
13909    private String getActiveLauncherPackageName(int userId) {
13910        Intent intent = new Intent(Intent.ACTION_MAIN);
13911        intent.addCategory(Intent.CATEGORY_HOME);
13912        ResolveInfo resolveInfo = resolveIntent(
13913                intent,
13914                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13915                PackageManager.MATCH_DEFAULT_ONLY,
13916                userId);
13917
13918        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13919    }
13920
13921    private String getDefaultDialerPackageName(int userId) {
13922        synchronized (mPackages) {
13923            return mSettings.getDefaultDialerPackageNameLPw(userId);
13924        }
13925    }
13926
13927    @Override
13928    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13929        mContext.enforceCallingOrSelfPermission(
13930                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13931                "Only package verification agents can verify applications");
13932
13933        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13934        final PackageVerificationResponse response = new PackageVerificationResponse(
13935                verificationCode, Binder.getCallingUid());
13936        msg.arg1 = id;
13937        msg.obj = response;
13938        mHandler.sendMessage(msg);
13939    }
13940
13941    @Override
13942    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13943            long millisecondsToDelay) {
13944        mContext.enforceCallingOrSelfPermission(
13945                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13946                "Only package verification agents can extend verification timeouts");
13947
13948        final PackageVerificationState state = mPendingVerification.get(id);
13949        final PackageVerificationResponse response = new PackageVerificationResponse(
13950                verificationCodeAtTimeout, Binder.getCallingUid());
13951
13952        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13953            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13954        }
13955        if (millisecondsToDelay < 0) {
13956            millisecondsToDelay = 0;
13957        }
13958        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13959                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13960            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13961        }
13962
13963        if ((state != null) && !state.timeoutExtended()) {
13964            state.extendTimeout();
13965
13966            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13967            msg.arg1 = id;
13968            msg.obj = response;
13969            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13970        }
13971    }
13972
13973    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13974            int verificationCode, UserHandle user) {
13975        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13976        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13977        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13978        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13979        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13980
13981        mContext.sendBroadcastAsUser(intent, user,
13982                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13983    }
13984
13985    private ComponentName matchComponentForVerifier(String packageName,
13986            List<ResolveInfo> receivers) {
13987        ActivityInfo targetReceiver = null;
13988
13989        final int NR = receivers.size();
13990        for (int i = 0; i < NR; i++) {
13991            final ResolveInfo info = receivers.get(i);
13992            if (info.activityInfo == null) {
13993                continue;
13994            }
13995
13996            if (packageName.equals(info.activityInfo.packageName)) {
13997                targetReceiver = info.activityInfo;
13998                break;
13999            }
14000        }
14001
14002        if (targetReceiver == null) {
14003            return null;
14004        }
14005
14006        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14007    }
14008
14009    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14010            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14011        if (pkgInfo.verifiers.length == 0) {
14012            return null;
14013        }
14014
14015        final int N = pkgInfo.verifiers.length;
14016        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14017        for (int i = 0; i < N; i++) {
14018            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14019
14020            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14021                    receivers);
14022            if (comp == null) {
14023                continue;
14024            }
14025
14026            final int verifierUid = getUidForVerifier(verifierInfo);
14027            if (verifierUid == -1) {
14028                continue;
14029            }
14030
14031            if (DEBUG_VERIFY) {
14032                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14033                        + " with the correct signature");
14034            }
14035            sufficientVerifiers.add(comp);
14036            verificationState.addSufficientVerifier(verifierUid);
14037        }
14038
14039        return sufficientVerifiers;
14040    }
14041
14042    private int getUidForVerifier(VerifierInfo verifierInfo) {
14043        synchronized (mPackages) {
14044            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14045            if (pkg == null) {
14046                return -1;
14047            } else if (pkg.mSigningDetails.signatures.length != 1) {
14048                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14049                        + " has more than one signature; ignoring");
14050                return -1;
14051            }
14052
14053            /*
14054             * If the public key of the package's signature does not match
14055             * our expected public key, then this is a different package and
14056             * we should skip.
14057             */
14058
14059            final byte[] expectedPublicKey;
14060            try {
14061                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14062                final PublicKey publicKey = verifierSig.getPublicKey();
14063                expectedPublicKey = publicKey.getEncoded();
14064            } catch (CertificateException e) {
14065                return -1;
14066            }
14067
14068            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14069
14070            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14071                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14072                        + " does not have the expected public key; ignoring");
14073                return -1;
14074            }
14075
14076            return pkg.applicationInfo.uid;
14077        }
14078    }
14079
14080    @Override
14081    public void finishPackageInstall(int token, boolean didLaunch) {
14082        enforceSystemOrRoot("Only the system is allowed to finish installs");
14083
14084        if (DEBUG_INSTALL) {
14085            Slog.v(TAG, "BM finishing package install for " + token);
14086        }
14087        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14088
14089        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14090        mHandler.sendMessage(msg);
14091    }
14092
14093    /**
14094     * Get the verification agent timeout.  Used for both the APK verifier and the
14095     * intent filter verifier.
14096     *
14097     * @return verification timeout in milliseconds
14098     */
14099    private long getVerificationTimeout() {
14100        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14101                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14102                DEFAULT_VERIFICATION_TIMEOUT);
14103    }
14104
14105    /**
14106     * Get the default verification agent response code.
14107     *
14108     * @return default verification response code
14109     */
14110    private int getDefaultVerificationResponse(UserHandle user) {
14111        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14112            return PackageManager.VERIFICATION_REJECT;
14113        }
14114        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14115                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14116                DEFAULT_VERIFICATION_RESPONSE);
14117    }
14118
14119    /**
14120     * Check whether or not package verification has been enabled.
14121     *
14122     * @return true if verification should be performed
14123     */
14124    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14125        if (!DEFAULT_VERIFY_ENABLE) {
14126            return false;
14127        }
14128
14129        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14130
14131        // Check if installing from ADB
14132        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14133            // Do not run verification in a test harness environment
14134            if (ActivityManager.isRunningInTestHarness()) {
14135                return false;
14136            }
14137            if (ensureVerifyAppsEnabled) {
14138                return true;
14139            }
14140            // Check if the developer does not want package verification for ADB installs
14141            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14142                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14143                return false;
14144            }
14145        } else {
14146            // only when not installed from ADB, skip verification for instant apps when
14147            // the installer and verifier are the same.
14148            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14149                if (mInstantAppInstallerActivity != null
14150                        && mInstantAppInstallerActivity.packageName.equals(
14151                                mRequiredVerifierPackage)) {
14152                    try {
14153                        mContext.getSystemService(AppOpsManager.class)
14154                                .checkPackage(installerUid, mRequiredVerifierPackage);
14155                        if (DEBUG_VERIFY) {
14156                            Slog.i(TAG, "disable verification for instant app");
14157                        }
14158                        return false;
14159                    } catch (SecurityException ignore) { }
14160                }
14161            }
14162        }
14163
14164        if (ensureVerifyAppsEnabled) {
14165            return true;
14166        }
14167
14168        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14169                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14170    }
14171
14172    @Override
14173    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14174            throws RemoteException {
14175        mContext.enforceCallingOrSelfPermission(
14176                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14177                "Only intentfilter verification agents can verify applications");
14178
14179        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14180        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14181                Binder.getCallingUid(), verificationCode, failedDomains);
14182        msg.arg1 = id;
14183        msg.obj = response;
14184        mHandler.sendMessage(msg);
14185    }
14186
14187    @Override
14188    public int getIntentVerificationStatus(String packageName, int userId) {
14189        final int callingUid = Binder.getCallingUid();
14190        if (UserHandle.getUserId(callingUid) != userId) {
14191            mContext.enforceCallingOrSelfPermission(
14192                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14193                    "getIntentVerificationStatus" + userId);
14194        }
14195        if (getInstantAppPackageName(callingUid) != null) {
14196            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14197        }
14198        synchronized (mPackages) {
14199            final PackageSetting ps = mSettings.mPackages.get(packageName);
14200            if (ps == null
14201                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14202                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14203            }
14204            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14205        }
14206    }
14207
14208    @Override
14209    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14210        mContext.enforceCallingOrSelfPermission(
14211                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14212
14213        boolean result = false;
14214        synchronized (mPackages) {
14215            final PackageSetting ps = mSettings.mPackages.get(packageName);
14216            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14217                return false;
14218            }
14219            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14220        }
14221        if (result) {
14222            scheduleWritePackageRestrictionsLocked(userId);
14223        }
14224        return result;
14225    }
14226
14227    @Override
14228    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14229            String packageName) {
14230        final int callingUid = Binder.getCallingUid();
14231        if (getInstantAppPackageName(callingUid) != null) {
14232            return ParceledListSlice.emptyList();
14233        }
14234        synchronized (mPackages) {
14235            final PackageSetting ps = mSettings.mPackages.get(packageName);
14236            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14237                return ParceledListSlice.emptyList();
14238            }
14239            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14240        }
14241    }
14242
14243    @Override
14244    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14245        if (TextUtils.isEmpty(packageName)) {
14246            return ParceledListSlice.emptyList();
14247        }
14248        final int callingUid = Binder.getCallingUid();
14249        final int callingUserId = UserHandle.getUserId(callingUid);
14250        synchronized (mPackages) {
14251            PackageParser.Package pkg = mPackages.get(packageName);
14252            if (pkg == null || pkg.activities == null) {
14253                return ParceledListSlice.emptyList();
14254            }
14255            if (pkg.mExtras == null) {
14256                return ParceledListSlice.emptyList();
14257            }
14258            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14259            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14260                return ParceledListSlice.emptyList();
14261            }
14262            final int count = pkg.activities.size();
14263            ArrayList<IntentFilter> result = new ArrayList<>();
14264            for (int n=0; n<count; n++) {
14265                PackageParser.Activity activity = pkg.activities.get(n);
14266                if (activity.intents != null && activity.intents.size() > 0) {
14267                    result.addAll(activity.intents);
14268                }
14269            }
14270            return new ParceledListSlice<>(result);
14271        }
14272    }
14273
14274    @Override
14275    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14276        mContext.enforceCallingOrSelfPermission(
14277                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14278        if (UserHandle.getCallingUserId() != userId) {
14279            mContext.enforceCallingOrSelfPermission(
14280                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14281        }
14282
14283        synchronized (mPackages) {
14284            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14285            if (packageName != null) {
14286                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14287                        packageName, userId);
14288            }
14289            return result;
14290        }
14291    }
14292
14293    @Override
14294    public String getDefaultBrowserPackageName(int userId) {
14295        if (UserHandle.getCallingUserId() != userId) {
14296            mContext.enforceCallingOrSelfPermission(
14297                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14298        }
14299        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14300            return null;
14301        }
14302        synchronized (mPackages) {
14303            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14304        }
14305    }
14306
14307    /**
14308     * Get the "allow unknown sources" setting.
14309     *
14310     * @return the current "allow unknown sources" setting
14311     */
14312    private int getUnknownSourcesSettings() {
14313        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14314                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14315                -1);
14316    }
14317
14318    @Override
14319    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14320        final int callingUid = Binder.getCallingUid();
14321        if (getInstantAppPackageName(callingUid) != null) {
14322            return;
14323        }
14324        // writer
14325        synchronized (mPackages) {
14326            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14327            if (targetPackageSetting == null
14328                    || filterAppAccessLPr(
14329                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14330                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14331            }
14332
14333            PackageSetting installerPackageSetting;
14334            if (installerPackageName != null) {
14335                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14336                if (installerPackageSetting == null) {
14337                    throw new IllegalArgumentException("Unknown installer package: "
14338                            + installerPackageName);
14339                }
14340            } else {
14341                installerPackageSetting = null;
14342            }
14343
14344            Signature[] callerSignature;
14345            Object obj = mSettings.getUserIdLPr(callingUid);
14346            if (obj != null) {
14347                if (obj instanceof SharedUserSetting) {
14348                    callerSignature =
14349                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14350                } else if (obj instanceof PackageSetting) {
14351                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14352                } else {
14353                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14354                }
14355            } else {
14356                throw new SecurityException("Unknown calling UID: " + callingUid);
14357            }
14358
14359            // Verify: can't set installerPackageName to a package that is
14360            // not signed with the same cert as the caller.
14361            if (installerPackageSetting != null) {
14362                if (compareSignatures(callerSignature,
14363                        installerPackageSetting.signatures.mSigningDetails.signatures)
14364                        != PackageManager.SIGNATURE_MATCH) {
14365                    throw new SecurityException(
14366                            "Caller does not have same cert as new installer package "
14367                            + installerPackageName);
14368                }
14369            }
14370
14371            // Verify: if target already has an installer package, it must
14372            // be signed with the same cert as the caller.
14373            if (targetPackageSetting.installerPackageName != null) {
14374                PackageSetting setting = mSettings.mPackages.get(
14375                        targetPackageSetting.installerPackageName);
14376                // If the currently set package isn't valid, then it's always
14377                // okay to change it.
14378                if (setting != null) {
14379                    if (compareSignatures(callerSignature,
14380                            setting.signatures.mSigningDetails.signatures)
14381                            != PackageManager.SIGNATURE_MATCH) {
14382                        throw new SecurityException(
14383                                "Caller does not have same cert as old installer package "
14384                                + targetPackageSetting.installerPackageName);
14385                    }
14386                }
14387            }
14388
14389            // Okay!
14390            targetPackageSetting.installerPackageName = installerPackageName;
14391            if (installerPackageName != null) {
14392                mSettings.mInstallerPackages.add(installerPackageName);
14393            }
14394            scheduleWriteSettingsLocked();
14395        }
14396    }
14397
14398    @Override
14399    public void setApplicationCategoryHint(String packageName, int categoryHint,
14400            String callerPackageName) {
14401        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14402            throw new SecurityException("Instant applications don't have access to this method");
14403        }
14404        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14405                callerPackageName);
14406        synchronized (mPackages) {
14407            PackageSetting ps = mSettings.mPackages.get(packageName);
14408            if (ps == null) {
14409                throw new IllegalArgumentException("Unknown target package " + packageName);
14410            }
14411            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14412                throw new IllegalArgumentException("Unknown target package " + packageName);
14413            }
14414            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14415                throw new IllegalArgumentException("Calling package " + callerPackageName
14416                        + " is not installer for " + packageName);
14417            }
14418
14419            if (ps.categoryHint != categoryHint) {
14420                ps.categoryHint = categoryHint;
14421                scheduleWriteSettingsLocked();
14422            }
14423        }
14424    }
14425
14426    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14427        // Queue up an async operation since the package installation may take a little while.
14428        mHandler.post(new Runnable() {
14429            public void run() {
14430                mHandler.removeCallbacks(this);
14431                 // Result object to be returned
14432                PackageInstalledInfo res = new PackageInstalledInfo();
14433                res.setReturnCode(currentStatus);
14434                res.uid = -1;
14435                res.pkg = null;
14436                res.removedInfo = null;
14437                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14438                    args.doPreInstall(res.returnCode);
14439                    synchronized (mInstallLock) {
14440                        installPackageTracedLI(args, res);
14441                    }
14442                    args.doPostInstall(res.returnCode, res.uid);
14443                }
14444
14445                // A restore should be performed at this point if (a) the install
14446                // succeeded, (b) the operation is not an update, and (c) the new
14447                // package has not opted out of backup participation.
14448                final boolean update = res.removedInfo != null
14449                        && res.removedInfo.removedPackage != null;
14450                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14451                boolean doRestore = !update
14452                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14453
14454                // Set up the post-install work request bookkeeping.  This will be used
14455                // and cleaned up by the post-install event handling regardless of whether
14456                // there's a restore pass performed.  Token values are >= 1.
14457                int token;
14458                if (mNextInstallToken < 0) mNextInstallToken = 1;
14459                token = mNextInstallToken++;
14460
14461                PostInstallData data = new PostInstallData(args, res);
14462                mRunningInstalls.put(token, data);
14463                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14464
14465                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14466                    // Pass responsibility to the Backup Manager.  It will perform a
14467                    // restore if appropriate, then pass responsibility back to the
14468                    // Package Manager to run the post-install observer callbacks
14469                    // and broadcasts.
14470                    IBackupManager bm = IBackupManager.Stub.asInterface(
14471                            ServiceManager.getService(Context.BACKUP_SERVICE));
14472                    if (bm != null) {
14473                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14474                                + " to BM for possible restore");
14475                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14476                        try {
14477                            // TODO: http://b/22388012
14478                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14479                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14480                            } else {
14481                                doRestore = false;
14482                            }
14483                        } catch (RemoteException e) {
14484                            // can't happen; the backup manager is local
14485                        } catch (Exception e) {
14486                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14487                            doRestore = false;
14488                        }
14489                    } else {
14490                        Slog.e(TAG, "Backup Manager not found!");
14491                        doRestore = false;
14492                    }
14493                }
14494
14495                if (!doRestore) {
14496                    // No restore possible, or the Backup Manager was mysteriously not
14497                    // available -- just fire the post-install work request directly.
14498                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14499
14500                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14501
14502                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14503                    mHandler.sendMessage(msg);
14504                }
14505            }
14506        });
14507    }
14508
14509    /**
14510     * Callback from PackageSettings whenever an app is first transitioned out of the
14511     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14512     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14513     * here whether the app is the target of an ongoing install, and only send the
14514     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14515     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14516     * handling.
14517     */
14518    void notifyFirstLaunch(final String packageName, final String installerPackage,
14519            final int userId) {
14520        // Serialize this with the rest of the install-process message chain.  In the
14521        // restore-at-install case, this Runnable will necessarily run before the
14522        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14523        // are coherent.  In the non-restore case, the app has already completed install
14524        // and been launched through some other means, so it is not in a problematic
14525        // state for observers to see the FIRST_LAUNCH signal.
14526        mHandler.post(new Runnable() {
14527            @Override
14528            public void run() {
14529                for (int i = 0; i < mRunningInstalls.size(); i++) {
14530                    final PostInstallData data = mRunningInstalls.valueAt(i);
14531                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14532                        continue;
14533                    }
14534                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14535                        // right package; but is it for the right user?
14536                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14537                            if (userId == data.res.newUsers[uIndex]) {
14538                                if (DEBUG_BACKUP) {
14539                                    Slog.i(TAG, "Package " + packageName
14540                                            + " being restored so deferring FIRST_LAUNCH");
14541                                }
14542                                return;
14543                            }
14544                        }
14545                    }
14546                }
14547                // didn't find it, so not being restored
14548                if (DEBUG_BACKUP) {
14549                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14550                }
14551                final boolean isInstantApp = isInstantApp(packageName, userId);
14552                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14553                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14554                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14555            }
14556        });
14557    }
14558
14559    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14560            int[] userIds, int[] instantUserIds) {
14561        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14562                installerPkg, null, userIds, instantUserIds);
14563    }
14564
14565    private abstract class HandlerParams {
14566        private static final int MAX_RETRIES = 4;
14567
14568        /**
14569         * Number of times startCopy() has been attempted and had a non-fatal
14570         * error.
14571         */
14572        private int mRetries = 0;
14573
14574        /** User handle for the user requesting the information or installation. */
14575        private final UserHandle mUser;
14576        String traceMethod;
14577        int traceCookie;
14578
14579        HandlerParams(UserHandle user) {
14580            mUser = user;
14581        }
14582
14583        UserHandle getUser() {
14584            return mUser;
14585        }
14586
14587        HandlerParams setTraceMethod(String traceMethod) {
14588            this.traceMethod = traceMethod;
14589            return this;
14590        }
14591
14592        HandlerParams setTraceCookie(int traceCookie) {
14593            this.traceCookie = traceCookie;
14594            return this;
14595        }
14596
14597        final boolean startCopy() {
14598            boolean res;
14599            try {
14600                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14601
14602                if (++mRetries > MAX_RETRIES) {
14603                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14604                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14605                    handleServiceError();
14606                    return false;
14607                } else {
14608                    handleStartCopy();
14609                    res = true;
14610                }
14611            } catch (RemoteException e) {
14612                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14613                mHandler.sendEmptyMessage(MCS_RECONNECT);
14614                res = false;
14615            }
14616            handleReturnCode();
14617            return res;
14618        }
14619
14620        final void serviceError() {
14621            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14622            handleServiceError();
14623            handleReturnCode();
14624        }
14625
14626        abstract void handleStartCopy() throws RemoteException;
14627        abstract void handleServiceError();
14628        abstract void handleReturnCode();
14629    }
14630
14631    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14632        for (File path : paths) {
14633            try {
14634                mcs.clearDirectory(path.getAbsolutePath());
14635            } catch (RemoteException e) {
14636            }
14637        }
14638    }
14639
14640    static class OriginInfo {
14641        /**
14642         * Location where install is coming from, before it has been
14643         * copied/renamed into place. This could be a single monolithic APK
14644         * file, or a cluster directory. This location may be untrusted.
14645         */
14646        final File file;
14647
14648        /**
14649         * Flag indicating that {@link #file} or {@link #cid} has already been
14650         * staged, meaning downstream users don't need to defensively copy the
14651         * contents.
14652         */
14653        final boolean staged;
14654
14655        /**
14656         * Flag indicating that {@link #file} or {@link #cid} is an already
14657         * installed app that is being moved.
14658         */
14659        final boolean existing;
14660
14661        final String resolvedPath;
14662        final File resolvedFile;
14663
14664        static OriginInfo fromNothing() {
14665            return new OriginInfo(null, false, false);
14666        }
14667
14668        static OriginInfo fromUntrustedFile(File file) {
14669            return new OriginInfo(file, false, false);
14670        }
14671
14672        static OriginInfo fromExistingFile(File file) {
14673            return new OriginInfo(file, false, true);
14674        }
14675
14676        static OriginInfo fromStagedFile(File file) {
14677            return new OriginInfo(file, true, false);
14678        }
14679
14680        private OriginInfo(File file, boolean staged, boolean existing) {
14681            this.file = file;
14682            this.staged = staged;
14683            this.existing = existing;
14684
14685            if (file != null) {
14686                resolvedPath = file.getAbsolutePath();
14687                resolvedFile = file;
14688            } else {
14689                resolvedPath = null;
14690                resolvedFile = null;
14691            }
14692        }
14693    }
14694
14695    static class MoveInfo {
14696        final int moveId;
14697        final String fromUuid;
14698        final String toUuid;
14699        final String packageName;
14700        final String dataAppName;
14701        final int appId;
14702        final String seinfo;
14703        final int targetSdkVersion;
14704
14705        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14706                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14707            this.moveId = moveId;
14708            this.fromUuid = fromUuid;
14709            this.toUuid = toUuid;
14710            this.packageName = packageName;
14711            this.dataAppName = dataAppName;
14712            this.appId = appId;
14713            this.seinfo = seinfo;
14714            this.targetSdkVersion = targetSdkVersion;
14715        }
14716    }
14717
14718    static class VerificationInfo {
14719        /** A constant used to indicate that a uid value is not present. */
14720        public static final int NO_UID = -1;
14721
14722        /** URI referencing where the package was downloaded from. */
14723        final Uri originatingUri;
14724
14725        /** HTTP referrer URI associated with the originatingURI. */
14726        final Uri referrer;
14727
14728        /** UID of the application that the install request originated from. */
14729        final int originatingUid;
14730
14731        /** UID of application requesting the install */
14732        final int installerUid;
14733
14734        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14735            this.originatingUri = originatingUri;
14736            this.referrer = referrer;
14737            this.originatingUid = originatingUid;
14738            this.installerUid = installerUid;
14739        }
14740    }
14741
14742    class InstallParams extends HandlerParams {
14743        final OriginInfo origin;
14744        final MoveInfo move;
14745        final IPackageInstallObserver2 observer;
14746        int installFlags;
14747        final String installerPackageName;
14748        final String volumeUuid;
14749        private InstallArgs mArgs;
14750        private int mRet;
14751        final String packageAbiOverride;
14752        final String[] grantedRuntimePermissions;
14753        final VerificationInfo verificationInfo;
14754        final PackageParser.SigningDetails signingDetails;
14755        final int installReason;
14756
14757        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14758                int installFlags, String installerPackageName, String volumeUuid,
14759                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14760                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14761            super(user);
14762            this.origin = origin;
14763            this.move = move;
14764            this.observer = observer;
14765            this.installFlags = installFlags;
14766            this.installerPackageName = installerPackageName;
14767            this.volumeUuid = volumeUuid;
14768            this.verificationInfo = verificationInfo;
14769            this.packageAbiOverride = packageAbiOverride;
14770            this.grantedRuntimePermissions = grantedPermissions;
14771            this.signingDetails = signingDetails;
14772            this.installReason = installReason;
14773        }
14774
14775        @Override
14776        public String toString() {
14777            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14778                    + " file=" + origin.file + "}";
14779        }
14780
14781        private int installLocationPolicy(PackageInfoLite pkgLite) {
14782            String packageName = pkgLite.packageName;
14783            int installLocation = pkgLite.installLocation;
14784            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14785            // reader
14786            synchronized (mPackages) {
14787                // Currently installed package which the new package is attempting to replace or
14788                // null if no such package is installed.
14789                PackageParser.Package installedPkg = mPackages.get(packageName);
14790                // Package which currently owns the data which the new package will own if installed.
14791                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14792                // will be null whereas dataOwnerPkg will contain information about the package
14793                // which was uninstalled while keeping its data.
14794                PackageParser.Package dataOwnerPkg = installedPkg;
14795                if (dataOwnerPkg  == null) {
14796                    PackageSetting ps = mSettings.mPackages.get(packageName);
14797                    if (ps != null) {
14798                        dataOwnerPkg = ps.pkg;
14799                    }
14800                }
14801
14802                if (dataOwnerPkg != null) {
14803                    // If installed, the package will get access to data left on the device by its
14804                    // predecessor. As a security measure, this is permited only if this is not a
14805                    // version downgrade or if the predecessor package is marked as debuggable and
14806                    // a downgrade is explicitly requested.
14807                    //
14808                    // On debuggable platform builds, downgrades are permitted even for
14809                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14810                    // not offer security guarantees and thus it's OK to disable some security
14811                    // mechanisms to make debugging/testing easier on those builds. However, even on
14812                    // debuggable builds downgrades of packages are permitted only if requested via
14813                    // installFlags. This is because we aim to keep the behavior of debuggable
14814                    // platform builds as close as possible to the behavior of non-debuggable
14815                    // platform builds.
14816                    final boolean downgradeRequested =
14817                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14818                    final boolean packageDebuggable =
14819                                (dataOwnerPkg.applicationInfo.flags
14820                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14821                    final boolean downgradePermitted =
14822                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14823                    if (!downgradePermitted) {
14824                        try {
14825                            checkDowngrade(dataOwnerPkg, pkgLite);
14826                        } catch (PackageManagerException e) {
14827                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14828                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14829                        }
14830                    }
14831                }
14832
14833                if (installedPkg != null) {
14834                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14835                        // Check for updated system application.
14836                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14837                            if (onSd) {
14838                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14839                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14840                            }
14841                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14842                        } else {
14843                            if (onSd) {
14844                                // Install flag overrides everything.
14845                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14846                            }
14847                            // If current upgrade specifies particular preference
14848                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14849                                // Application explicitly specified internal.
14850                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14851                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14852                                // App explictly prefers external. Let policy decide
14853                            } else {
14854                                // Prefer previous location
14855                                if (isExternal(installedPkg)) {
14856                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14857                                }
14858                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14859                            }
14860                        }
14861                    } else {
14862                        // Invalid install. Return error code
14863                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14864                    }
14865                }
14866            }
14867            // All the special cases have been taken care of.
14868            // Return result based on recommended install location.
14869            if (onSd) {
14870                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14871            }
14872            return pkgLite.recommendedInstallLocation;
14873        }
14874
14875        /*
14876         * Invoke remote method to get package information and install
14877         * location values. Override install location based on default
14878         * policy if needed and then create install arguments based
14879         * on the install location.
14880         */
14881        public void handleStartCopy() throws RemoteException {
14882            int ret = PackageManager.INSTALL_SUCCEEDED;
14883
14884            // If we're already staged, we've firmly committed to an install location
14885            if (origin.staged) {
14886                if (origin.file != null) {
14887                    installFlags |= PackageManager.INSTALL_INTERNAL;
14888                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14889                } else {
14890                    throw new IllegalStateException("Invalid stage location");
14891                }
14892            }
14893
14894            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14895            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14896            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14897            PackageInfoLite pkgLite = null;
14898
14899            if (onInt && onSd) {
14900                // Check if both bits are set.
14901                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14902                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14903            } else if (onSd && ephemeral) {
14904                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14905                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14906            } else {
14907                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14908                        packageAbiOverride);
14909
14910                if (DEBUG_EPHEMERAL && ephemeral) {
14911                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14912                }
14913
14914                /*
14915                 * If we have too little free space, try to free cache
14916                 * before giving up.
14917                 */
14918                if (!origin.staged && pkgLite.recommendedInstallLocation
14919                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14920                    // TODO: focus freeing disk space on the target device
14921                    final StorageManager storage = StorageManager.from(mContext);
14922                    final long lowThreshold = storage.getStorageLowBytes(
14923                            Environment.getDataDirectory());
14924
14925                    final long sizeBytes = mContainerService.calculateInstalledSize(
14926                            origin.resolvedPath, packageAbiOverride);
14927
14928                    try {
14929                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14930                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14931                                installFlags, packageAbiOverride);
14932                    } catch (InstallerException e) {
14933                        Slog.w(TAG, "Failed to free cache", e);
14934                    }
14935
14936                    /*
14937                     * The cache free must have deleted the file we
14938                     * downloaded to install.
14939                     *
14940                     * TODO: fix the "freeCache" call to not delete
14941                     *       the file we care about.
14942                     */
14943                    if (pkgLite.recommendedInstallLocation
14944                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14945                        pkgLite.recommendedInstallLocation
14946                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14947                    }
14948                }
14949            }
14950
14951            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14952                int loc = pkgLite.recommendedInstallLocation;
14953                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14954                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14955                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14956                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14957                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14958                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14959                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14960                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14961                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14962                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14963                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14964                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14965                } else {
14966                    // Override with defaults if needed.
14967                    loc = installLocationPolicy(pkgLite);
14968                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14969                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14970                    } else if (!onSd && !onInt) {
14971                        // Override install location with flags
14972                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14973                            // Set the flag to install on external media.
14974                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14975                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14976                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14977                            if (DEBUG_EPHEMERAL) {
14978                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14979                            }
14980                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14981                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14982                                    |PackageManager.INSTALL_INTERNAL);
14983                        } else {
14984                            // Make sure the flag for installing on external
14985                            // media is unset
14986                            installFlags |= PackageManager.INSTALL_INTERNAL;
14987                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14988                        }
14989                    }
14990                }
14991            }
14992
14993            final InstallArgs args = createInstallArgs(this);
14994            mArgs = args;
14995
14996            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14997                // TODO: http://b/22976637
14998                // Apps installed for "all" users use the device owner to verify the app
14999                UserHandle verifierUser = getUser();
15000                if (verifierUser == UserHandle.ALL) {
15001                    verifierUser = UserHandle.SYSTEM;
15002                }
15003
15004                /*
15005                 * Determine if we have any installed package verifiers. If we
15006                 * do, then we'll defer to them to verify the packages.
15007                 */
15008                final int requiredUid = mRequiredVerifierPackage == null ? -1
15009                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15010                                verifierUser.getIdentifier());
15011                final int installerUid =
15012                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15013                if (!origin.existing && requiredUid != -1
15014                        && isVerificationEnabled(
15015                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15016                    final Intent verification = new Intent(
15017                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15018                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15019                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15020                            PACKAGE_MIME_TYPE);
15021                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15022
15023                    // Query all live verifiers based on current user state
15024                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15025                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15026                            false /*allowDynamicSplits*/);
15027
15028                    if (DEBUG_VERIFY) {
15029                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15030                                + verification.toString() + " with " + pkgLite.verifiers.length
15031                                + " optional verifiers");
15032                    }
15033
15034                    final int verificationId = mPendingVerificationToken++;
15035
15036                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15037
15038                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15039                            installerPackageName);
15040
15041                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15042                            installFlags);
15043
15044                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15045                            pkgLite.packageName);
15046
15047                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15048                            pkgLite.versionCode);
15049
15050                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15051                            pkgLite.getLongVersionCode());
15052
15053                    if (verificationInfo != null) {
15054                        if (verificationInfo.originatingUri != null) {
15055                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15056                                    verificationInfo.originatingUri);
15057                        }
15058                        if (verificationInfo.referrer != null) {
15059                            verification.putExtra(Intent.EXTRA_REFERRER,
15060                                    verificationInfo.referrer);
15061                        }
15062                        if (verificationInfo.originatingUid >= 0) {
15063                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15064                                    verificationInfo.originatingUid);
15065                        }
15066                        if (verificationInfo.installerUid >= 0) {
15067                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15068                                    verificationInfo.installerUid);
15069                        }
15070                    }
15071
15072                    final PackageVerificationState verificationState = new PackageVerificationState(
15073                            requiredUid, args);
15074
15075                    mPendingVerification.append(verificationId, verificationState);
15076
15077                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15078                            receivers, verificationState);
15079
15080                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15081                    final long idleDuration = getVerificationTimeout();
15082
15083                    /*
15084                     * If any sufficient verifiers were listed in the package
15085                     * manifest, attempt to ask them.
15086                     */
15087                    if (sufficientVerifiers != null) {
15088                        final int N = sufficientVerifiers.size();
15089                        if (N == 0) {
15090                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15091                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15092                        } else {
15093                            for (int i = 0; i < N; i++) {
15094                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15095                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15096                                        verifierComponent.getPackageName(), idleDuration,
15097                                        verifierUser.getIdentifier(), false, "package verifier");
15098
15099                                final Intent sufficientIntent = new Intent(verification);
15100                                sufficientIntent.setComponent(verifierComponent);
15101                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15102                            }
15103                        }
15104                    }
15105
15106                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15107                            mRequiredVerifierPackage, receivers);
15108                    if (ret == PackageManager.INSTALL_SUCCEEDED
15109                            && mRequiredVerifierPackage != null) {
15110                        Trace.asyncTraceBegin(
15111                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15112                        /*
15113                         * Send the intent to the required verification agent,
15114                         * but only start the verification timeout after the
15115                         * target BroadcastReceivers have run.
15116                         */
15117                        verification.setComponent(requiredVerifierComponent);
15118                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15119                                mRequiredVerifierPackage, idleDuration,
15120                                verifierUser.getIdentifier(), false, "package verifier");
15121                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15122                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15123                                new BroadcastReceiver() {
15124                                    @Override
15125                                    public void onReceive(Context context, Intent intent) {
15126                                        final Message msg = mHandler
15127                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15128                                        msg.arg1 = verificationId;
15129                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15130                                    }
15131                                }, null, 0, null, null);
15132
15133                        /*
15134                         * We don't want the copy to proceed until verification
15135                         * succeeds, so null out this field.
15136                         */
15137                        mArgs = null;
15138                    }
15139                } else {
15140                    /*
15141                     * No package verification is enabled, so immediately start
15142                     * the remote call to initiate copy using temporary file.
15143                     */
15144                    ret = args.copyApk(mContainerService, true);
15145                }
15146            }
15147
15148            mRet = ret;
15149        }
15150
15151        @Override
15152        void handleReturnCode() {
15153            // If mArgs is null, then MCS couldn't be reached. When it
15154            // reconnects, it will try again to install. At that point, this
15155            // will succeed.
15156            if (mArgs != null) {
15157                processPendingInstall(mArgs, mRet);
15158            }
15159        }
15160
15161        @Override
15162        void handleServiceError() {
15163            mArgs = createInstallArgs(this);
15164            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15165        }
15166    }
15167
15168    private InstallArgs createInstallArgs(InstallParams params) {
15169        if (params.move != null) {
15170            return new MoveInstallArgs(params);
15171        } else {
15172            return new FileInstallArgs(params);
15173        }
15174    }
15175
15176    /**
15177     * Create args that describe an existing installed package. Typically used
15178     * when cleaning up old installs, or used as a move source.
15179     */
15180    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15181            String resourcePath, String[] instructionSets) {
15182        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15183    }
15184
15185    static abstract class InstallArgs {
15186        /** @see InstallParams#origin */
15187        final OriginInfo origin;
15188        /** @see InstallParams#move */
15189        final MoveInfo move;
15190
15191        final IPackageInstallObserver2 observer;
15192        // Always refers to PackageManager flags only
15193        final int installFlags;
15194        final String installerPackageName;
15195        final String volumeUuid;
15196        final UserHandle user;
15197        final String abiOverride;
15198        final String[] installGrantPermissions;
15199        /** If non-null, drop an async trace when the install completes */
15200        final String traceMethod;
15201        final int traceCookie;
15202        final PackageParser.SigningDetails signingDetails;
15203        final int installReason;
15204
15205        // The list of instruction sets supported by this app. This is currently
15206        // only used during the rmdex() phase to clean up resources. We can get rid of this
15207        // if we move dex files under the common app path.
15208        /* nullable */ String[] instructionSets;
15209
15210        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15211                int installFlags, String installerPackageName, String volumeUuid,
15212                UserHandle user, String[] instructionSets,
15213                String abiOverride, String[] installGrantPermissions,
15214                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15215                int installReason) {
15216            this.origin = origin;
15217            this.move = move;
15218            this.installFlags = installFlags;
15219            this.observer = observer;
15220            this.installerPackageName = installerPackageName;
15221            this.volumeUuid = volumeUuid;
15222            this.user = user;
15223            this.instructionSets = instructionSets;
15224            this.abiOverride = abiOverride;
15225            this.installGrantPermissions = installGrantPermissions;
15226            this.traceMethod = traceMethod;
15227            this.traceCookie = traceCookie;
15228            this.signingDetails = signingDetails;
15229            this.installReason = installReason;
15230        }
15231
15232        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15233        abstract int doPreInstall(int status);
15234
15235        /**
15236         * Rename package into final resting place. All paths on the given
15237         * scanned package should be updated to reflect the rename.
15238         */
15239        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15240        abstract int doPostInstall(int status, int uid);
15241
15242        /** @see PackageSettingBase#codePathString */
15243        abstract String getCodePath();
15244        /** @see PackageSettingBase#resourcePathString */
15245        abstract String getResourcePath();
15246
15247        // Need installer lock especially for dex file removal.
15248        abstract void cleanUpResourcesLI();
15249        abstract boolean doPostDeleteLI(boolean delete);
15250
15251        /**
15252         * Called before the source arguments are copied. This is used mostly
15253         * for MoveParams when it needs to read the source file to put it in the
15254         * destination.
15255         */
15256        int doPreCopy() {
15257            return PackageManager.INSTALL_SUCCEEDED;
15258        }
15259
15260        /**
15261         * Called after the source arguments are copied. This is used mostly for
15262         * MoveParams when it needs to read the source file to put it in the
15263         * destination.
15264         */
15265        int doPostCopy(int uid) {
15266            return PackageManager.INSTALL_SUCCEEDED;
15267        }
15268
15269        protected boolean isFwdLocked() {
15270            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15271        }
15272
15273        protected boolean isExternalAsec() {
15274            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15275        }
15276
15277        protected boolean isEphemeral() {
15278            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15279        }
15280
15281        UserHandle getUser() {
15282            return user;
15283        }
15284    }
15285
15286    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15287        if (!allCodePaths.isEmpty()) {
15288            if (instructionSets == null) {
15289                throw new IllegalStateException("instructionSet == null");
15290            }
15291            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15292            for (String codePath : allCodePaths) {
15293                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15294                    try {
15295                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15296                    } catch (InstallerException ignored) {
15297                    }
15298                }
15299            }
15300        }
15301    }
15302
15303    /**
15304     * Logic to handle installation of non-ASEC applications, including copying
15305     * and renaming logic.
15306     */
15307    class FileInstallArgs extends InstallArgs {
15308        private File codeFile;
15309        private File resourceFile;
15310
15311        // Example topology:
15312        // /data/app/com.example/base.apk
15313        // /data/app/com.example/split_foo.apk
15314        // /data/app/com.example/lib/arm/libfoo.so
15315        // /data/app/com.example/lib/arm64/libfoo.so
15316        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15317
15318        /** New install */
15319        FileInstallArgs(InstallParams params) {
15320            super(params.origin, params.move, params.observer, params.installFlags,
15321                    params.installerPackageName, params.volumeUuid,
15322                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15323                    params.grantedRuntimePermissions,
15324                    params.traceMethod, params.traceCookie, params.signingDetails,
15325                    params.installReason);
15326            if (isFwdLocked()) {
15327                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15328            }
15329        }
15330
15331        /** Existing install */
15332        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15333            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15334                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15335                    PackageManager.INSTALL_REASON_UNKNOWN);
15336            this.codeFile = (codePath != null) ? new File(codePath) : null;
15337            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15338        }
15339
15340        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15341            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15342            try {
15343                return doCopyApk(imcs, temp);
15344            } finally {
15345                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15346            }
15347        }
15348
15349        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15350            if (origin.staged) {
15351                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15352                codeFile = origin.file;
15353                resourceFile = origin.file;
15354                return PackageManager.INSTALL_SUCCEEDED;
15355            }
15356
15357            try {
15358                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15359                final File tempDir =
15360                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15361                codeFile = tempDir;
15362                resourceFile = tempDir;
15363            } catch (IOException e) {
15364                Slog.w(TAG, "Failed to create copy file: " + e);
15365                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15366            }
15367
15368            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15369                @Override
15370                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15371                    if (!FileUtils.isValidExtFilename(name)) {
15372                        throw new IllegalArgumentException("Invalid filename: " + name);
15373                    }
15374                    try {
15375                        final File file = new File(codeFile, name);
15376                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15377                                O_RDWR | O_CREAT, 0644);
15378                        Os.chmod(file.getAbsolutePath(), 0644);
15379                        return new ParcelFileDescriptor(fd);
15380                    } catch (ErrnoException e) {
15381                        throw new RemoteException("Failed to open: " + e.getMessage());
15382                    }
15383                }
15384            };
15385
15386            int ret = PackageManager.INSTALL_SUCCEEDED;
15387            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15388            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15389                Slog.e(TAG, "Failed to copy package");
15390                return ret;
15391            }
15392
15393            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15394            NativeLibraryHelper.Handle handle = null;
15395            try {
15396                handle = NativeLibraryHelper.Handle.create(codeFile);
15397                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15398                        abiOverride);
15399            } catch (IOException e) {
15400                Slog.e(TAG, "Copying native libraries failed", e);
15401                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15402            } finally {
15403                IoUtils.closeQuietly(handle);
15404            }
15405
15406            return ret;
15407        }
15408
15409        int doPreInstall(int status) {
15410            if (status != PackageManager.INSTALL_SUCCEEDED) {
15411                cleanUp();
15412            }
15413            return status;
15414        }
15415
15416        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15417            if (status != PackageManager.INSTALL_SUCCEEDED) {
15418                cleanUp();
15419                return false;
15420            }
15421
15422            final File targetDir = codeFile.getParentFile();
15423            final File beforeCodeFile = codeFile;
15424            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15425
15426            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15427            try {
15428                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15429            } catch (ErrnoException e) {
15430                Slog.w(TAG, "Failed to rename", e);
15431                return false;
15432            }
15433
15434            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15435                Slog.w(TAG, "Failed to restorecon");
15436                return false;
15437            }
15438
15439            // Reflect the rename internally
15440            codeFile = afterCodeFile;
15441            resourceFile = afterCodeFile;
15442
15443            // Reflect the rename in scanned details
15444            try {
15445                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15446            } catch (IOException e) {
15447                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15448                return false;
15449            }
15450            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15451                    afterCodeFile, pkg.baseCodePath));
15452            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15453                    afterCodeFile, pkg.splitCodePaths));
15454
15455            // Reflect the rename in app info
15456            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15457            pkg.setApplicationInfoCodePath(pkg.codePath);
15458            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15459            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15460            pkg.setApplicationInfoResourcePath(pkg.codePath);
15461            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15462            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15463
15464            return true;
15465        }
15466
15467        int doPostInstall(int status, int uid) {
15468            if (status != PackageManager.INSTALL_SUCCEEDED) {
15469                cleanUp();
15470            }
15471            return status;
15472        }
15473
15474        @Override
15475        String getCodePath() {
15476            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15477        }
15478
15479        @Override
15480        String getResourcePath() {
15481            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15482        }
15483
15484        private boolean cleanUp() {
15485            if (codeFile == null || !codeFile.exists()) {
15486                return false;
15487            }
15488
15489            removeCodePathLI(codeFile);
15490
15491            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15492                resourceFile.delete();
15493            }
15494
15495            return true;
15496        }
15497
15498        void cleanUpResourcesLI() {
15499            // Try enumerating all code paths before deleting
15500            List<String> allCodePaths = Collections.EMPTY_LIST;
15501            if (codeFile != null && codeFile.exists()) {
15502                try {
15503                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15504                    allCodePaths = pkg.getAllCodePaths();
15505                } catch (PackageParserException e) {
15506                    // Ignored; we tried our best
15507                }
15508            }
15509
15510            cleanUp();
15511            removeDexFiles(allCodePaths, instructionSets);
15512        }
15513
15514        boolean doPostDeleteLI(boolean delete) {
15515            // XXX err, shouldn't we respect the delete flag?
15516            cleanUpResourcesLI();
15517            return true;
15518        }
15519    }
15520
15521    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15522            PackageManagerException {
15523        if (copyRet < 0) {
15524            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15525                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15526                throw new PackageManagerException(copyRet, message);
15527            }
15528        }
15529    }
15530
15531    /**
15532     * Extract the StorageManagerService "container ID" from the full code path of an
15533     * .apk.
15534     */
15535    static String cidFromCodePath(String fullCodePath) {
15536        int eidx = fullCodePath.lastIndexOf("/");
15537        String subStr1 = fullCodePath.substring(0, eidx);
15538        int sidx = subStr1.lastIndexOf("/");
15539        return subStr1.substring(sidx+1, eidx);
15540    }
15541
15542    /**
15543     * Logic to handle movement of existing installed applications.
15544     */
15545    class MoveInstallArgs extends InstallArgs {
15546        private File codeFile;
15547        private File resourceFile;
15548
15549        /** New install */
15550        MoveInstallArgs(InstallParams params) {
15551            super(params.origin, params.move, params.observer, params.installFlags,
15552                    params.installerPackageName, params.volumeUuid,
15553                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15554                    params.grantedRuntimePermissions,
15555                    params.traceMethod, params.traceCookie, params.signingDetails,
15556                    params.installReason);
15557        }
15558
15559        int copyApk(IMediaContainerService imcs, boolean temp) {
15560            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15561                    + move.fromUuid + " to " + move.toUuid);
15562            synchronized (mInstaller) {
15563                try {
15564                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15565                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15566                } catch (InstallerException e) {
15567                    Slog.w(TAG, "Failed to move app", e);
15568                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15569                }
15570            }
15571
15572            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15573            resourceFile = codeFile;
15574            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15575
15576            return PackageManager.INSTALL_SUCCEEDED;
15577        }
15578
15579        int doPreInstall(int status) {
15580            if (status != PackageManager.INSTALL_SUCCEEDED) {
15581                cleanUp(move.toUuid);
15582            }
15583            return status;
15584        }
15585
15586        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15587            if (status != PackageManager.INSTALL_SUCCEEDED) {
15588                cleanUp(move.toUuid);
15589                return false;
15590            }
15591
15592            // Reflect the move in app info
15593            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15594            pkg.setApplicationInfoCodePath(pkg.codePath);
15595            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15596            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15597            pkg.setApplicationInfoResourcePath(pkg.codePath);
15598            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15599            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15600
15601            return true;
15602        }
15603
15604        int doPostInstall(int status, int uid) {
15605            if (status == PackageManager.INSTALL_SUCCEEDED) {
15606                cleanUp(move.fromUuid);
15607            } else {
15608                cleanUp(move.toUuid);
15609            }
15610            return status;
15611        }
15612
15613        @Override
15614        String getCodePath() {
15615            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15616        }
15617
15618        @Override
15619        String getResourcePath() {
15620            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15621        }
15622
15623        private boolean cleanUp(String volumeUuid) {
15624            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15625                    move.dataAppName);
15626            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15627            final int[] userIds = sUserManager.getUserIds();
15628            synchronized (mInstallLock) {
15629                // Clean up both app data and code
15630                // All package moves are frozen until finished
15631                for (int userId : userIds) {
15632                    try {
15633                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15634                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15635                    } catch (InstallerException e) {
15636                        Slog.w(TAG, String.valueOf(e));
15637                    }
15638                }
15639                removeCodePathLI(codeFile);
15640            }
15641            return true;
15642        }
15643
15644        void cleanUpResourcesLI() {
15645            throw new UnsupportedOperationException();
15646        }
15647
15648        boolean doPostDeleteLI(boolean delete) {
15649            throw new UnsupportedOperationException();
15650        }
15651    }
15652
15653    static String getAsecPackageName(String packageCid) {
15654        int idx = packageCid.lastIndexOf("-");
15655        if (idx == -1) {
15656            return packageCid;
15657        }
15658        return packageCid.substring(0, idx);
15659    }
15660
15661    // Utility method used to create code paths based on package name and available index.
15662    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15663        String idxStr = "";
15664        int idx = 1;
15665        // Fall back to default value of idx=1 if prefix is not
15666        // part of oldCodePath
15667        if (oldCodePath != null) {
15668            String subStr = oldCodePath;
15669            // Drop the suffix right away
15670            if (suffix != null && subStr.endsWith(suffix)) {
15671                subStr = subStr.substring(0, subStr.length() - suffix.length());
15672            }
15673            // If oldCodePath already contains prefix find out the
15674            // ending index to either increment or decrement.
15675            int sidx = subStr.lastIndexOf(prefix);
15676            if (sidx != -1) {
15677                subStr = subStr.substring(sidx + prefix.length());
15678                if (subStr != null) {
15679                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15680                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15681                    }
15682                    try {
15683                        idx = Integer.parseInt(subStr);
15684                        if (idx <= 1) {
15685                            idx++;
15686                        } else {
15687                            idx--;
15688                        }
15689                    } catch(NumberFormatException e) {
15690                    }
15691                }
15692            }
15693        }
15694        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15695        return prefix + idxStr;
15696    }
15697
15698    private File getNextCodePath(File targetDir, String packageName) {
15699        File result;
15700        SecureRandom random = new SecureRandom();
15701        byte[] bytes = new byte[16];
15702        do {
15703            random.nextBytes(bytes);
15704            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15705            result = new File(targetDir, packageName + "-" + suffix);
15706        } while (result.exists());
15707        return result;
15708    }
15709
15710    // Utility method that returns the relative package path with respect
15711    // to the installation directory. Like say for /data/data/com.test-1.apk
15712    // string com.test-1 is returned.
15713    static String deriveCodePathName(String codePath) {
15714        if (codePath == null) {
15715            return null;
15716        }
15717        final File codeFile = new File(codePath);
15718        final String name = codeFile.getName();
15719        if (codeFile.isDirectory()) {
15720            return name;
15721        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15722            final int lastDot = name.lastIndexOf('.');
15723            return name.substring(0, lastDot);
15724        } else {
15725            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15726            return null;
15727        }
15728    }
15729
15730    static class PackageInstalledInfo {
15731        String name;
15732        int uid;
15733        // The set of users that originally had this package installed.
15734        int[] origUsers;
15735        // The set of users that now have this package installed.
15736        int[] newUsers;
15737        PackageParser.Package pkg;
15738        int returnCode;
15739        String returnMsg;
15740        String installerPackageName;
15741        PackageRemovedInfo removedInfo;
15742        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15743
15744        public void setError(int code, String msg) {
15745            setReturnCode(code);
15746            setReturnMessage(msg);
15747            Slog.w(TAG, msg);
15748        }
15749
15750        public void setError(String msg, PackageParserException e) {
15751            setReturnCode(e.error);
15752            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15753            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15754            for (int i = 0; i < childCount; i++) {
15755                addedChildPackages.valueAt(i).setError(msg, e);
15756            }
15757            Slog.w(TAG, msg, e);
15758        }
15759
15760        public void setError(String msg, PackageManagerException e) {
15761            returnCode = e.error;
15762            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15763            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15764            for (int i = 0; i < childCount; i++) {
15765                addedChildPackages.valueAt(i).setError(msg, e);
15766            }
15767            Slog.w(TAG, msg, e);
15768        }
15769
15770        public void setReturnCode(int returnCode) {
15771            this.returnCode = returnCode;
15772            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15773            for (int i = 0; i < childCount; i++) {
15774                addedChildPackages.valueAt(i).returnCode = returnCode;
15775            }
15776        }
15777
15778        private void setReturnMessage(String returnMsg) {
15779            this.returnMsg = returnMsg;
15780            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15781            for (int i = 0; i < childCount; i++) {
15782                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15783            }
15784        }
15785
15786        // In some error cases we want to convey more info back to the observer
15787        String origPackage;
15788        String origPermission;
15789    }
15790
15791    /*
15792     * Install a non-existing package.
15793     */
15794    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15795            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15796            String volumeUuid, PackageInstalledInfo res, int installReason) {
15797        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15798
15799        // Remember this for later, in case we need to rollback this install
15800        String pkgName = pkg.packageName;
15801
15802        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15803
15804        synchronized(mPackages) {
15805            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15806            if (renamedPackage != null) {
15807                // A package with the same name is already installed, though
15808                // it has been renamed to an older name.  The package we
15809                // are trying to install should be installed as an update to
15810                // the existing one, but that has not been requested, so bail.
15811                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15812                        + " without first uninstalling package running as "
15813                        + renamedPackage);
15814                return;
15815            }
15816            if (mPackages.containsKey(pkgName)) {
15817                // Don't allow installation over an existing package with the same name.
15818                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15819                        + " without first uninstalling.");
15820                return;
15821            }
15822        }
15823
15824        try {
15825            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15826                    System.currentTimeMillis(), user);
15827
15828            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15829
15830            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15831                prepareAppDataAfterInstallLIF(newPackage);
15832
15833            } else {
15834                // Remove package from internal structures, but keep around any
15835                // data that might have already existed
15836                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15837                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15838            }
15839        } catch (PackageManagerException e) {
15840            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15841        }
15842
15843        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15844    }
15845
15846    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15847        try (DigestInputStream digestStream =
15848                new DigestInputStream(new FileInputStream(file), digest)) {
15849            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15850        }
15851    }
15852
15853    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15854            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15855            PackageInstalledInfo res, int installReason) {
15856        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15857
15858        final PackageParser.Package oldPackage;
15859        final PackageSetting ps;
15860        final String pkgName = pkg.packageName;
15861        final int[] allUsers;
15862        final int[] installedUsers;
15863
15864        synchronized(mPackages) {
15865            oldPackage = mPackages.get(pkgName);
15866            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15867
15868            // don't allow upgrade to target a release SDK from a pre-release SDK
15869            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15870                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15871            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15872                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15873            if (oldTargetsPreRelease
15874                    && !newTargetsPreRelease
15875                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15876                Slog.w(TAG, "Can't install package targeting released sdk");
15877                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15878                return;
15879            }
15880
15881            ps = mSettings.mPackages.get(pkgName);
15882
15883            // verify signatures are valid
15884            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15885            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15886                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15887                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15888                            "New package not signed by keys specified by upgrade-keysets: "
15889                                    + pkgName);
15890                    return;
15891                }
15892            } else {
15893                // default to original signature matching
15894                if (compareSignatures(oldPackage.mSigningDetails.signatures,
15895                        pkg.mSigningDetails.signatures)
15896                        != PackageManager.SIGNATURE_MATCH) {
15897                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15898                            "New package has a different signature: " + pkgName);
15899                    return;
15900                }
15901            }
15902
15903            // don't allow a system upgrade unless the upgrade hash matches
15904            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15905                byte[] digestBytes = null;
15906                try {
15907                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15908                    updateDigest(digest, new File(pkg.baseCodePath));
15909                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15910                        for (String path : pkg.splitCodePaths) {
15911                            updateDigest(digest, new File(path));
15912                        }
15913                    }
15914                    digestBytes = digest.digest();
15915                } catch (NoSuchAlgorithmException | IOException e) {
15916                    res.setError(INSTALL_FAILED_INVALID_APK,
15917                            "Could not compute hash: " + pkgName);
15918                    return;
15919                }
15920                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15921                    res.setError(INSTALL_FAILED_INVALID_APK,
15922                            "New package fails restrict-update check: " + pkgName);
15923                    return;
15924                }
15925                // retain upgrade restriction
15926                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15927            }
15928
15929            // Check for shared user id changes
15930            String invalidPackageName =
15931                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15932            if (invalidPackageName != null) {
15933                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15934                        "Package " + invalidPackageName + " tried to change user "
15935                                + oldPackage.mSharedUserId);
15936                return;
15937            }
15938
15939            // check if the new package supports all of the abis which the old package supports
15940            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
15941            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
15942            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
15943                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15944                        "Update to package " + pkgName + " doesn't support multi arch");
15945                return;
15946            }
15947
15948            // In case of rollback, remember per-user/profile install state
15949            allUsers = sUserManager.getUserIds();
15950            installedUsers = ps.queryInstalledUsers(allUsers, true);
15951
15952            // don't allow an upgrade from full to ephemeral
15953            if (isInstantApp) {
15954                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15955                    for (int currentUser : allUsers) {
15956                        if (!ps.getInstantApp(currentUser)) {
15957                            // can't downgrade from full to instant
15958                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15959                                    + " for user: " + currentUser);
15960                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15961                            return;
15962                        }
15963                    }
15964                } else if (!ps.getInstantApp(user.getIdentifier())) {
15965                    // can't downgrade from full to instant
15966                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15967                            + " for user: " + user.getIdentifier());
15968                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15969                    return;
15970                }
15971            }
15972        }
15973
15974        // Update what is removed
15975        res.removedInfo = new PackageRemovedInfo(this);
15976        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15977        res.removedInfo.removedPackage = oldPackage.packageName;
15978        res.removedInfo.installerPackageName = ps.installerPackageName;
15979        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15980        res.removedInfo.isUpdate = true;
15981        res.removedInfo.origUsers = installedUsers;
15982        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15983        for (int i = 0; i < installedUsers.length; i++) {
15984            final int userId = installedUsers[i];
15985            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15986        }
15987
15988        final int childCount = (oldPackage.childPackages != null)
15989                ? oldPackage.childPackages.size() : 0;
15990        for (int i = 0; i < childCount; i++) {
15991            boolean childPackageUpdated = false;
15992            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15993            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15994            if (res.addedChildPackages != null) {
15995                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15996                if (childRes != null) {
15997                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15998                    childRes.removedInfo.removedPackage = childPkg.packageName;
15999                    if (childPs != null) {
16000                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16001                    }
16002                    childRes.removedInfo.isUpdate = true;
16003                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16004                    childPackageUpdated = true;
16005                }
16006            }
16007            if (!childPackageUpdated) {
16008                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16009                childRemovedRes.removedPackage = childPkg.packageName;
16010                if (childPs != null) {
16011                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16012                }
16013                childRemovedRes.isUpdate = false;
16014                childRemovedRes.dataRemoved = true;
16015                synchronized (mPackages) {
16016                    if (childPs != null) {
16017                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16018                    }
16019                }
16020                if (res.removedInfo.removedChildPackages == null) {
16021                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16022                }
16023                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16024            }
16025        }
16026
16027        boolean sysPkg = (isSystemApp(oldPackage));
16028        if (sysPkg) {
16029            // Set the system/privileged/oem/vendor flags as needed
16030            final boolean privileged =
16031                    (oldPackage.applicationInfo.privateFlags
16032                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16033            final boolean oem =
16034                    (oldPackage.applicationInfo.privateFlags
16035                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16036            final boolean vendor =
16037                    (oldPackage.applicationInfo.privateFlags
16038                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16039            final @ParseFlags int systemParseFlags = parseFlags;
16040            final @ScanFlags int systemScanFlags = scanFlags
16041                    | SCAN_AS_SYSTEM
16042                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16043                    | (oem ? SCAN_AS_OEM : 0)
16044                    | (vendor ? SCAN_AS_VENDOR : 0);
16045
16046            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16047                    user, allUsers, installerPackageName, res, installReason);
16048        } else {
16049            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16050                    user, allUsers, installerPackageName, res, installReason);
16051        }
16052    }
16053
16054    @Override
16055    public List<String> getPreviousCodePaths(String packageName) {
16056        final int callingUid = Binder.getCallingUid();
16057        final List<String> result = new ArrayList<>();
16058        if (getInstantAppPackageName(callingUid) != null) {
16059            return result;
16060        }
16061        final PackageSetting ps = mSettings.mPackages.get(packageName);
16062        if (ps != null
16063                && ps.oldCodePaths != null
16064                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16065            result.addAll(ps.oldCodePaths);
16066        }
16067        return result;
16068    }
16069
16070    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16071            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16072            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16073            String installerPackageName, PackageInstalledInfo res, int installReason) {
16074        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16075                + deletedPackage);
16076
16077        String pkgName = deletedPackage.packageName;
16078        boolean deletedPkg = true;
16079        boolean addedPkg = false;
16080        boolean updatedSettings = false;
16081        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16082        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16083                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16084
16085        final long origUpdateTime = (pkg.mExtras != null)
16086                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16087
16088        // First delete the existing package while retaining the data directory
16089        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16090                res.removedInfo, true, pkg)) {
16091            // If the existing package wasn't successfully deleted
16092            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16093            deletedPkg = false;
16094        } else {
16095            // Successfully deleted the old package; proceed with replace.
16096
16097            // If deleted package lived in a container, give users a chance to
16098            // relinquish resources before killing.
16099            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16100                if (DEBUG_INSTALL) {
16101                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16102                }
16103                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16104                final ArrayList<String> pkgList = new ArrayList<String>(1);
16105                pkgList.add(deletedPackage.applicationInfo.packageName);
16106                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16107            }
16108
16109            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16110                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16111            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16112
16113            try {
16114                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16115                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16116                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16117                        installReason);
16118
16119                // Update the in-memory copy of the previous code paths.
16120                PackageSetting ps = mSettings.mPackages.get(pkgName);
16121                if (!killApp) {
16122                    if (ps.oldCodePaths == null) {
16123                        ps.oldCodePaths = new ArraySet<>();
16124                    }
16125                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16126                    if (deletedPackage.splitCodePaths != null) {
16127                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16128                    }
16129                } else {
16130                    ps.oldCodePaths = null;
16131                }
16132                if (ps.childPackageNames != null) {
16133                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16134                        final String childPkgName = ps.childPackageNames.get(i);
16135                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16136                        childPs.oldCodePaths = ps.oldCodePaths;
16137                    }
16138                }
16139                // set instant app status, but, only if it's explicitly specified
16140                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16141                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16142                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16143                prepareAppDataAfterInstallLIF(newPackage);
16144                addedPkg = true;
16145                mDexManager.notifyPackageUpdated(newPackage.packageName,
16146                        newPackage.baseCodePath, newPackage.splitCodePaths);
16147            } catch (PackageManagerException e) {
16148                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16149            }
16150        }
16151
16152        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16153            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16154
16155            // Revert all internal state mutations and added folders for the failed install
16156            if (addedPkg) {
16157                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16158                        res.removedInfo, true, null);
16159            }
16160
16161            // Restore the old package
16162            if (deletedPkg) {
16163                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16164                File restoreFile = new File(deletedPackage.codePath);
16165                // Parse old package
16166                boolean oldExternal = isExternal(deletedPackage);
16167                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16168                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16169                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16170                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16171                try {
16172                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16173                            null);
16174                } catch (PackageManagerException e) {
16175                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16176                            + e.getMessage());
16177                    return;
16178                }
16179
16180                synchronized (mPackages) {
16181                    // Ensure the installer package name up to date
16182                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16183
16184                    // Update permissions for restored package
16185                    mPermissionManager.updatePermissions(
16186                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16187                            mPermissionCallback);
16188
16189                    mSettings.writeLPr();
16190                }
16191
16192                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16193            }
16194        } else {
16195            synchronized (mPackages) {
16196                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16197                if (ps != null) {
16198                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16199                    if (res.removedInfo.removedChildPackages != null) {
16200                        final int childCount = res.removedInfo.removedChildPackages.size();
16201                        // Iterate in reverse as we may modify the collection
16202                        for (int i = childCount - 1; i >= 0; i--) {
16203                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16204                            if (res.addedChildPackages.containsKey(childPackageName)) {
16205                                res.removedInfo.removedChildPackages.removeAt(i);
16206                            } else {
16207                                PackageRemovedInfo childInfo = res.removedInfo
16208                                        .removedChildPackages.valueAt(i);
16209                                childInfo.removedForAllUsers = mPackages.get(
16210                                        childInfo.removedPackage) == null;
16211                            }
16212                        }
16213                    }
16214                }
16215            }
16216        }
16217    }
16218
16219    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16220            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16221            final @ScanFlags int scanFlags, UserHandle user,
16222            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16223            int installReason) {
16224        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16225                + ", old=" + deletedPackage);
16226
16227        final boolean disabledSystem;
16228
16229        // Remove existing system package
16230        removePackageLI(deletedPackage, true);
16231
16232        synchronized (mPackages) {
16233            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16234        }
16235        if (!disabledSystem) {
16236            // We didn't need to disable the .apk as a current system package,
16237            // which means we are replacing another update that is already
16238            // installed.  We need to make sure to delete the older one's .apk.
16239            res.removedInfo.args = createInstallArgsForExisting(0,
16240                    deletedPackage.applicationInfo.getCodePath(),
16241                    deletedPackage.applicationInfo.getResourcePath(),
16242                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16243        } else {
16244            res.removedInfo.args = null;
16245        }
16246
16247        // Successfully disabled the old package. Now proceed with re-installation
16248        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16249                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16250        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16251
16252        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16253        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16254                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16255
16256        PackageParser.Package newPackage = null;
16257        try {
16258            // Add the package to the internal data structures
16259            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16260
16261            // Set the update and install times
16262            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16263            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16264                    System.currentTimeMillis());
16265
16266            // Update the package dynamic state if succeeded
16267            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16268                // Now that the install succeeded make sure we remove data
16269                // directories for any child package the update removed.
16270                final int deletedChildCount = (deletedPackage.childPackages != null)
16271                        ? deletedPackage.childPackages.size() : 0;
16272                final int newChildCount = (newPackage.childPackages != null)
16273                        ? newPackage.childPackages.size() : 0;
16274                for (int i = 0; i < deletedChildCount; i++) {
16275                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16276                    boolean childPackageDeleted = true;
16277                    for (int j = 0; j < newChildCount; j++) {
16278                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16279                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16280                            childPackageDeleted = false;
16281                            break;
16282                        }
16283                    }
16284                    if (childPackageDeleted) {
16285                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16286                                deletedChildPkg.packageName);
16287                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16288                            PackageRemovedInfo removedChildRes = res.removedInfo
16289                                    .removedChildPackages.get(deletedChildPkg.packageName);
16290                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16291                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16292                        }
16293                    }
16294                }
16295
16296                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16297                        installReason);
16298                prepareAppDataAfterInstallLIF(newPackage);
16299
16300                mDexManager.notifyPackageUpdated(newPackage.packageName,
16301                            newPackage.baseCodePath, newPackage.splitCodePaths);
16302            }
16303        } catch (PackageManagerException e) {
16304            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16305            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16306        }
16307
16308        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16309            // Re installation failed. Restore old information
16310            // Remove new pkg information
16311            if (newPackage != null) {
16312                removeInstalledPackageLI(newPackage, true);
16313            }
16314            // Add back the old system package
16315            try {
16316                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16317            } catch (PackageManagerException e) {
16318                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16319            }
16320
16321            synchronized (mPackages) {
16322                if (disabledSystem) {
16323                    enableSystemPackageLPw(deletedPackage);
16324                }
16325
16326                // Ensure the installer package name up to date
16327                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16328
16329                // Update permissions for restored package
16330                mPermissionManager.updatePermissions(
16331                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16332                        mPermissionCallback);
16333
16334                mSettings.writeLPr();
16335            }
16336
16337            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16338                    + " after failed upgrade");
16339        }
16340    }
16341
16342    /**
16343     * Checks whether the parent or any of the child packages have a change shared
16344     * user. For a package to be a valid update the shred users of the parent and
16345     * the children should match. We may later support changing child shared users.
16346     * @param oldPkg The updated package.
16347     * @param newPkg The update package.
16348     * @return The shared user that change between the versions.
16349     */
16350    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16351            PackageParser.Package newPkg) {
16352        // Check parent shared user
16353        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16354            return newPkg.packageName;
16355        }
16356        // Check child shared users
16357        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16358        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16359        for (int i = 0; i < newChildCount; i++) {
16360            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16361            // If this child was present, did it have the same shared user?
16362            for (int j = 0; j < oldChildCount; j++) {
16363                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16364                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16365                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16366                    return newChildPkg.packageName;
16367                }
16368            }
16369        }
16370        return null;
16371    }
16372
16373    private void removeNativeBinariesLI(PackageSetting ps) {
16374        // Remove the lib path for the parent package
16375        if (ps != null) {
16376            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16377            // Remove the lib path for the child packages
16378            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16379            for (int i = 0; i < childCount; i++) {
16380                PackageSetting childPs = null;
16381                synchronized (mPackages) {
16382                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16383                }
16384                if (childPs != null) {
16385                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16386                            .legacyNativeLibraryPathString);
16387                }
16388            }
16389        }
16390    }
16391
16392    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16393        // Enable the parent package
16394        mSettings.enableSystemPackageLPw(pkg.packageName);
16395        // Enable the child packages
16396        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16397        for (int i = 0; i < childCount; i++) {
16398            PackageParser.Package childPkg = pkg.childPackages.get(i);
16399            mSettings.enableSystemPackageLPw(childPkg.packageName);
16400        }
16401    }
16402
16403    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16404            PackageParser.Package newPkg) {
16405        // Disable the parent package (parent always replaced)
16406        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16407        // Disable the child packages
16408        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16409        for (int i = 0; i < childCount; i++) {
16410            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16411            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16412            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16413        }
16414        return disabled;
16415    }
16416
16417    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16418            String installerPackageName) {
16419        // Enable the parent package
16420        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16421        // Enable the child packages
16422        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16423        for (int i = 0; i < childCount; i++) {
16424            PackageParser.Package childPkg = pkg.childPackages.get(i);
16425            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16426        }
16427    }
16428
16429    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16430            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16431        // Update the parent package setting
16432        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16433                res, user, installReason);
16434        // Update the child packages setting
16435        final int childCount = (newPackage.childPackages != null)
16436                ? newPackage.childPackages.size() : 0;
16437        for (int i = 0; i < childCount; i++) {
16438            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16439            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16440            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16441                    childRes.origUsers, childRes, user, installReason);
16442        }
16443    }
16444
16445    private void updateSettingsInternalLI(PackageParser.Package pkg,
16446            String installerPackageName, int[] allUsers, int[] installedForUsers,
16447            PackageInstalledInfo res, UserHandle user, int installReason) {
16448        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16449
16450        String pkgName = pkg.packageName;
16451        synchronized (mPackages) {
16452            //write settings. the installStatus will be incomplete at this stage.
16453            //note that the new package setting would have already been
16454            //added to mPackages. It hasn't been persisted yet.
16455            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16456            // TODO: Remove this write? It's also written at the end of this method
16457            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16458            mSettings.writeLPr();
16459            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16460        }
16461
16462        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16463        synchronized (mPackages) {
16464// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16465            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16466                    mPermissionCallback);
16467            // For system-bundled packages, we assume that installing an upgraded version
16468            // of the package implies that the user actually wants to run that new code,
16469            // so we enable the package.
16470            PackageSetting ps = mSettings.mPackages.get(pkgName);
16471            final int userId = user.getIdentifier();
16472            if (ps != null) {
16473                if (isSystemApp(pkg)) {
16474                    if (DEBUG_INSTALL) {
16475                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16476                    }
16477                    // Enable system package for requested users
16478                    if (res.origUsers != null) {
16479                        for (int origUserId : res.origUsers) {
16480                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16481                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16482                                        origUserId, installerPackageName);
16483                            }
16484                        }
16485                    }
16486                    // Also convey the prior install/uninstall state
16487                    if (allUsers != null && installedForUsers != null) {
16488                        for (int currentUserId : allUsers) {
16489                            final boolean installed = ArrayUtils.contains(
16490                                    installedForUsers, currentUserId);
16491                            if (DEBUG_INSTALL) {
16492                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16493                            }
16494                            ps.setInstalled(installed, currentUserId);
16495                        }
16496                        // these install state changes will be persisted in the
16497                        // upcoming call to mSettings.writeLPr().
16498                    }
16499                }
16500                // It's implied that when a user requests installation, they want the app to be
16501                // installed and enabled.
16502                if (userId != UserHandle.USER_ALL) {
16503                    ps.setInstalled(true, userId);
16504                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16505                }
16506
16507                // When replacing an existing package, preserve the original install reason for all
16508                // users that had the package installed before.
16509                final Set<Integer> previousUserIds = new ArraySet<>();
16510                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16511                    final int installReasonCount = res.removedInfo.installReasons.size();
16512                    for (int i = 0; i < installReasonCount; i++) {
16513                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16514                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16515                        ps.setInstallReason(previousInstallReason, previousUserId);
16516                        previousUserIds.add(previousUserId);
16517                    }
16518                }
16519
16520                // Set install reason for users that are having the package newly installed.
16521                if (userId == UserHandle.USER_ALL) {
16522                    for (int currentUserId : sUserManager.getUserIds()) {
16523                        if (!previousUserIds.contains(currentUserId)) {
16524                            ps.setInstallReason(installReason, currentUserId);
16525                        }
16526                    }
16527                } else if (!previousUserIds.contains(userId)) {
16528                    ps.setInstallReason(installReason, userId);
16529                }
16530                mSettings.writeKernelMappingLPr(ps);
16531            }
16532            res.name = pkgName;
16533            res.uid = pkg.applicationInfo.uid;
16534            res.pkg = pkg;
16535            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16536            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16537            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16538            //to update install status
16539            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16540            mSettings.writeLPr();
16541            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16542        }
16543
16544        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16545    }
16546
16547    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16548        try {
16549            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16550            installPackageLI(args, res);
16551        } finally {
16552            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16553        }
16554    }
16555
16556    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16557        final int installFlags = args.installFlags;
16558        final String installerPackageName = args.installerPackageName;
16559        final String volumeUuid = args.volumeUuid;
16560        final File tmpPackageFile = new File(args.getCodePath());
16561        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16562        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16563                || (args.volumeUuid != null));
16564        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16565        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16566        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16567        final boolean virtualPreload =
16568                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16569        boolean replace = false;
16570        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16571        if (args.move != null) {
16572            // moving a complete application; perform an initial scan on the new install location
16573            scanFlags |= SCAN_INITIAL;
16574        }
16575        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16576            scanFlags |= SCAN_DONT_KILL_APP;
16577        }
16578        if (instantApp) {
16579            scanFlags |= SCAN_AS_INSTANT_APP;
16580        }
16581        if (fullApp) {
16582            scanFlags |= SCAN_AS_FULL_APP;
16583        }
16584        if (virtualPreload) {
16585            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16586        }
16587
16588        // Result object to be returned
16589        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16590        res.installerPackageName = installerPackageName;
16591
16592        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16593
16594        // Sanity check
16595        if (instantApp && (forwardLocked || onExternal)) {
16596            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16597                    + " external=" + onExternal);
16598            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16599            return;
16600        }
16601
16602        // Retrieve PackageSettings and parse package
16603        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16604                | PackageParser.PARSE_ENFORCE_CODE
16605                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16606                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16607                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16608        PackageParser pp = new PackageParser();
16609        pp.setSeparateProcesses(mSeparateProcesses);
16610        pp.setDisplayMetrics(mMetrics);
16611        pp.setCallback(mPackageParserCallback);
16612
16613        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16614        final PackageParser.Package pkg;
16615        try {
16616            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16617            DexMetadataHelper.validatePackageDexMetadata(pkg);
16618        } catch (PackageParserException e) {
16619            res.setError("Failed parse during installPackageLI", e);
16620            return;
16621        } finally {
16622            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16623        }
16624
16625        // Instant apps have several additional install-time checks.
16626        if (instantApp) {
16627            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16628                Slog.w(TAG,
16629                        "Instant app package " + pkg.packageName + " does not target at least O");
16630                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16631                        "Instant app package must target at least O");
16632                return;
16633            }
16634            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16635                Slog.w(TAG, "Instant app package " + pkg.packageName
16636                        + " does not target targetSandboxVersion 2");
16637                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16638                        "Instant app package must use targetSandboxVersion 2");
16639                return;
16640            }
16641            if (pkg.mSharedUserId != null) {
16642                Slog.w(TAG, "Instant app package " + pkg.packageName
16643                        + " may not declare sharedUserId.");
16644                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16645                        "Instant app package may not declare a sharedUserId");
16646                return;
16647            }
16648        }
16649
16650        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16651            // Static shared libraries have synthetic package names
16652            renameStaticSharedLibraryPackage(pkg);
16653
16654            // No static shared libs on external storage
16655            if (onExternal) {
16656                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16657                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16658                        "Packages declaring static-shared libs cannot be updated");
16659                return;
16660            }
16661        }
16662
16663        // If we are installing a clustered package add results for the children
16664        if (pkg.childPackages != null) {
16665            synchronized (mPackages) {
16666                final int childCount = pkg.childPackages.size();
16667                for (int i = 0; i < childCount; i++) {
16668                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16669                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16670                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16671                    childRes.pkg = childPkg;
16672                    childRes.name = childPkg.packageName;
16673                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16674                    if (childPs != null) {
16675                        childRes.origUsers = childPs.queryInstalledUsers(
16676                                sUserManager.getUserIds(), true);
16677                    }
16678                    if ((mPackages.containsKey(childPkg.packageName))) {
16679                        childRes.removedInfo = new PackageRemovedInfo(this);
16680                        childRes.removedInfo.removedPackage = childPkg.packageName;
16681                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16682                    }
16683                    if (res.addedChildPackages == null) {
16684                        res.addedChildPackages = new ArrayMap<>();
16685                    }
16686                    res.addedChildPackages.put(childPkg.packageName, childRes);
16687                }
16688            }
16689        }
16690
16691        // If package doesn't declare API override, mark that we have an install
16692        // time CPU ABI override.
16693        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16694            pkg.cpuAbiOverride = args.abiOverride;
16695        }
16696
16697        String pkgName = res.name = pkg.packageName;
16698        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16699            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16700                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16701                return;
16702            }
16703        }
16704
16705        try {
16706            // either use what we've been given or parse directly from the APK
16707            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16708                pkg.setSigningDetails(args.signingDetails);
16709            } else {
16710                PackageParser.collectCertificates(pkg, parseFlags);
16711            }
16712        } catch (PackageParserException e) {
16713            res.setError("Failed collect during installPackageLI", e);
16714            return;
16715        }
16716
16717        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16718                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16719            Slog.w(TAG, "Instant app package " + pkg.packageName
16720                    + " is not signed with at least APK Signature Scheme v2");
16721            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16722                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16723            return;
16724        }
16725
16726        // Get rid of all references to package scan path via parser.
16727        pp = null;
16728        String oldCodePath = null;
16729        boolean systemApp = false;
16730        synchronized (mPackages) {
16731            // Check if installing already existing package
16732            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16733                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16734                if (pkg.mOriginalPackages != null
16735                        && pkg.mOriginalPackages.contains(oldName)
16736                        && mPackages.containsKey(oldName)) {
16737                    // This package is derived from an original package,
16738                    // and this device has been updating from that original
16739                    // name.  We must continue using the original name, so
16740                    // rename the new package here.
16741                    pkg.setPackageName(oldName);
16742                    pkgName = pkg.packageName;
16743                    replace = true;
16744                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16745                            + oldName + " pkgName=" + pkgName);
16746                } else if (mPackages.containsKey(pkgName)) {
16747                    // This package, under its official name, already exists
16748                    // on the device; we should replace it.
16749                    replace = true;
16750                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16751                }
16752
16753                // Child packages are installed through the parent package
16754                if (pkg.parentPackage != null) {
16755                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16756                            "Package " + pkg.packageName + " is child of package "
16757                                    + pkg.parentPackage.parentPackage + ". Child packages "
16758                                    + "can be updated only through the parent package.");
16759                    return;
16760                }
16761
16762                if (replace) {
16763                    // Prevent apps opting out from runtime permissions
16764                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16765                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16766                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16767                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16768                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16769                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16770                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16771                                        + " doesn't support runtime permissions but the old"
16772                                        + " target SDK " + oldTargetSdk + " does.");
16773                        return;
16774                    }
16775                    // Prevent persistent apps from being updated
16776                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16777                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16778                                "Package " + oldPackage.packageName + " is a persistent app. "
16779                                        + "Persistent apps are not updateable.");
16780                        return;
16781                    }
16782                    // Prevent apps from downgrading their targetSandbox.
16783                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16784                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16785                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16786                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16787                                "Package " + pkg.packageName + " new target sandbox "
16788                                + newTargetSandbox + " is incompatible with the previous value of"
16789                                + oldTargetSandbox + ".");
16790                        return;
16791                    }
16792
16793                    // Prevent installing of child packages
16794                    if (oldPackage.parentPackage != null) {
16795                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16796                                "Package " + pkg.packageName + " is child of package "
16797                                        + oldPackage.parentPackage + ". Child packages "
16798                                        + "can be updated only through the parent package.");
16799                        return;
16800                    }
16801                }
16802            }
16803
16804            PackageSetting ps = mSettings.mPackages.get(pkgName);
16805            if (ps != null) {
16806                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16807
16808                // Static shared libs have same package with different versions where
16809                // we internally use a synthetic package name to allow multiple versions
16810                // of the same package, therefore we need to compare signatures against
16811                // the package setting for the latest library version.
16812                PackageSetting signatureCheckPs = ps;
16813                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16814                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16815                    if (libraryEntry != null) {
16816                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16817                    }
16818                }
16819
16820                // Quick sanity check that we're signed correctly if updating;
16821                // we'll check this again later when scanning, but we want to
16822                // bail early here before tripping over redefined permissions.
16823                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16824                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16825                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16826                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16827                                + pkg.packageName + " upgrade keys do not match the "
16828                                + "previously installed version");
16829                        return;
16830                    }
16831                } else {
16832                    try {
16833                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16834                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16835                        // We don't care about disabledPkgSetting on install for now.
16836                        final boolean compatMatch = verifySignatures(
16837                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16838                                compareRecover);
16839                        // The new KeySets will be re-added later in the scanning process.
16840                        if (compatMatch) {
16841                            synchronized (mPackages) {
16842                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16843                            }
16844                        }
16845                    } catch (PackageManagerException e) {
16846                        res.setError(e.error, e.getMessage());
16847                        return;
16848                    }
16849                }
16850
16851                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16852                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16853                    systemApp = (ps.pkg.applicationInfo.flags &
16854                            ApplicationInfo.FLAG_SYSTEM) != 0;
16855                }
16856                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16857            }
16858
16859            int N = pkg.permissions.size();
16860            for (int i = N-1; i >= 0; i--) {
16861                final PackageParser.Permission perm = pkg.permissions.get(i);
16862                final BasePermission bp =
16863                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16864
16865                // Don't allow anyone but the system to define ephemeral permissions.
16866                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16867                        && !systemApp) {
16868                    Slog.w(TAG, "Non-System package " + pkg.packageName
16869                            + " attempting to delcare ephemeral permission "
16870                            + perm.info.name + "; Removing ephemeral.");
16871                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16872                }
16873
16874                // Check whether the newly-scanned package wants to define an already-defined perm
16875                if (bp != null) {
16876                    // If the defining package is signed with our cert, it's okay.  This
16877                    // also includes the "updating the same package" case, of course.
16878                    // "updating same package" could also involve key-rotation.
16879                    final boolean sigsOk;
16880                    final String sourcePackageName = bp.getSourcePackageName();
16881                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16882                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16883                    if (sourcePackageName.equals(pkg.packageName)
16884                            && (ksms.shouldCheckUpgradeKeySetLocked(
16885                                    sourcePackageSetting, scanFlags))) {
16886                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16887                    } else {
16888                        sigsOk = compareSignatures(
16889                                sourcePackageSetting.signatures.mSigningDetails.signatures,
16890                                pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH;
16891                    }
16892                    if (!sigsOk) {
16893                        // If the owning package is the system itself, we log but allow
16894                        // install to proceed; we fail the install on all other permission
16895                        // redefinitions.
16896                        if (!sourcePackageName.equals("android")) {
16897                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16898                                    + pkg.packageName + " attempting to redeclare permission "
16899                                    + perm.info.name + " already owned by " + sourcePackageName);
16900                            res.origPermission = perm.info.name;
16901                            res.origPackage = sourcePackageName;
16902                            return;
16903                        } else {
16904                            Slog.w(TAG, "Package " + pkg.packageName
16905                                    + " attempting to redeclare system permission "
16906                                    + perm.info.name + "; ignoring new declaration");
16907                            pkg.permissions.remove(i);
16908                        }
16909                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16910                        // Prevent apps to change protection level to dangerous from any other
16911                        // type as this would allow a privilege escalation where an app adds a
16912                        // normal/signature permission in other app's group and later redefines
16913                        // it as dangerous leading to the group auto-grant.
16914                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16915                                == PermissionInfo.PROTECTION_DANGEROUS) {
16916                            if (bp != null && !bp.isRuntime()) {
16917                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16918                                        + "non-runtime permission " + perm.info.name
16919                                        + " to runtime; keeping old protection level");
16920                                perm.info.protectionLevel = bp.getProtectionLevel();
16921                            }
16922                        }
16923                    }
16924                }
16925            }
16926        }
16927
16928        if (systemApp) {
16929            if (onExternal) {
16930                // Abort update; system app can't be replaced with app on sdcard
16931                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16932                        "Cannot install updates to system apps on sdcard");
16933                return;
16934            } else if (instantApp) {
16935                // Abort update; system app can't be replaced with an instant app
16936                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16937                        "Cannot update a system app with an instant app");
16938                return;
16939            }
16940        }
16941
16942        if (args.move != null) {
16943            // We did an in-place move, so dex is ready to roll
16944            scanFlags |= SCAN_NO_DEX;
16945            scanFlags |= SCAN_MOVE;
16946
16947            synchronized (mPackages) {
16948                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16949                if (ps == null) {
16950                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16951                            "Missing settings for moved package " + pkgName);
16952                }
16953
16954                // We moved the entire application as-is, so bring over the
16955                // previously derived ABI information.
16956                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16957                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16958            }
16959
16960        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16961            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16962            scanFlags |= SCAN_NO_DEX;
16963
16964            try {
16965                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16966                    args.abiOverride : pkg.cpuAbiOverride);
16967                final boolean extractNativeLibs = !pkg.isLibrary();
16968                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
16969            } catch (PackageManagerException pme) {
16970                Slog.e(TAG, "Error deriving application ABI", pme);
16971                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16972                return;
16973            }
16974
16975            // Shared libraries for the package need to be updated.
16976            synchronized (mPackages) {
16977                try {
16978                    updateSharedLibrariesLPr(pkg, null);
16979                } catch (PackageManagerException e) {
16980                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16981                }
16982            }
16983        }
16984
16985        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16986            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16987            return;
16988        }
16989
16990        if (!instantApp) {
16991            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16992        } else {
16993            if (DEBUG_DOMAIN_VERIFICATION) {
16994                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16995            }
16996        }
16997
16998        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16999                "installPackageLI")) {
17000            if (replace) {
17001                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17002                    // Static libs have a synthetic package name containing the version
17003                    // and cannot be updated as an update would get a new package name,
17004                    // unless this is the exact same version code which is useful for
17005                    // development.
17006                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17007                    if (existingPkg != null &&
17008                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17009                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17010                                + "static-shared libs cannot be updated");
17011                        return;
17012                    }
17013                }
17014                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17015                        installerPackageName, res, args.installReason);
17016            } else {
17017                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17018                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17019            }
17020        }
17021
17022        // Check whether we need to dexopt the app.
17023        //
17024        // NOTE: it is IMPORTANT to call dexopt:
17025        //   - after doRename which will sync the package data from PackageParser.Package and its
17026        //     corresponding ApplicationInfo.
17027        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17028        //     uid of the application (pkg.applicationInfo.uid).
17029        //     This update happens in place!
17030        //
17031        // We only need to dexopt if the package meets ALL of the following conditions:
17032        //   1) it is not forward locked.
17033        //   2) it is not on on an external ASEC container.
17034        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17035        //
17036        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17037        // complete, so we skip this step during installation. Instead, we'll take extra time
17038        // the first time the instant app starts. It's preferred to do it this way to provide
17039        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17040        // middle of running an instant app. The default behaviour can be overridden
17041        // via gservices.
17042        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17043                && !forwardLocked
17044                && !pkg.applicationInfo.isExternalAsec()
17045                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17046                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17047
17048        if (performDexopt) {
17049            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17050            // Do not run PackageDexOptimizer through the local performDexOpt
17051            // method because `pkg` may not be in `mPackages` yet.
17052            //
17053            // Also, don't fail application installs if the dexopt step fails.
17054            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17055                    REASON_INSTALL,
17056                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
17057            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17058                    null /* instructionSets */,
17059                    getOrCreateCompilerPackageStats(pkg),
17060                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17061                    dexoptOptions);
17062            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17063        }
17064
17065        // Notify BackgroundDexOptService that the package has been changed.
17066        // If this is an update of a package which used to fail to compile,
17067        // BackgroundDexOptService will remove it from its blacklist.
17068        // TODO: Layering violation
17069        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17070
17071        synchronized (mPackages) {
17072            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17073            if (ps != null) {
17074                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17075                ps.setUpdateAvailable(false /*updateAvailable*/);
17076            }
17077
17078            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17079            for (int i = 0; i < childCount; i++) {
17080                PackageParser.Package childPkg = pkg.childPackages.get(i);
17081                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17082                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17083                if (childPs != null) {
17084                    childRes.newUsers = childPs.queryInstalledUsers(
17085                            sUserManager.getUserIds(), true);
17086                }
17087            }
17088
17089            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17090                updateSequenceNumberLP(ps, res.newUsers);
17091                updateInstantAppInstallerLocked(pkgName);
17092            }
17093        }
17094    }
17095
17096    private void startIntentFilterVerifications(int userId, boolean replacing,
17097            PackageParser.Package pkg) {
17098        if (mIntentFilterVerifierComponent == null) {
17099            Slog.w(TAG, "No IntentFilter verification will not be done as "
17100                    + "there is no IntentFilterVerifier available!");
17101            return;
17102        }
17103
17104        final int verifierUid = getPackageUid(
17105                mIntentFilterVerifierComponent.getPackageName(),
17106                MATCH_DEBUG_TRIAGED_MISSING,
17107                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17108
17109        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17110        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17111        mHandler.sendMessage(msg);
17112
17113        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17114        for (int i = 0; i < childCount; i++) {
17115            PackageParser.Package childPkg = pkg.childPackages.get(i);
17116            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17117            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17118            mHandler.sendMessage(msg);
17119        }
17120    }
17121
17122    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17123            PackageParser.Package pkg) {
17124        int size = pkg.activities.size();
17125        if (size == 0) {
17126            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17127                    "No activity, so no need to verify any IntentFilter!");
17128            return;
17129        }
17130
17131        final boolean hasDomainURLs = hasDomainURLs(pkg);
17132        if (!hasDomainURLs) {
17133            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17134                    "No domain URLs, so no need to verify any IntentFilter!");
17135            return;
17136        }
17137
17138        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17139                + " if any IntentFilter from the " + size
17140                + " Activities needs verification ...");
17141
17142        int count = 0;
17143        final String packageName = pkg.packageName;
17144
17145        synchronized (mPackages) {
17146            // If this is a new install and we see that we've already run verification for this
17147            // package, we have nothing to do: it means the state was restored from backup.
17148            if (!replacing) {
17149                IntentFilterVerificationInfo ivi =
17150                        mSettings.getIntentFilterVerificationLPr(packageName);
17151                if (ivi != null) {
17152                    if (DEBUG_DOMAIN_VERIFICATION) {
17153                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17154                                + ivi.getStatusString());
17155                    }
17156                    return;
17157                }
17158            }
17159
17160            // If any filters need to be verified, then all need to be.
17161            boolean needToVerify = false;
17162            for (PackageParser.Activity a : pkg.activities) {
17163                for (ActivityIntentInfo filter : a.intents) {
17164                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17165                        if (DEBUG_DOMAIN_VERIFICATION) {
17166                            Slog.d(TAG,
17167                                    "Intent filter needs verification, so processing all filters");
17168                        }
17169                        needToVerify = true;
17170                        break;
17171                    }
17172                }
17173            }
17174
17175            if (needToVerify) {
17176                final int verificationId = mIntentFilterVerificationToken++;
17177                for (PackageParser.Activity a : pkg.activities) {
17178                    for (ActivityIntentInfo filter : a.intents) {
17179                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17180                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17181                                    "Verification needed for IntentFilter:" + filter.toString());
17182                            mIntentFilterVerifier.addOneIntentFilterVerification(
17183                                    verifierUid, userId, verificationId, filter, packageName);
17184                            count++;
17185                        }
17186                    }
17187                }
17188            }
17189        }
17190
17191        if (count > 0) {
17192            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17193                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17194                    +  " for userId:" + userId);
17195            mIntentFilterVerifier.startVerifications(userId);
17196        } else {
17197            if (DEBUG_DOMAIN_VERIFICATION) {
17198                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17199            }
17200        }
17201    }
17202
17203    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17204        final ComponentName cn  = filter.activity.getComponentName();
17205        final String packageName = cn.getPackageName();
17206
17207        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17208                packageName);
17209        if (ivi == null) {
17210            return true;
17211        }
17212        int status = ivi.getStatus();
17213        switch (status) {
17214            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17215            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17216                return true;
17217
17218            default:
17219                // Nothing to do
17220                return false;
17221        }
17222    }
17223
17224    private static boolean isMultiArch(ApplicationInfo info) {
17225        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17226    }
17227
17228    private static boolean isExternal(PackageParser.Package pkg) {
17229        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17230    }
17231
17232    private static boolean isExternal(PackageSetting ps) {
17233        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17234    }
17235
17236    private static boolean isSystemApp(PackageParser.Package pkg) {
17237        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17238    }
17239
17240    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17241        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17242    }
17243
17244    private static boolean isOemApp(PackageParser.Package pkg) {
17245        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17246    }
17247
17248    private static boolean isVendorApp(PackageParser.Package pkg) {
17249        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17250    }
17251
17252    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17253        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17254    }
17255
17256    private static boolean isSystemApp(PackageSetting ps) {
17257        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17258    }
17259
17260    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17261        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17262    }
17263
17264    private int packageFlagsToInstallFlags(PackageSetting ps) {
17265        int installFlags = 0;
17266        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17267            // This existing package was an external ASEC install when we have
17268            // the external flag without a UUID
17269            installFlags |= PackageManager.INSTALL_EXTERNAL;
17270        }
17271        if (ps.isForwardLocked()) {
17272            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17273        }
17274        return installFlags;
17275    }
17276
17277    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17278        if (isExternal(pkg)) {
17279            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17280                return mSettings.getExternalVersion();
17281            } else {
17282                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17283            }
17284        } else {
17285            return mSettings.getInternalVersion();
17286        }
17287    }
17288
17289    private void deleteTempPackageFiles() {
17290        final FilenameFilter filter = new FilenameFilter() {
17291            public boolean accept(File dir, String name) {
17292                return name.startsWith("vmdl") && name.endsWith(".tmp");
17293            }
17294        };
17295        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17296            file.delete();
17297        }
17298    }
17299
17300    @Override
17301    public void deletePackageAsUser(String packageName, int versionCode,
17302            IPackageDeleteObserver observer, int userId, int flags) {
17303        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17304                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17305    }
17306
17307    @Override
17308    public void deletePackageVersioned(VersionedPackage versionedPackage,
17309            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17310        final int callingUid = Binder.getCallingUid();
17311        mContext.enforceCallingOrSelfPermission(
17312                android.Manifest.permission.DELETE_PACKAGES, null);
17313        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17314        Preconditions.checkNotNull(versionedPackage);
17315        Preconditions.checkNotNull(observer);
17316        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17317                PackageManager.VERSION_CODE_HIGHEST,
17318                Long.MAX_VALUE, "versionCode must be >= -1");
17319
17320        final String packageName = versionedPackage.getPackageName();
17321        final long versionCode = versionedPackage.getLongVersionCode();
17322        final String internalPackageName;
17323        synchronized (mPackages) {
17324            // Normalize package name to handle renamed packages and static libs
17325            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17326        }
17327
17328        final int uid = Binder.getCallingUid();
17329        if (!isOrphaned(internalPackageName)
17330                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17331            try {
17332                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17333                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17334                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17335                observer.onUserActionRequired(intent);
17336            } catch (RemoteException re) {
17337            }
17338            return;
17339        }
17340        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17341        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17342        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17343            mContext.enforceCallingOrSelfPermission(
17344                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17345                    "deletePackage for user " + userId);
17346        }
17347
17348        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17349            try {
17350                observer.onPackageDeleted(packageName,
17351                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17352            } catch (RemoteException re) {
17353            }
17354            return;
17355        }
17356
17357        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17358            try {
17359                observer.onPackageDeleted(packageName,
17360                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17361            } catch (RemoteException re) {
17362            }
17363            return;
17364        }
17365
17366        if (DEBUG_REMOVE) {
17367            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17368                    + " deleteAllUsers: " + deleteAllUsers + " version="
17369                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17370                    ? "VERSION_CODE_HIGHEST" : versionCode));
17371        }
17372        // Queue up an async operation since the package deletion may take a little while.
17373        mHandler.post(new Runnable() {
17374            public void run() {
17375                mHandler.removeCallbacks(this);
17376                int returnCode;
17377                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17378                boolean doDeletePackage = true;
17379                if (ps != null) {
17380                    final boolean targetIsInstantApp =
17381                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17382                    doDeletePackage = !targetIsInstantApp
17383                            || canViewInstantApps;
17384                }
17385                if (doDeletePackage) {
17386                    if (!deleteAllUsers) {
17387                        returnCode = deletePackageX(internalPackageName, versionCode,
17388                                userId, deleteFlags);
17389                    } else {
17390                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17391                                internalPackageName, users);
17392                        // If nobody is blocking uninstall, proceed with delete for all users
17393                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17394                            returnCode = deletePackageX(internalPackageName, versionCode,
17395                                    userId, deleteFlags);
17396                        } else {
17397                            // Otherwise uninstall individually for users with blockUninstalls=false
17398                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17399                            for (int userId : users) {
17400                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17401                                    returnCode = deletePackageX(internalPackageName, versionCode,
17402                                            userId, userFlags);
17403                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17404                                        Slog.w(TAG, "Package delete failed for user " + userId
17405                                                + ", returnCode " + returnCode);
17406                                    }
17407                                }
17408                            }
17409                            // The app has only been marked uninstalled for certain users.
17410                            // We still need to report that delete was blocked
17411                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17412                        }
17413                    }
17414                } else {
17415                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17416                }
17417                try {
17418                    observer.onPackageDeleted(packageName, returnCode, null);
17419                } catch (RemoteException e) {
17420                    Log.i(TAG, "Observer no longer exists.");
17421                } //end catch
17422            } //end run
17423        });
17424    }
17425
17426    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17427        if (pkg.staticSharedLibName != null) {
17428            return pkg.manifestPackageName;
17429        }
17430        return pkg.packageName;
17431    }
17432
17433    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17434        // Handle renamed packages
17435        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17436        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17437
17438        // Is this a static library?
17439        LongSparseArray<SharedLibraryEntry> versionedLib =
17440                mStaticLibsByDeclaringPackage.get(packageName);
17441        if (versionedLib == null || versionedLib.size() <= 0) {
17442            return packageName;
17443        }
17444
17445        // Figure out which lib versions the caller can see
17446        LongSparseLongArray versionsCallerCanSee = null;
17447        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17448        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17449                && callingAppId != Process.ROOT_UID) {
17450            versionsCallerCanSee = new LongSparseLongArray();
17451            String libName = versionedLib.valueAt(0).info.getName();
17452            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17453            if (uidPackages != null) {
17454                for (String uidPackage : uidPackages) {
17455                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17456                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17457                    if (libIdx >= 0) {
17458                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17459                        versionsCallerCanSee.append(libVersion, libVersion);
17460                    }
17461                }
17462            }
17463        }
17464
17465        // Caller can see nothing - done
17466        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17467            return packageName;
17468        }
17469
17470        // Find the version the caller can see and the app version code
17471        SharedLibraryEntry highestVersion = null;
17472        final int versionCount = versionedLib.size();
17473        for (int i = 0; i < versionCount; i++) {
17474            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17475            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17476                    libEntry.info.getLongVersion()) < 0) {
17477                continue;
17478            }
17479            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17480            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17481                if (libVersionCode == versionCode) {
17482                    return libEntry.apk;
17483                }
17484            } else if (highestVersion == null) {
17485                highestVersion = libEntry;
17486            } else if (libVersionCode  > highestVersion.info
17487                    .getDeclaringPackage().getLongVersionCode()) {
17488                highestVersion = libEntry;
17489            }
17490        }
17491
17492        if (highestVersion != null) {
17493            return highestVersion.apk;
17494        }
17495
17496        return packageName;
17497    }
17498
17499    boolean isCallerVerifier(int callingUid) {
17500        final int callingUserId = UserHandle.getUserId(callingUid);
17501        return mRequiredVerifierPackage != null &&
17502                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17503    }
17504
17505    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17506        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17507              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17508            return true;
17509        }
17510        final int callingUserId = UserHandle.getUserId(callingUid);
17511        // If the caller installed the pkgName, then allow it to silently uninstall.
17512        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17513            return true;
17514        }
17515
17516        // Allow package verifier to silently uninstall.
17517        if (mRequiredVerifierPackage != null &&
17518                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17519            return true;
17520        }
17521
17522        // Allow package uninstaller to silently uninstall.
17523        if (mRequiredUninstallerPackage != null &&
17524                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17525            return true;
17526        }
17527
17528        // Allow storage manager to silently uninstall.
17529        if (mStorageManagerPackage != null &&
17530                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17531            return true;
17532        }
17533
17534        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17535        // uninstall for device owner provisioning.
17536        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17537                == PERMISSION_GRANTED) {
17538            return true;
17539        }
17540
17541        return false;
17542    }
17543
17544    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17545        int[] result = EMPTY_INT_ARRAY;
17546        for (int userId : userIds) {
17547            if (getBlockUninstallForUser(packageName, userId)) {
17548                result = ArrayUtils.appendInt(result, userId);
17549            }
17550        }
17551        return result;
17552    }
17553
17554    @Override
17555    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17556        final int callingUid = Binder.getCallingUid();
17557        if (getInstantAppPackageName(callingUid) != null
17558                && !isCallerSameApp(packageName, callingUid)) {
17559            return false;
17560        }
17561        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17562    }
17563
17564    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17565        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17566                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17567        try {
17568            if (dpm != null) {
17569                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17570                        /* callingUserOnly =*/ false);
17571                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17572                        : deviceOwnerComponentName.getPackageName();
17573                // Does the package contains the device owner?
17574                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17575                // this check is probably not needed, since DO should be registered as a device
17576                // admin on some user too. (Original bug for this: b/17657954)
17577                if (packageName.equals(deviceOwnerPackageName)) {
17578                    return true;
17579                }
17580                // Does it contain a device admin for any user?
17581                int[] users;
17582                if (userId == UserHandle.USER_ALL) {
17583                    users = sUserManager.getUserIds();
17584                } else {
17585                    users = new int[]{userId};
17586                }
17587                for (int i = 0; i < users.length; ++i) {
17588                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17589                        return true;
17590                    }
17591                }
17592            }
17593        } catch (RemoteException e) {
17594        }
17595        return false;
17596    }
17597
17598    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17599        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17600    }
17601
17602    /**
17603     *  This method is an internal method that could be get invoked either
17604     *  to delete an installed package or to clean up a failed installation.
17605     *  After deleting an installed package, a broadcast is sent to notify any
17606     *  listeners that the package has been removed. For cleaning up a failed
17607     *  installation, the broadcast is not necessary since the package's
17608     *  installation wouldn't have sent the initial broadcast either
17609     *  The key steps in deleting a package are
17610     *  deleting the package information in internal structures like mPackages,
17611     *  deleting the packages base directories through installd
17612     *  updating mSettings to reflect current status
17613     *  persisting settings for later use
17614     *  sending a broadcast if necessary
17615     */
17616    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17617        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17618        final boolean res;
17619
17620        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17621                ? UserHandle.USER_ALL : userId;
17622
17623        if (isPackageDeviceAdmin(packageName, removeUser)) {
17624            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17625            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17626        }
17627
17628        PackageSetting uninstalledPs = null;
17629        PackageParser.Package pkg = null;
17630
17631        // for the uninstall-updates case and restricted profiles, remember the per-
17632        // user handle installed state
17633        int[] allUsers;
17634        synchronized (mPackages) {
17635            uninstalledPs = mSettings.mPackages.get(packageName);
17636            if (uninstalledPs == null) {
17637                Slog.w(TAG, "Not removing non-existent package " + packageName);
17638                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17639            }
17640
17641            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17642                    && uninstalledPs.versionCode != versionCode) {
17643                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17644                        + uninstalledPs.versionCode + " != " + versionCode);
17645                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17646            }
17647
17648            // Static shared libs can be declared by any package, so let us not
17649            // allow removing a package if it provides a lib others depend on.
17650            pkg = mPackages.get(packageName);
17651
17652            allUsers = sUserManager.getUserIds();
17653
17654            if (pkg != null && pkg.staticSharedLibName != null) {
17655                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17656                        pkg.staticSharedLibVersion);
17657                if (libEntry != null) {
17658                    for (int currUserId : allUsers) {
17659                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17660                            continue;
17661                        }
17662                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17663                                libEntry.info, 0, currUserId);
17664                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17665                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17666                                    + " hosting lib " + libEntry.info.getName() + " version "
17667                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17668                                    + " for user " + currUserId);
17669                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17670                        }
17671                    }
17672                }
17673            }
17674
17675            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17676        }
17677
17678        final int freezeUser;
17679        if (isUpdatedSystemApp(uninstalledPs)
17680                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17681            // We're downgrading a system app, which will apply to all users, so
17682            // freeze them all during the downgrade
17683            freezeUser = UserHandle.USER_ALL;
17684        } else {
17685            freezeUser = removeUser;
17686        }
17687
17688        synchronized (mInstallLock) {
17689            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17690            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17691                    deleteFlags, "deletePackageX")) {
17692                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17693                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17694            }
17695            synchronized (mPackages) {
17696                if (res) {
17697                    if (pkg != null) {
17698                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17699                    }
17700                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17701                    updateInstantAppInstallerLocked(packageName);
17702                }
17703            }
17704        }
17705
17706        if (res) {
17707            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17708            info.sendPackageRemovedBroadcasts(killApp);
17709            info.sendSystemPackageUpdatedBroadcasts();
17710            info.sendSystemPackageAppearedBroadcasts();
17711        }
17712        // Force a gc here.
17713        Runtime.getRuntime().gc();
17714        // Delete the resources here after sending the broadcast to let
17715        // other processes clean up before deleting resources.
17716        if (info.args != null) {
17717            synchronized (mInstallLock) {
17718                info.args.doPostDeleteLI(true);
17719            }
17720        }
17721
17722        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17723    }
17724
17725    static class PackageRemovedInfo {
17726        final PackageSender packageSender;
17727        String removedPackage;
17728        String installerPackageName;
17729        int uid = -1;
17730        int removedAppId = -1;
17731        int[] origUsers;
17732        int[] removedUsers = null;
17733        int[] broadcastUsers = null;
17734        int[] instantUserIds = null;
17735        SparseArray<Integer> installReasons;
17736        boolean isRemovedPackageSystemUpdate = false;
17737        boolean isUpdate;
17738        boolean dataRemoved;
17739        boolean removedForAllUsers;
17740        boolean isStaticSharedLib;
17741        // Clean up resources deleted packages.
17742        InstallArgs args = null;
17743        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17744        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17745
17746        PackageRemovedInfo(PackageSender packageSender) {
17747            this.packageSender = packageSender;
17748        }
17749
17750        void sendPackageRemovedBroadcasts(boolean killApp) {
17751            sendPackageRemovedBroadcastInternal(killApp);
17752            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17753            for (int i = 0; i < childCount; i++) {
17754                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17755                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17756            }
17757        }
17758
17759        void sendSystemPackageUpdatedBroadcasts() {
17760            if (isRemovedPackageSystemUpdate) {
17761                sendSystemPackageUpdatedBroadcastsInternal();
17762                final int childCount = (removedChildPackages != null)
17763                        ? removedChildPackages.size() : 0;
17764                for (int i = 0; i < childCount; i++) {
17765                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17766                    if (childInfo.isRemovedPackageSystemUpdate) {
17767                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17768                    }
17769                }
17770            }
17771        }
17772
17773        void sendSystemPackageAppearedBroadcasts() {
17774            final int packageCount = (appearedChildPackages != null)
17775                    ? appearedChildPackages.size() : 0;
17776            for (int i = 0; i < packageCount; i++) {
17777                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17778                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17779                    true /*sendBootCompleted*/, false /*startReceiver*/,
17780                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17781            }
17782        }
17783
17784        private void sendSystemPackageUpdatedBroadcastsInternal() {
17785            Bundle extras = new Bundle(2);
17786            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17787            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17788            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17789                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17790            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17791                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17792            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17793                null, null, 0, removedPackage, null, null, null);
17794            if (installerPackageName != null) {
17795                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17796                        removedPackage, extras, 0 /*flags*/,
17797                        installerPackageName, null, null, null);
17798                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17799                        removedPackage, extras, 0 /*flags*/,
17800                        installerPackageName, null, null, null);
17801            }
17802        }
17803
17804        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17805            // Don't send static shared library removal broadcasts as these
17806            // libs are visible only the the apps that depend on them an one
17807            // cannot remove the library if it has a dependency.
17808            if (isStaticSharedLib) {
17809                return;
17810            }
17811            Bundle extras = new Bundle(2);
17812            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17813            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17814            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17815            if (isUpdate || isRemovedPackageSystemUpdate) {
17816                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17817            }
17818            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17819            if (removedPackage != null) {
17820                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17821                    removedPackage, extras, 0, null /*targetPackage*/, null,
17822                    broadcastUsers, instantUserIds);
17823                if (installerPackageName != null) {
17824                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17825                            removedPackage, extras, 0 /*flags*/,
17826                            installerPackageName, null, broadcastUsers, instantUserIds);
17827                }
17828                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17829                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17830                        removedPackage, extras,
17831                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17832                        null, null, broadcastUsers, instantUserIds);
17833                    packageSender.notifyPackageRemoved(removedPackage);
17834                }
17835            }
17836            if (removedAppId >= 0) {
17837                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17838                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17839                    null, null, broadcastUsers, instantUserIds);
17840            }
17841        }
17842
17843        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17844            removedUsers = userIds;
17845            if (removedUsers == null) {
17846                broadcastUsers = null;
17847                return;
17848            }
17849
17850            broadcastUsers = EMPTY_INT_ARRAY;
17851            instantUserIds = EMPTY_INT_ARRAY;
17852            for (int i = userIds.length - 1; i >= 0; --i) {
17853                final int userId = userIds[i];
17854                if (deletedPackageSetting.getInstantApp(userId)) {
17855                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
17856                } else {
17857                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17858                }
17859            }
17860        }
17861    }
17862
17863    /*
17864     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17865     * flag is not set, the data directory is removed as well.
17866     * make sure this flag is set for partially installed apps. If not its meaningless to
17867     * delete a partially installed application.
17868     */
17869    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17870            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17871        String packageName = ps.name;
17872        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17873        // Retrieve object to delete permissions for shared user later on
17874        final PackageParser.Package deletedPkg;
17875        final PackageSetting deletedPs;
17876        // reader
17877        synchronized (mPackages) {
17878            deletedPkg = mPackages.get(packageName);
17879            deletedPs = mSettings.mPackages.get(packageName);
17880            if (outInfo != null) {
17881                outInfo.removedPackage = packageName;
17882                outInfo.installerPackageName = ps.installerPackageName;
17883                outInfo.isStaticSharedLib = deletedPkg != null
17884                        && deletedPkg.staticSharedLibName != null;
17885                outInfo.populateUsers(deletedPs == null ? null
17886                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17887            }
17888        }
17889
17890        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
17891
17892        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17893            final PackageParser.Package resolvedPkg;
17894            if (deletedPkg != null) {
17895                resolvedPkg = deletedPkg;
17896            } else {
17897                // We don't have a parsed package when it lives on an ejected
17898                // adopted storage device, so fake something together
17899                resolvedPkg = new PackageParser.Package(ps.name);
17900                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17901            }
17902            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17903                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17904            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17905            if (outInfo != null) {
17906                outInfo.dataRemoved = true;
17907            }
17908            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17909        }
17910
17911        int removedAppId = -1;
17912
17913        // writer
17914        synchronized (mPackages) {
17915            boolean installedStateChanged = false;
17916            if (deletedPs != null) {
17917                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17918                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17919                    clearDefaultBrowserIfNeeded(packageName);
17920                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17921                    removedAppId = mSettings.removePackageLPw(packageName);
17922                    if (outInfo != null) {
17923                        outInfo.removedAppId = removedAppId;
17924                    }
17925                    mPermissionManager.updatePermissions(
17926                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17927                    if (deletedPs.sharedUser != null) {
17928                        // Remove permissions associated with package. Since runtime
17929                        // permissions are per user we have to kill the removed package
17930                        // or packages running under the shared user of the removed
17931                        // package if revoking the permissions requested only by the removed
17932                        // package is successful and this causes a change in gids.
17933                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17934                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17935                                    userId);
17936                            if (userIdToKill == UserHandle.USER_ALL
17937                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17938                                // If gids changed for this user, kill all affected packages.
17939                                mHandler.post(new Runnable() {
17940                                    @Override
17941                                    public void run() {
17942                                        // This has to happen with no lock held.
17943                                        killApplication(deletedPs.name, deletedPs.appId,
17944                                                KILL_APP_REASON_GIDS_CHANGED);
17945                                    }
17946                                });
17947                                break;
17948                            }
17949                        }
17950                    }
17951                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17952                }
17953                // make sure to preserve per-user disabled state if this removal was just
17954                // a downgrade of a system app to the factory package
17955                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17956                    if (DEBUG_REMOVE) {
17957                        Slog.d(TAG, "Propagating install state across downgrade");
17958                    }
17959                    for (int userId : allUserHandles) {
17960                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17961                        if (DEBUG_REMOVE) {
17962                            Slog.d(TAG, "    user " + userId + " => " + installed);
17963                        }
17964                        if (installed != ps.getInstalled(userId)) {
17965                            installedStateChanged = true;
17966                        }
17967                        ps.setInstalled(installed, userId);
17968                    }
17969                }
17970            }
17971            // can downgrade to reader
17972            if (writeSettings) {
17973                // Save settings now
17974                mSettings.writeLPr();
17975            }
17976            if (installedStateChanged) {
17977                mSettings.writeKernelMappingLPr(ps);
17978            }
17979        }
17980        if (removedAppId != -1) {
17981            // A user ID was deleted here. Go through all users and remove it
17982            // from KeyStore.
17983            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17984        }
17985    }
17986
17987    static boolean locationIsPrivileged(String path) {
17988        try {
17989            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
17990            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
17991            return path.startsWith(privilegedAppDir.getCanonicalPath())
17992                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath());
17993        } catch (IOException e) {
17994            Slog.e(TAG, "Unable to access code path " + path);
17995        }
17996        return false;
17997    }
17998
17999    static boolean locationIsOem(String path) {
18000        try {
18001            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18002        } catch (IOException e) {
18003            Slog.e(TAG, "Unable to access code path " + path);
18004        }
18005        return false;
18006    }
18007
18008    static boolean locationIsVendor(String path) {
18009        try {
18010            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18011        } catch (IOException e) {
18012            Slog.e(TAG, "Unable to access code path " + path);
18013        }
18014        return false;
18015    }
18016
18017    /*
18018     * Tries to delete system package.
18019     */
18020    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18021            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18022            boolean writeSettings) {
18023        if (deletedPs.parentPackageName != null) {
18024            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18025            return false;
18026        }
18027
18028        final boolean applyUserRestrictions
18029                = (allUserHandles != null) && (outInfo.origUsers != null);
18030        final PackageSetting disabledPs;
18031        // Confirm if the system package has been updated
18032        // An updated system app can be deleted. This will also have to restore
18033        // the system pkg from system partition
18034        // reader
18035        synchronized (mPackages) {
18036            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18037        }
18038
18039        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18040                + " disabledPs=" + disabledPs);
18041
18042        if (disabledPs == null) {
18043            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18044            return false;
18045        } else if (DEBUG_REMOVE) {
18046            Slog.d(TAG, "Deleting system pkg from data partition");
18047        }
18048
18049        if (DEBUG_REMOVE) {
18050            if (applyUserRestrictions) {
18051                Slog.d(TAG, "Remembering install states:");
18052                for (int userId : allUserHandles) {
18053                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18054                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18055                }
18056            }
18057        }
18058
18059        // Delete the updated package
18060        outInfo.isRemovedPackageSystemUpdate = true;
18061        if (outInfo.removedChildPackages != null) {
18062            final int childCount = (deletedPs.childPackageNames != null)
18063                    ? deletedPs.childPackageNames.size() : 0;
18064            for (int i = 0; i < childCount; i++) {
18065                String childPackageName = deletedPs.childPackageNames.get(i);
18066                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18067                        .contains(childPackageName)) {
18068                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18069                            childPackageName);
18070                    if (childInfo != null) {
18071                        childInfo.isRemovedPackageSystemUpdate = true;
18072                    }
18073                }
18074            }
18075        }
18076
18077        if (disabledPs.versionCode < deletedPs.versionCode) {
18078            // Delete data for downgrades
18079            flags &= ~PackageManager.DELETE_KEEP_DATA;
18080        } else {
18081            // Preserve data by setting flag
18082            flags |= PackageManager.DELETE_KEEP_DATA;
18083        }
18084
18085        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18086                outInfo, writeSettings, disabledPs.pkg);
18087        if (!ret) {
18088            return false;
18089        }
18090
18091        // writer
18092        synchronized (mPackages) {
18093            // NOTE: The system package always needs to be enabled; even if it's for
18094            // a compressed stub. If we don't, installing the system package fails
18095            // during scan [scanning checks the disabled packages]. We will reverse
18096            // this later, after we've "installed" the stub.
18097            // Reinstate the old system package
18098            enableSystemPackageLPw(disabledPs.pkg);
18099            // Remove any native libraries from the upgraded package.
18100            removeNativeBinariesLI(deletedPs);
18101        }
18102
18103        // Install the system package
18104        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18105        try {
18106            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18107                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18108        } catch (PackageManagerException e) {
18109            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18110                    + e.getMessage());
18111            return false;
18112        } finally {
18113            if (disabledPs.pkg.isStub) {
18114                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18115            }
18116        }
18117        return true;
18118    }
18119
18120    /**
18121     * Installs a package that's already on the system partition.
18122     */
18123    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18124            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18125            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18126                    throws PackageManagerException {
18127        @ParseFlags int parseFlags =
18128                mDefParseFlags
18129                | PackageParser.PARSE_MUST_BE_APK
18130                | PackageParser.PARSE_IS_SYSTEM_DIR;
18131        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18132        if (isPrivileged || locationIsPrivileged(codePathString)) {
18133            scanFlags |= SCAN_AS_PRIVILEGED;
18134        }
18135        if (locationIsOem(codePathString)) {
18136            scanFlags |= SCAN_AS_OEM;
18137        }
18138        if (locationIsVendor(codePathString)) {
18139            scanFlags |= SCAN_AS_VENDOR;
18140        }
18141
18142        final File codePath = new File(codePathString);
18143        final PackageParser.Package pkg =
18144                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18145
18146        try {
18147            // update shared libraries for the newly re-installed system package
18148            updateSharedLibrariesLPr(pkg, null);
18149        } catch (PackageManagerException e) {
18150            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18151        }
18152
18153        prepareAppDataAfterInstallLIF(pkg);
18154
18155        // writer
18156        synchronized (mPackages) {
18157            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18158
18159            // Propagate the permissions state as we do not want to drop on the floor
18160            // runtime permissions. The update permissions method below will take
18161            // care of removing obsolete permissions and grant install permissions.
18162            if (origPermissionState != null) {
18163                ps.getPermissionsState().copyFrom(origPermissionState);
18164            }
18165            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18166                    mPermissionCallback);
18167
18168            final boolean applyUserRestrictions
18169                    = (allUserHandles != null) && (origUserHandles != null);
18170            if (applyUserRestrictions) {
18171                boolean installedStateChanged = false;
18172                if (DEBUG_REMOVE) {
18173                    Slog.d(TAG, "Propagating install state across reinstall");
18174                }
18175                for (int userId : allUserHandles) {
18176                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18177                    if (DEBUG_REMOVE) {
18178                        Slog.d(TAG, "    user " + userId + " => " + installed);
18179                    }
18180                    if (installed != ps.getInstalled(userId)) {
18181                        installedStateChanged = true;
18182                    }
18183                    ps.setInstalled(installed, userId);
18184
18185                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18186                }
18187                // Regardless of writeSettings we need to ensure that this restriction
18188                // state propagation is persisted
18189                mSettings.writeAllUsersPackageRestrictionsLPr();
18190                if (installedStateChanged) {
18191                    mSettings.writeKernelMappingLPr(ps);
18192                }
18193            }
18194            // can downgrade to reader here
18195            if (writeSettings) {
18196                mSettings.writeLPr();
18197            }
18198        }
18199        return pkg;
18200    }
18201
18202    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18203            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18204            PackageRemovedInfo outInfo, boolean writeSettings,
18205            PackageParser.Package replacingPackage) {
18206        synchronized (mPackages) {
18207            if (outInfo != null) {
18208                outInfo.uid = ps.appId;
18209            }
18210
18211            if (outInfo != null && outInfo.removedChildPackages != null) {
18212                final int childCount = (ps.childPackageNames != null)
18213                        ? ps.childPackageNames.size() : 0;
18214                for (int i = 0; i < childCount; i++) {
18215                    String childPackageName = ps.childPackageNames.get(i);
18216                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18217                    if (childPs == null) {
18218                        return false;
18219                    }
18220                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18221                            childPackageName);
18222                    if (childInfo != null) {
18223                        childInfo.uid = childPs.appId;
18224                    }
18225                }
18226            }
18227        }
18228
18229        // Delete package data from internal structures and also remove data if flag is set
18230        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18231
18232        // Delete the child packages data
18233        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18234        for (int i = 0; i < childCount; i++) {
18235            PackageSetting childPs;
18236            synchronized (mPackages) {
18237                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18238            }
18239            if (childPs != null) {
18240                PackageRemovedInfo childOutInfo = (outInfo != null
18241                        && outInfo.removedChildPackages != null)
18242                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18243                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18244                        && (replacingPackage != null
18245                        && !replacingPackage.hasChildPackage(childPs.name))
18246                        ? flags & ~DELETE_KEEP_DATA : flags;
18247                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18248                        deleteFlags, writeSettings);
18249            }
18250        }
18251
18252        // Delete application code and resources only for parent packages
18253        if (ps.parentPackageName == null) {
18254            if (deleteCodeAndResources && (outInfo != null)) {
18255                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18256                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18257                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18258            }
18259        }
18260
18261        return true;
18262    }
18263
18264    @Override
18265    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18266            int userId) {
18267        mContext.enforceCallingOrSelfPermission(
18268                android.Manifest.permission.DELETE_PACKAGES, null);
18269        synchronized (mPackages) {
18270            // Cannot block uninstall of static shared libs as they are
18271            // considered a part of the using app (emulating static linking).
18272            // Also static libs are installed always on internal storage.
18273            PackageParser.Package pkg = mPackages.get(packageName);
18274            if (pkg != null && pkg.staticSharedLibName != null) {
18275                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18276                        + " providing static shared library: " + pkg.staticSharedLibName);
18277                return false;
18278            }
18279            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18280            mSettings.writePackageRestrictionsLPr(userId);
18281        }
18282        return true;
18283    }
18284
18285    @Override
18286    public boolean getBlockUninstallForUser(String packageName, int userId) {
18287        synchronized (mPackages) {
18288            final PackageSetting ps = mSettings.mPackages.get(packageName);
18289            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18290                return false;
18291            }
18292            return mSettings.getBlockUninstallLPr(userId, packageName);
18293        }
18294    }
18295
18296    @Override
18297    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18298        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18299        synchronized (mPackages) {
18300            PackageSetting ps = mSettings.mPackages.get(packageName);
18301            if (ps == null) {
18302                Log.w(TAG, "Package doesn't exist: " + packageName);
18303                return false;
18304            }
18305            if (systemUserApp) {
18306                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18307            } else {
18308                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18309            }
18310            mSettings.writeLPr();
18311        }
18312        return true;
18313    }
18314
18315    /*
18316     * This method handles package deletion in general
18317     */
18318    private boolean deletePackageLIF(String packageName, UserHandle user,
18319            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18320            PackageRemovedInfo outInfo, boolean writeSettings,
18321            PackageParser.Package replacingPackage) {
18322        if (packageName == null) {
18323            Slog.w(TAG, "Attempt to delete null packageName.");
18324            return false;
18325        }
18326
18327        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18328
18329        PackageSetting ps;
18330        synchronized (mPackages) {
18331            ps = mSettings.mPackages.get(packageName);
18332            if (ps == null) {
18333                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18334                return false;
18335            }
18336
18337            if (ps.parentPackageName != null && (!isSystemApp(ps)
18338                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18339                if (DEBUG_REMOVE) {
18340                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18341                            + ((user == null) ? UserHandle.USER_ALL : user));
18342                }
18343                final int removedUserId = (user != null) ? user.getIdentifier()
18344                        : UserHandle.USER_ALL;
18345                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18346                    return false;
18347                }
18348                markPackageUninstalledForUserLPw(ps, user);
18349                scheduleWritePackageRestrictionsLocked(user);
18350                return true;
18351            }
18352        }
18353
18354        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18355                && user.getIdentifier() != UserHandle.USER_ALL)) {
18356            // The caller is asking that the package only be deleted for a single
18357            // user.  To do this, we just mark its uninstalled state and delete
18358            // its data. If this is a system app, we only allow this to happen if
18359            // they have set the special DELETE_SYSTEM_APP which requests different
18360            // semantics than normal for uninstalling system apps.
18361            markPackageUninstalledForUserLPw(ps, user);
18362
18363            if (!isSystemApp(ps)) {
18364                // Do not uninstall the APK if an app should be cached
18365                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18366                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18367                    // Other user still have this package installed, so all
18368                    // we need to do is clear this user's data and save that
18369                    // it is uninstalled.
18370                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18371                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18372                        return false;
18373                    }
18374                    scheduleWritePackageRestrictionsLocked(user);
18375                    return true;
18376                } else {
18377                    // We need to set it back to 'installed' so the uninstall
18378                    // broadcasts will be sent correctly.
18379                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18380                    ps.setInstalled(true, user.getIdentifier());
18381                    mSettings.writeKernelMappingLPr(ps);
18382                }
18383            } else {
18384                // This is a system app, so we assume that the
18385                // other users still have this package installed, so all
18386                // we need to do is clear this user's data and save that
18387                // it is uninstalled.
18388                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18389                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18390                    return false;
18391                }
18392                scheduleWritePackageRestrictionsLocked(user);
18393                return true;
18394            }
18395        }
18396
18397        // If we are deleting a composite package for all users, keep track
18398        // of result for each child.
18399        if (ps.childPackageNames != null && outInfo != null) {
18400            synchronized (mPackages) {
18401                final int childCount = ps.childPackageNames.size();
18402                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18403                for (int i = 0; i < childCount; i++) {
18404                    String childPackageName = ps.childPackageNames.get(i);
18405                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18406                    childInfo.removedPackage = childPackageName;
18407                    childInfo.installerPackageName = ps.installerPackageName;
18408                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18409                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18410                    if (childPs != null) {
18411                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18412                    }
18413                }
18414            }
18415        }
18416
18417        boolean ret = false;
18418        if (isSystemApp(ps)) {
18419            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18420            // When an updated system application is deleted we delete the existing resources
18421            // as well and fall back to existing code in system partition
18422            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18423        } else {
18424            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18425            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18426                    outInfo, writeSettings, replacingPackage);
18427        }
18428
18429        // Take a note whether we deleted the package for all users
18430        if (outInfo != null) {
18431            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18432            if (outInfo.removedChildPackages != null) {
18433                synchronized (mPackages) {
18434                    final int childCount = outInfo.removedChildPackages.size();
18435                    for (int i = 0; i < childCount; i++) {
18436                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18437                        if (childInfo != null) {
18438                            childInfo.removedForAllUsers = mPackages.get(
18439                                    childInfo.removedPackage) == null;
18440                        }
18441                    }
18442                }
18443            }
18444            // If we uninstalled an update to a system app there may be some
18445            // child packages that appeared as they are declared in the system
18446            // app but were not declared in the update.
18447            if (isSystemApp(ps)) {
18448                synchronized (mPackages) {
18449                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18450                    final int childCount = (updatedPs.childPackageNames != null)
18451                            ? updatedPs.childPackageNames.size() : 0;
18452                    for (int i = 0; i < childCount; i++) {
18453                        String childPackageName = updatedPs.childPackageNames.get(i);
18454                        if (outInfo.removedChildPackages == null
18455                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18456                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18457                            if (childPs == null) {
18458                                continue;
18459                            }
18460                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18461                            installRes.name = childPackageName;
18462                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18463                            installRes.pkg = mPackages.get(childPackageName);
18464                            installRes.uid = childPs.pkg.applicationInfo.uid;
18465                            if (outInfo.appearedChildPackages == null) {
18466                                outInfo.appearedChildPackages = new ArrayMap<>();
18467                            }
18468                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18469                        }
18470                    }
18471                }
18472            }
18473        }
18474
18475        return ret;
18476    }
18477
18478    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18479        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18480                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18481        for (int nextUserId : userIds) {
18482            if (DEBUG_REMOVE) {
18483                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18484            }
18485            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18486                    false /*installed*/,
18487                    true /*stopped*/,
18488                    true /*notLaunched*/,
18489                    false /*hidden*/,
18490                    false /*suspended*/,
18491                    false /*instantApp*/,
18492                    false /*virtualPreload*/,
18493                    null /*lastDisableAppCaller*/,
18494                    null /*enabledComponents*/,
18495                    null /*disabledComponents*/,
18496                    ps.readUserState(nextUserId).domainVerificationStatus,
18497                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18498                    null /*harmfulAppWarning*/);
18499        }
18500        mSettings.writeKernelMappingLPr(ps);
18501    }
18502
18503    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18504            PackageRemovedInfo outInfo) {
18505        final PackageParser.Package pkg;
18506        synchronized (mPackages) {
18507            pkg = mPackages.get(ps.name);
18508        }
18509
18510        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18511                : new int[] {userId};
18512        for (int nextUserId : userIds) {
18513            if (DEBUG_REMOVE) {
18514                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18515                        + nextUserId);
18516            }
18517
18518            destroyAppDataLIF(pkg, userId,
18519                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18520            destroyAppProfilesLIF(pkg, userId);
18521            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18522            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18523            schedulePackageCleaning(ps.name, nextUserId, false);
18524            synchronized (mPackages) {
18525                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18526                    scheduleWritePackageRestrictionsLocked(nextUserId);
18527                }
18528                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18529            }
18530        }
18531
18532        if (outInfo != null) {
18533            outInfo.removedPackage = ps.name;
18534            outInfo.installerPackageName = ps.installerPackageName;
18535            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18536            outInfo.removedAppId = ps.appId;
18537            outInfo.removedUsers = userIds;
18538            outInfo.broadcastUsers = userIds;
18539        }
18540
18541        return true;
18542    }
18543
18544    private final class ClearStorageConnection implements ServiceConnection {
18545        IMediaContainerService mContainerService;
18546
18547        @Override
18548        public void onServiceConnected(ComponentName name, IBinder service) {
18549            synchronized (this) {
18550                mContainerService = IMediaContainerService.Stub
18551                        .asInterface(Binder.allowBlocking(service));
18552                notifyAll();
18553            }
18554        }
18555
18556        @Override
18557        public void onServiceDisconnected(ComponentName name) {
18558        }
18559    }
18560
18561    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18562        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18563
18564        final boolean mounted;
18565        if (Environment.isExternalStorageEmulated()) {
18566            mounted = true;
18567        } else {
18568            final String status = Environment.getExternalStorageState();
18569
18570            mounted = status.equals(Environment.MEDIA_MOUNTED)
18571                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18572        }
18573
18574        if (!mounted) {
18575            return;
18576        }
18577
18578        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18579        int[] users;
18580        if (userId == UserHandle.USER_ALL) {
18581            users = sUserManager.getUserIds();
18582        } else {
18583            users = new int[] { userId };
18584        }
18585        final ClearStorageConnection conn = new ClearStorageConnection();
18586        if (mContext.bindServiceAsUser(
18587                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18588            try {
18589                for (int curUser : users) {
18590                    long timeout = SystemClock.uptimeMillis() + 5000;
18591                    synchronized (conn) {
18592                        long now;
18593                        while (conn.mContainerService == null &&
18594                                (now = SystemClock.uptimeMillis()) < timeout) {
18595                            try {
18596                                conn.wait(timeout - now);
18597                            } catch (InterruptedException e) {
18598                            }
18599                        }
18600                    }
18601                    if (conn.mContainerService == null) {
18602                        return;
18603                    }
18604
18605                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18606                    clearDirectory(conn.mContainerService,
18607                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18608                    if (allData) {
18609                        clearDirectory(conn.mContainerService,
18610                                userEnv.buildExternalStorageAppDataDirs(packageName));
18611                        clearDirectory(conn.mContainerService,
18612                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18613                    }
18614                }
18615            } finally {
18616                mContext.unbindService(conn);
18617            }
18618        }
18619    }
18620
18621    @Override
18622    public void clearApplicationProfileData(String packageName) {
18623        enforceSystemOrRoot("Only the system can clear all profile data");
18624
18625        final PackageParser.Package pkg;
18626        synchronized (mPackages) {
18627            pkg = mPackages.get(packageName);
18628        }
18629
18630        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18631            synchronized (mInstallLock) {
18632                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18633            }
18634        }
18635    }
18636
18637    @Override
18638    public void clearApplicationUserData(final String packageName,
18639            final IPackageDataObserver observer, final int userId) {
18640        mContext.enforceCallingOrSelfPermission(
18641                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18642
18643        final int callingUid = Binder.getCallingUid();
18644        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18645                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18646
18647        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18648        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18649        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18650            throw new SecurityException("Cannot clear data for a protected package: "
18651                    + packageName);
18652        }
18653        // Queue up an async operation since the package deletion may take a little while.
18654        mHandler.post(new Runnable() {
18655            public void run() {
18656                mHandler.removeCallbacks(this);
18657                final boolean succeeded;
18658                if (!filterApp) {
18659                    try (PackageFreezer freezer = freezePackage(packageName,
18660                            "clearApplicationUserData")) {
18661                        synchronized (mInstallLock) {
18662                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18663                        }
18664                        clearExternalStorageDataSync(packageName, userId, true);
18665                        synchronized (mPackages) {
18666                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18667                                    packageName, userId);
18668                        }
18669                    }
18670                    if (succeeded) {
18671                        // invoke DeviceStorageMonitor's update method to clear any notifications
18672                        DeviceStorageMonitorInternal dsm = LocalServices
18673                                .getService(DeviceStorageMonitorInternal.class);
18674                        if (dsm != null) {
18675                            dsm.checkMemory();
18676                        }
18677                    }
18678                } else {
18679                    succeeded = false;
18680                }
18681                if (observer != null) {
18682                    try {
18683                        observer.onRemoveCompleted(packageName, succeeded);
18684                    } catch (RemoteException e) {
18685                        Log.i(TAG, "Observer no longer exists.");
18686                    }
18687                } //end if observer
18688            } //end run
18689        });
18690    }
18691
18692    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18693        if (packageName == null) {
18694            Slog.w(TAG, "Attempt to delete null packageName.");
18695            return false;
18696        }
18697
18698        // Try finding details about the requested package
18699        PackageParser.Package pkg;
18700        synchronized (mPackages) {
18701            pkg = mPackages.get(packageName);
18702            if (pkg == null) {
18703                final PackageSetting ps = mSettings.mPackages.get(packageName);
18704                if (ps != null) {
18705                    pkg = ps.pkg;
18706                }
18707            }
18708
18709            if (pkg == null) {
18710                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18711                return false;
18712            }
18713
18714            PackageSetting ps = (PackageSetting) pkg.mExtras;
18715            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18716        }
18717
18718        clearAppDataLIF(pkg, userId,
18719                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18720
18721        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18722        removeKeystoreDataIfNeeded(userId, appId);
18723
18724        UserManagerInternal umInternal = getUserManagerInternal();
18725        final int flags;
18726        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18727            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18728        } else if (umInternal.isUserRunning(userId)) {
18729            flags = StorageManager.FLAG_STORAGE_DE;
18730        } else {
18731            flags = 0;
18732        }
18733        prepareAppDataContentsLIF(pkg, userId, flags);
18734
18735        return true;
18736    }
18737
18738    /**
18739     * Reverts user permission state changes (permissions and flags) in
18740     * all packages for a given user.
18741     *
18742     * @param userId The device user for which to do a reset.
18743     */
18744    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18745        final int packageCount = mPackages.size();
18746        for (int i = 0; i < packageCount; i++) {
18747            PackageParser.Package pkg = mPackages.valueAt(i);
18748            PackageSetting ps = (PackageSetting) pkg.mExtras;
18749            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18750        }
18751    }
18752
18753    private void resetNetworkPolicies(int userId) {
18754        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18755    }
18756
18757    /**
18758     * Reverts user permission state changes (permissions and flags).
18759     *
18760     * @param ps The package for which to reset.
18761     * @param userId The device user for which to do a reset.
18762     */
18763    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18764            final PackageSetting ps, final int userId) {
18765        if (ps.pkg == null) {
18766            return;
18767        }
18768
18769        // These are flags that can change base on user actions.
18770        final int userSettableMask = FLAG_PERMISSION_USER_SET
18771                | FLAG_PERMISSION_USER_FIXED
18772                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18773                | FLAG_PERMISSION_REVIEW_REQUIRED;
18774
18775        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18776                | FLAG_PERMISSION_POLICY_FIXED;
18777
18778        boolean writeInstallPermissions = false;
18779        boolean writeRuntimePermissions = false;
18780
18781        final int permissionCount = ps.pkg.requestedPermissions.size();
18782        for (int i = 0; i < permissionCount; i++) {
18783            final String permName = ps.pkg.requestedPermissions.get(i);
18784            final BasePermission bp =
18785                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18786            if (bp == null) {
18787                continue;
18788            }
18789
18790            // If shared user we just reset the state to which only this app contributed.
18791            if (ps.sharedUser != null) {
18792                boolean used = false;
18793                final int packageCount = ps.sharedUser.packages.size();
18794                for (int j = 0; j < packageCount; j++) {
18795                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18796                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18797                            && pkg.pkg.requestedPermissions.contains(permName)) {
18798                        used = true;
18799                        break;
18800                    }
18801                }
18802                if (used) {
18803                    continue;
18804                }
18805            }
18806
18807            final PermissionsState permissionsState = ps.getPermissionsState();
18808
18809            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18810
18811            // Always clear the user settable flags.
18812            final boolean hasInstallState =
18813                    permissionsState.getInstallPermissionState(permName) != null;
18814            // If permission review is enabled and this is a legacy app, mark the
18815            // permission as requiring a review as this is the initial state.
18816            int flags = 0;
18817            if (mSettings.mPermissions.mPermissionReviewRequired
18818                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18819                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18820            }
18821            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18822                if (hasInstallState) {
18823                    writeInstallPermissions = true;
18824                } else {
18825                    writeRuntimePermissions = true;
18826                }
18827            }
18828
18829            // Below is only runtime permission handling.
18830            if (!bp.isRuntime()) {
18831                continue;
18832            }
18833
18834            // Never clobber system or policy.
18835            if ((oldFlags & policyOrSystemFlags) != 0) {
18836                continue;
18837            }
18838
18839            // If this permission was granted by default, make sure it is.
18840            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18841                if (permissionsState.grantRuntimePermission(bp, userId)
18842                        != PERMISSION_OPERATION_FAILURE) {
18843                    writeRuntimePermissions = true;
18844                }
18845            // If permission review is enabled the permissions for a legacy apps
18846            // are represented as constantly granted runtime ones, so don't revoke.
18847            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18848                // Otherwise, reset the permission.
18849                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18850                switch (revokeResult) {
18851                    case PERMISSION_OPERATION_SUCCESS:
18852                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18853                        writeRuntimePermissions = true;
18854                        final int appId = ps.appId;
18855                        mHandler.post(new Runnable() {
18856                            @Override
18857                            public void run() {
18858                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18859                            }
18860                        });
18861                    } break;
18862                }
18863            }
18864        }
18865
18866        // Synchronously write as we are taking permissions away.
18867        if (writeRuntimePermissions) {
18868            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18869        }
18870
18871        // Synchronously write as we are taking permissions away.
18872        if (writeInstallPermissions) {
18873            mSettings.writeLPr();
18874        }
18875    }
18876
18877    /**
18878     * Remove entries from the keystore daemon. Will only remove it if the
18879     * {@code appId} is valid.
18880     */
18881    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18882        if (appId < 0) {
18883            return;
18884        }
18885
18886        final KeyStore keyStore = KeyStore.getInstance();
18887        if (keyStore != null) {
18888            if (userId == UserHandle.USER_ALL) {
18889                for (final int individual : sUserManager.getUserIds()) {
18890                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18891                }
18892            } else {
18893                keyStore.clearUid(UserHandle.getUid(userId, appId));
18894            }
18895        } else {
18896            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18897        }
18898    }
18899
18900    @Override
18901    public void deleteApplicationCacheFiles(final String packageName,
18902            final IPackageDataObserver observer) {
18903        final int userId = UserHandle.getCallingUserId();
18904        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18905    }
18906
18907    @Override
18908    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18909            final IPackageDataObserver observer) {
18910        final int callingUid = Binder.getCallingUid();
18911        mContext.enforceCallingOrSelfPermission(
18912                android.Manifest.permission.DELETE_CACHE_FILES, null);
18913        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18914                /* requireFullPermission= */ true, /* checkShell= */ false,
18915                "delete application cache files");
18916        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18917                android.Manifest.permission.ACCESS_INSTANT_APPS);
18918
18919        final PackageParser.Package pkg;
18920        synchronized (mPackages) {
18921            pkg = mPackages.get(packageName);
18922        }
18923
18924        // Queue up an async operation since the package deletion may take a little while.
18925        mHandler.post(new Runnable() {
18926            public void run() {
18927                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18928                boolean doClearData = true;
18929                if (ps != null) {
18930                    final boolean targetIsInstantApp =
18931                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18932                    doClearData = !targetIsInstantApp
18933                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18934                }
18935                if (doClearData) {
18936                    synchronized (mInstallLock) {
18937                        final int flags = StorageManager.FLAG_STORAGE_DE
18938                                | StorageManager.FLAG_STORAGE_CE;
18939                        // We're only clearing cache files, so we don't care if the
18940                        // app is unfrozen and still able to run
18941                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18942                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18943                    }
18944                    clearExternalStorageDataSync(packageName, userId, false);
18945                }
18946                if (observer != null) {
18947                    try {
18948                        observer.onRemoveCompleted(packageName, true);
18949                    } catch (RemoteException e) {
18950                        Log.i(TAG, "Observer no longer exists.");
18951                    }
18952                }
18953            }
18954        });
18955    }
18956
18957    @Override
18958    public void getPackageSizeInfo(final String packageName, int userHandle,
18959            final IPackageStatsObserver observer) {
18960        throw new UnsupportedOperationException(
18961                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18962    }
18963
18964    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18965        final PackageSetting ps;
18966        synchronized (mPackages) {
18967            ps = mSettings.mPackages.get(packageName);
18968            if (ps == null) {
18969                Slog.w(TAG, "Failed to find settings for " + packageName);
18970                return false;
18971            }
18972        }
18973
18974        final String[] packageNames = { packageName };
18975        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18976        final String[] codePaths = { ps.codePathString };
18977
18978        try {
18979            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18980                    ps.appId, ceDataInodes, codePaths, stats);
18981
18982            // For now, ignore code size of packages on system partition
18983            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18984                stats.codeSize = 0;
18985            }
18986
18987            // External clients expect these to be tracked separately
18988            stats.dataSize -= stats.cacheSize;
18989
18990        } catch (InstallerException e) {
18991            Slog.w(TAG, String.valueOf(e));
18992            return false;
18993        }
18994
18995        return true;
18996    }
18997
18998    private int getUidTargetSdkVersionLockedLPr(int uid) {
18999        Object obj = mSettings.getUserIdLPr(uid);
19000        if (obj instanceof SharedUserSetting) {
19001            final SharedUserSetting sus = (SharedUserSetting) obj;
19002            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19003            final Iterator<PackageSetting> it = sus.packages.iterator();
19004            while (it.hasNext()) {
19005                final PackageSetting ps = it.next();
19006                if (ps.pkg != null) {
19007                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19008                    if (v < vers) vers = v;
19009                }
19010            }
19011            return vers;
19012        } else if (obj instanceof PackageSetting) {
19013            final PackageSetting ps = (PackageSetting) obj;
19014            if (ps.pkg != null) {
19015                return ps.pkg.applicationInfo.targetSdkVersion;
19016            }
19017        }
19018        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19019    }
19020
19021    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19022        final PackageParser.Package p = mPackages.get(packageName);
19023        if (p != null) {
19024            return p.applicationInfo.targetSdkVersion;
19025        }
19026        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19027    }
19028
19029    @Override
19030    public void addPreferredActivity(IntentFilter filter, int match,
19031            ComponentName[] set, ComponentName activity, int userId) {
19032        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19033                "Adding preferred");
19034    }
19035
19036    private void addPreferredActivityInternal(IntentFilter filter, int match,
19037            ComponentName[] set, ComponentName activity, boolean always, int userId,
19038            String opname) {
19039        // writer
19040        int callingUid = Binder.getCallingUid();
19041        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19042                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19043        if (filter.countActions() == 0) {
19044            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19045            return;
19046        }
19047        synchronized (mPackages) {
19048            if (mContext.checkCallingOrSelfPermission(
19049                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19050                    != PackageManager.PERMISSION_GRANTED) {
19051                if (getUidTargetSdkVersionLockedLPr(callingUid)
19052                        < Build.VERSION_CODES.FROYO) {
19053                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19054                            + callingUid);
19055                    return;
19056                }
19057                mContext.enforceCallingOrSelfPermission(
19058                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19059            }
19060
19061            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19062            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19063                    + userId + ":");
19064            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19065            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19066            scheduleWritePackageRestrictionsLocked(userId);
19067            postPreferredActivityChangedBroadcast(userId);
19068        }
19069    }
19070
19071    private void postPreferredActivityChangedBroadcast(int userId) {
19072        mHandler.post(() -> {
19073            final IActivityManager am = ActivityManager.getService();
19074            if (am == null) {
19075                return;
19076            }
19077
19078            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19079            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19080            try {
19081                am.broadcastIntent(null, intent, null, null,
19082                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19083                        null, false, false, userId);
19084            } catch (RemoteException e) {
19085            }
19086        });
19087    }
19088
19089    @Override
19090    public void replacePreferredActivity(IntentFilter filter, int match,
19091            ComponentName[] set, ComponentName activity, int userId) {
19092        if (filter.countActions() != 1) {
19093            throw new IllegalArgumentException(
19094                    "replacePreferredActivity expects filter to have only 1 action.");
19095        }
19096        if (filter.countDataAuthorities() != 0
19097                || filter.countDataPaths() != 0
19098                || filter.countDataSchemes() > 1
19099                || filter.countDataTypes() != 0) {
19100            throw new IllegalArgumentException(
19101                    "replacePreferredActivity expects filter to have no data authorities, " +
19102                    "paths, or types; and at most one scheme.");
19103        }
19104
19105        final int callingUid = Binder.getCallingUid();
19106        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19107                true /* requireFullPermission */, false /* checkShell */,
19108                "replace preferred activity");
19109        synchronized (mPackages) {
19110            if (mContext.checkCallingOrSelfPermission(
19111                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19112                    != PackageManager.PERMISSION_GRANTED) {
19113                if (getUidTargetSdkVersionLockedLPr(callingUid)
19114                        < Build.VERSION_CODES.FROYO) {
19115                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19116                            + Binder.getCallingUid());
19117                    return;
19118                }
19119                mContext.enforceCallingOrSelfPermission(
19120                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19121            }
19122
19123            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19124            if (pir != null) {
19125                // Get all of the existing entries that exactly match this filter.
19126                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19127                if (existing != null && existing.size() == 1) {
19128                    PreferredActivity cur = existing.get(0);
19129                    if (DEBUG_PREFERRED) {
19130                        Slog.i(TAG, "Checking replace of preferred:");
19131                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19132                        if (!cur.mPref.mAlways) {
19133                            Slog.i(TAG, "  -- CUR; not mAlways!");
19134                        } else {
19135                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19136                            Slog.i(TAG, "  -- CUR: mSet="
19137                                    + Arrays.toString(cur.mPref.mSetComponents));
19138                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19139                            Slog.i(TAG, "  -- NEW: mMatch="
19140                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19141                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19142                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19143                        }
19144                    }
19145                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19146                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19147                            && cur.mPref.sameSet(set)) {
19148                        // Setting the preferred activity to what it happens to be already
19149                        if (DEBUG_PREFERRED) {
19150                            Slog.i(TAG, "Replacing with same preferred activity "
19151                                    + cur.mPref.mShortComponent + " for user "
19152                                    + userId + ":");
19153                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19154                        }
19155                        return;
19156                    }
19157                }
19158
19159                if (existing != null) {
19160                    if (DEBUG_PREFERRED) {
19161                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19162                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19163                    }
19164                    for (int i = 0; i < existing.size(); i++) {
19165                        PreferredActivity pa = existing.get(i);
19166                        if (DEBUG_PREFERRED) {
19167                            Slog.i(TAG, "Removing existing preferred activity "
19168                                    + pa.mPref.mComponent + ":");
19169                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19170                        }
19171                        pir.removeFilter(pa);
19172                    }
19173                }
19174            }
19175            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19176                    "Replacing preferred");
19177        }
19178    }
19179
19180    @Override
19181    public void clearPackagePreferredActivities(String packageName) {
19182        final int callingUid = Binder.getCallingUid();
19183        if (getInstantAppPackageName(callingUid) != null) {
19184            return;
19185        }
19186        // writer
19187        synchronized (mPackages) {
19188            PackageParser.Package pkg = mPackages.get(packageName);
19189            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19190                if (mContext.checkCallingOrSelfPermission(
19191                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19192                        != PackageManager.PERMISSION_GRANTED) {
19193                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19194                            < Build.VERSION_CODES.FROYO) {
19195                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19196                                + callingUid);
19197                        return;
19198                    }
19199                    mContext.enforceCallingOrSelfPermission(
19200                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19201                }
19202            }
19203            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19204            if (ps != null
19205                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19206                return;
19207            }
19208            int user = UserHandle.getCallingUserId();
19209            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19210                scheduleWritePackageRestrictionsLocked(user);
19211            }
19212        }
19213    }
19214
19215    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19216    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19217        ArrayList<PreferredActivity> removed = null;
19218        boolean changed = false;
19219        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19220            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19221            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19222            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19223                continue;
19224            }
19225            Iterator<PreferredActivity> it = pir.filterIterator();
19226            while (it.hasNext()) {
19227                PreferredActivity pa = it.next();
19228                // Mark entry for removal only if it matches the package name
19229                // and the entry is of type "always".
19230                if (packageName == null ||
19231                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19232                                && pa.mPref.mAlways)) {
19233                    if (removed == null) {
19234                        removed = new ArrayList<PreferredActivity>();
19235                    }
19236                    removed.add(pa);
19237                }
19238            }
19239            if (removed != null) {
19240                for (int j=0; j<removed.size(); j++) {
19241                    PreferredActivity pa = removed.get(j);
19242                    pir.removeFilter(pa);
19243                }
19244                changed = true;
19245            }
19246        }
19247        if (changed) {
19248            postPreferredActivityChangedBroadcast(userId);
19249        }
19250        return changed;
19251    }
19252
19253    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19254    private void clearIntentFilterVerificationsLPw(int userId) {
19255        final int packageCount = mPackages.size();
19256        for (int i = 0; i < packageCount; i++) {
19257            PackageParser.Package pkg = mPackages.valueAt(i);
19258            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19259        }
19260    }
19261
19262    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19263    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19264        if (userId == UserHandle.USER_ALL) {
19265            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19266                    sUserManager.getUserIds())) {
19267                for (int oneUserId : sUserManager.getUserIds()) {
19268                    scheduleWritePackageRestrictionsLocked(oneUserId);
19269                }
19270            }
19271        } else {
19272            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19273                scheduleWritePackageRestrictionsLocked(userId);
19274            }
19275        }
19276    }
19277
19278    /** Clears state for all users, and touches intent filter verification policy */
19279    void clearDefaultBrowserIfNeeded(String packageName) {
19280        for (int oneUserId : sUserManager.getUserIds()) {
19281            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19282        }
19283    }
19284
19285    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19286        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19287        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19288            if (packageName.equals(defaultBrowserPackageName)) {
19289                setDefaultBrowserPackageName(null, userId);
19290            }
19291        }
19292    }
19293
19294    @Override
19295    public void resetApplicationPreferences(int userId) {
19296        mContext.enforceCallingOrSelfPermission(
19297                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19298        final long identity = Binder.clearCallingIdentity();
19299        // writer
19300        try {
19301            synchronized (mPackages) {
19302                clearPackagePreferredActivitiesLPw(null, userId);
19303                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19304                // TODO: We have to reset the default SMS and Phone. This requires
19305                // significant refactoring to keep all default apps in the package
19306                // manager (cleaner but more work) or have the services provide
19307                // callbacks to the package manager to request a default app reset.
19308                applyFactoryDefaultBrowserLPw(userId);
19309                clearIntentFilterVerificationsLPw(userId);
19310                primeDomainVerificationsLPw(userId);
19311                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19312                scheduleWritePackageRestrictionsLocked(userId);
19313            }
19314            resetNetworkPolicies(userId);
19315        } finally {
19316            Binder.restoreCallingIdentity(identity);
19317        }
19318    }
19319
19320    @Override
19321    public int getPreferredActivities(List<IntentFilter> outFilters,
19322            List<ComponentName> outActivities, String packageName) {
19323        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19324            return 0;
19325        }
19326        int num = 0;
19327        final int userId = UserHandle.getCallingUserId();
19328        // reader
19329        synchronized (mPackages) {
19330            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19331            if (pir != null) {
19332                final Iterator<PreferredActivity> it = pir.filterIterator();
19333                while (it.hasNext()) {
19334                    final PreferredActivity pa = it.next();
19335                    if (packageName == null
19336                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19337                                    && pa.mPref.mAlways)) {
19338                        if (outFilters != null) {
19339                            outFilters.add(new IntentFilter(pa));
19340                        }
19341                        if (outActivities != null) {
19342                            outActivities.add(pa.mPref.mComponent);
19343                        }
19344                    }
19345                }
19346            }
19347        }
19348
19349        return num;
19350    }
19351
19352    @Override
19353    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19354            int userId) {
19355        int callingUid = Binder.getCallingUid();
19356        if (callingUid != Process.SYSTEM_UID) {
19357            throw new SecurityException(
19358                    "addPersistentPreferredActivity can only be run by the system");
19359        }
19360        if (filter.countActions() == 0) {
19361            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19362            return;
19363        }
19364        synchronized (mPackages) {
19365            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19366                    ":");
19367            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19368            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19369                    new PersistentPreferredActivity(filter, activity));
19370            scheduleWritePackageRestrictionsLocked(userId);
19371            postPreferredActivityChangedBroadcast(userId);
19372        }
19373    }
19374
19375    @Override
19376    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19377        int callingUid = Binder.getCallingUid();
19378        if (callingUid != Process.SYSTEM_UID) {
19379            throw new SecurityException(
19380                    "clearPackagePersistentPreferredActivities can only be run by the system");
19381        }
19382        ArrayList<PersistentPreferredActivity> removed = null;
19383        boolean changed = false;
19384        synchronized (mPackages) {
19385            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19386                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19387                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19388                        .valueAt(i);
19389                if (userId != thisUserId) {
19390                    continue;
19391                }
19392                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19393                while (it.hasNext()) {
19394                    PersistentPreferredActivity ppa = it.next();
19395                    // Mark entry for removal only if it matches the package name.
19396                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19397                        if (removed == null) {
19398                            removed = new ArrayList<PersistentPreferredActivity>();
19399                        }
19400                        removed.add(ppa);
19401                    }
19402                }
19403                if (removed != null) {
19404                    for (int j=0; j<removed.size(); j++) {
19405                        PersistentPreferredActivity ppa = removed.get(j);
19406                        ppir.removeFilter(ppa);
19407                    }
19408                    changed = true;
19409                }
19410            }
19411
19412            if (changed) {
19413                scheduleWritePackageRestrictionsLocked(userId);
19414                postPreferredActivityChangedBroadcast(userId);
19415            }
19416        }
19417    }
19418
19419    /**
19420     * Common machinery for picking apart a restored XML blob and passing
19421     * it to a caller-supplied functor to be applied to the running system.
19422     */
19423    private void restoreFromXml(XmlPullParser parser, int userId,
19424            String expectedStartTag, BlobXmlRestorer functor)
19425            throws IOException, XmlPullParserException {
19426        int type;
19427        while ((type = parser.next()) != XmlPullParser.START_TAG
19428                && type != XmlPullParser.END_DOCUMENT) {
19429        }
19430        if (type != XmlPullParser.START_TAG) {
19431            // oops didn't find a start tag?!
19432            if (DEBUG_BACKUP) {
19433                Slog.e(TAG, "Didn't find start tag during restore");
19434            }
19435            return;
19436        }
19437Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19438        // this is supposed to be TAG_PREFERRED_BACKUP
19439        if (!expectedStartTag.equals(parser.getName())) {
19440            if (DEBUG_BACKUP) {
19441                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19442            }
19443            return;
19444        }
19445
19446        // skip interfering stuff, then we're aligned with the backing implementation
19447        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19448Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19449        functor.apply(parser, userId);
19450    }
19451
19452    private interface BlobXmlRestorer {
19453        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19454    }
19455
19456    /**
19457     * Non-Binder method, support for the backup/restore mechanism: write the
19458     * full set of preferred activities in its canonical XML format.  Returns the
19459     * XML output as a byte array, or null if there is none.
19460     */
19461    @Override
19462    public byte[] getPreferredActivityBackup(int userId) {
19463        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19464            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19465        }
19466
19467        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19468        try {
19469            final XmlSerializer serializer = new FastXmlSerializer();
19470            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19471            serializer.startDocument(null, true);
19472            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19473
19474            synchronized (mPackages) {
19475                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19476            }
19477
19478            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19479            serializer.endDocument();
19480            serializer.flush();
19481        } catch (Exception e) {
19482            if (DEBUG_BACKUP) {
19483                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19484            }
19485            return null;
19486        }
19487
19488        return dataStream.toByteArray();
19489    }
19490
19491    @Override
19492    public void restorePreferredActivities(byte[] backup, int userId) {
19493        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19494            throw new SecurityException("Only the system may call restorePreferredActivities()");
19495        }
19496
19497        try {
19498            final XmlPullParser parser = Xml.newPullParser();
19499            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19500            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19501                    new BlobXmlRestorer() {
19502                        @Override
19503                        public void apply(XmlPullParser parser, int userId)
19504                                throws XmlPullParserException, IOException {
19505                            synchronized (mPackages) {
19506                                mSettings.readPreferredActivitiesLPw(parser, userId);
19507                            }
19508                        }
19509                    } );
19510        } catch (Exception e) {
19511            if (DEBUG_BACKUP) {
19512                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19513            }
19514        }
19515    }
19516
19517    /**
19518     * Non-Binder method, support for the backup/restore mechanism: write the
19519     * default browser (etc) settings in its canonical XML format.  Returns the default
19520     * browser XML representation as a byte array, or null if there is none.
19521     */
19522    @Override
19523    public byte[] getDefaultAppsBackup(int userId) {
19524        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19525            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19526        }
19527
19528        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19529        try {
19530            final XmlSerializer serializer = new FastXmlSerializer();
19531            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19532            serializer.startDocument(null, true);
19533            serializer.startTag(null, TAG_DEFAULT_APPS);
19534
19535            synchronized (mPackages) {
19536                mSettings.writeDefaultAppsLPr(serializer, userId);
19537            }
19538
19539            serializer.endTag(null, TAG_DEFAULT_APPS);
19540            serializer.endDocument();
19541            serializer.flush();
19542        } catch (Exception e) {
19543            if (DEBUG_BACKUP) {
19544                Slog.e(TAG, "Unable to write default apps for backup", e);
19545            }
19546            return null;
19547        }
19548
19549        return dataStream.toByteArray();
19550    }
19551
19552    @Override
19553    public void restoreDefaultApps(byte[] backup, int userId) {
19554        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19555            throw new SecurityException("Only the system may call restoreDefaultApps()");
19556        }
19557
19558        try {
19559            final XmlPullParser parser = Xml.newPullParser();
19560            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19561            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19562                    new BlobXmlRestorer() {
19563                        @Override
19564                        public void apply(XmlPullParser parser, int userId)
19565                                throws XmlPullParserException, IOException {
19566                            synchronized (mPackages) {
19567                                mSettings.readDefaultAppsLPw(parser, userId);
19568                            }
19569                        }
19570                    } );
19571        } catch (Exception e) {
19572            if (DEBUG_BACKUP) {
19573                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19574            }
19575        }
19576    }
19577
19578    @Override
19579    public byte[] getIntentFilterVerificationBackup(int userId) {
19580        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19581            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19582        }
19583
19584        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19585        try {
19586            final XmlSerializer serializer = new FastXmlSerializer();
19587            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19588            serializer.startDocument(null, true);
19589            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19590
19591            synchronized (mPackages) {
19592                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19593            }
19594
19595            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19596            serializer.endDocument();
19597            serializer.flush();
19598        } catch (Exception e) {
19599            if (DEBUG_BACKUP) {
19600                Slog.e(TAG, "Unable to write default apps for backup", e);
19601            }
19602            return null;
19603        }
19604
19605        return dataStream.toByteArray();
19606    }
19607
19608    @Override
19609    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19610        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19611            throw new SecurityException("Only the system may call restorePreferredActivities()");
19612        }
19613
19614        try {
19615            final XmlPullParser parser = Xml.newPullParser();
19616            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19617            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19618                    new BlobXmlRestorer() {
19619                        @Override
19620                        public void apply(XmlPullParser parser, int userId)
19621                                throws XmlPullParserException, IOException {
19622                            synchronized (mPackages) {
19623                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19624                                mSettings.writeLPr();
19625                            }
19626                        }
19627                    } );
19628        } catch (Exception e) {
19629            if (DEBUG_BACKUP) {
19630                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19631            }
19632        }
19633    }
19634
19635    @Override
19636    public byte[] getPermissionGrantBackup(int userId) {
19637        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19638            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19639        }
19640
19641        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19642        try {
19643            final XmlSerializer serializer = new FastXmlSerializer();
19644            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19645            serializer.startDocument(null, true);
19646            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19647
19648            synchronized (mPackages) {
19649                serializeRuntimePermissionGrantsLPr(serializer, userId);
19650            }
19651
19652            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19653            serializer.endDocument();
19654            serializer.flush();
19655        } catch (Exception e) {
19656            if (DEBUG_BACKUP) {
19657                Slog.e(TAG, "Unable to write default apps for backup", e);
19658            }
19659            return null;
19660        }
19661
19662        return dataStream.toByteArray();
19663    }
19664
19665    @Override
19666    public void restorePermissionGrants(byte[] backup, int userId) {
19667        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19668            throw new SecurityException("Only the system may call restorePermissionGrants()");
19669        }
19670
19671        try {
19672            final XmlPullParser parser = Xml.newPullParser();
19673            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19674            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19675                    new BlobXmlRestorer() {
19676                        @Override
19677                        public void apply(XmlPullParser parser, int userId)
19678                                throws XmlPullParserException, IOException {
19679                            synchronized (mPackages) {
19680                                processRestoredPermissionGrantsLPr(parser, userId);
19681                            }
19682                        }
19683                    } );
19684        } catch (Exception e) {
19685            if (DEBUG_BACKUP) {
19686                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19687            }
19688        }
19689    }
19690
19691    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19692            throws IOException {
19693        serializer.startTag(null, TAG_ALL_GRANTS);
19694
19695        final int N = mSettings.mPackages.size();
19696        for (int i = 0; i < N; i++) {
19697            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19698            boolean pkgGrantsKnown = false;
19699
19700            PermissionsState packagePerms = ps.getPermissionsState();
19701
19702            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19703                final int grantFlags = state.getFlags();
19704                // only look at grants that are not system/policy fixed
19705                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19706                    final boolean isGranted = state.isGranted();
19707                    // And only back up the user-twiddled state bits
19708                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19709                        final String packageName = mSettings.mPackages.keyAt(i);
19710                        if (!pkgGrantsKnown) {
19711                            serializer.startTag(null, TAG_GRANT);
19712                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19713                            pkgGrantsKnown = true;
19714                        }
19715
19716                        final boolean userSet =
19717                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19718                        final boolean userFixed =
19719                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19720                        final boolean revoke =
19721                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19722
19723                        serializer.startTag(null, TAG_PERMISSION);
19724                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19725                        if (isGranted) {
19726                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19727                        }
19728                        if (userSet) {
19729                            serializer.attribute(null, ATTR_USER_SET, "true");
19730                        }
19731                        if (userFixed) {
19732                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19733                        }
19734                        if (revoke) {
19735                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19736                        }
19737                        serializer.endTag(null, TAG_PERMISSION);
19738                    }
19739                }
19740            }
19741
19742            if (pkgGrantsKnown) {
19743                serializer.endTag(null, TAG_GRANT);
19744            }
19745        }
19746
19747        serializer.endTag(null, TAG_ALL_GRANTS);
19748    }
19749
19750    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19751            throws XmlPullParserException, IOException {
19752        String pkgName = null;
19753        int outerDepth = parser.getDepth();
19754        int type;
19755        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19756                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19757            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19758                continue;
19759            }
19760
19761            final String tagName = parser.getName();
19762            if (tagName.equals(TAG_GRANT)) {
19763                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19764                if (DEBUG_BACKUP) {
19765                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19766                }
19767            } else if (tagName.equals(TAG_PERMISSION)) {
19768
19769                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19770                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19771
19772                int newFlagSet = 0;
19773                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19774                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19775                }
19776                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19777                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19778                }
19779                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19780                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19781                }
19782                if (DEBUG_BACKUP) {
19783                    Slog.v(TAG, "  + Restoring grant:"
19784                            + " pkg=" + pkgName
19785                            + " perm=" + permName
19786                            + " granted=" + isGranted
19787                            + " bits=0x" + Integer.toHexString(newFlagSet));
19788                }
19789                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19790                if (ps != null) {
19791                    // Already installed so we apply the grant immediately
19792                    if (DEBUG_BACKUP) {
19793                        Slog.v(TAG, "        + already installed; applying");
19794                    }
19795                    PermissionsState perms = ps.getPermissionsState();
19796                    BasePermission bp =
19797                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19798                    if (bp != null) {
19799                        if (isGranted) {
19800                            perms.grantRuntimePermission(bp, userId);
19801                        }
19802                        if (newFlagSet != 0) {
19803                            perms.updatePermissionFlags(
19804                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19805                        }
19806                    }
19807                } else {
19808                    // Need to wait for post-restore install to apply the grant
19809                    if (DEBUG_BACKUP) {
19810                        Slog.v(TAG, "        - not yet installed; saving for later");
19811                    }
19812                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19813                            isGranted, newFlagSet, userId);
19814                }
19815            } else {
19816                PackageManagerService.reportSettingsProblem(Log.WARN,
19817                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19818                XmlUtils.skipCurrentTag(parser);
19819            }
19820        }
19821
19822        scheduleWriteSettingsLocked();
19823        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19824    }
19825
19826    @Override
19827    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19828            int sourceUserId, int targetUserId, int flags) {
19829        mContext.enforceCallingOrSelfPermission(
19830                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19831        int callingUid = Binder.getCallingUid();
19832        enforceOwnerRights(ownerPackage, callingUid);
19833        PackageManagerServiceUtils.enforceShellRestriction(
19834                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19835        if (intentFilter.countActions() == 0) {
19836            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19837            return;
19838        }
19839        synchronized (mPackages) {
19840            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19841                    ownerPackage, targetUserId, flags);
19842            CrossProfileIntentResolver resolver =
19843                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19844            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19845            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19846            if (existing != null) {
19847                int size = existing.size();
19848                for (int i = 0; i < size; i++) {
19849                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19850                        return;
19851                    }
19852                }
19853            }
19854            resolver.addFilter(newFilter);
19855            scheduleWritePackageRestrictionsLocked(sourceUserId);
19856        }
19857    }
19858
19859    @Override
19860    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19861        mContext.enforceCallingOrSelfPermission(
19862                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19863        final int callingUid = Binder.getCallingUid();
19864        enforceOwnerRights(ownerPackage, callingUid);
19865        PackageManagerServiceUtils.enforceShellRestriction(
19866                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19867        synchronized (mPackages) {
19868            CrossProfileIntentResolver resolver =
19869                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19870            ArraySet<CrossProfileIntentFilter> set =
19871                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19872            for (CrossProfileIntentFilter filter : set) {
19873                if (filter.getOwnerPackage().equals(ownerPackage)) {
19874                    resolver.removeFilter(filter);
19875                }
19876            }
19877            scheduleWritePackageRestrictionsLocked(sourceUserId);
19878        }
19879    }
19880
19881    // Enforcing that callingUid is owning pkg on userId
19882    private void enforceOwnerRights(String pkg, int callingUid) {
19883        // The system owns everything.
19884        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19885            return;
19886        }
19887        final int callingUserId = UserHandle.getUserId(callingUid);
19888        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19889        if (pi == null) {
19890            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19891                    + callingUserId);
19892        }
19893        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19894            throw new SecurityException("Calling uid " + callingUid
19895                    + " does not own package " + pkg);
19896        }
19897    }
19898
19899    @Override
19900    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19901        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19902            return null;
19903        }
19904        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19905    }
19906
19907    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19908        UserManagerService ums = UserManagerService.getInstance();
19909        if (ums != null) {
19910            final UserInfo parent = ums.getProfileParent(userId);
19911            final int launcherUid = (parent != null) ? parent.id : userId;
19912            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19913            if (launcherComponent != null) {
19914                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19915                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19916                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19917                        .setPackage(launcherComponent.getPackageName());
19918                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19919            }
19920        }
19921    }
19922
19923    /**
19924     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19925     * then reports the most likely home activity or null if there are more than one.
19926     */
19927    private ComponentName getDefaultHomeActivity(int userId) {
19928        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19929        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19930        if (cn != null) {
19931            return cn;
19932        }
19933
19934        // Find the launcher with the highest priority and return that component if there are no
19935        // other home activity with the same priority.
19936        int lastPriority = Integer.MIN_VALUE;
19937        ComponentName lastComponent = null;
19938        final int size = allHomeCandidates.size();
19939        for (int i = 0; i < size; i++) {
19940            final ResolveInfo ri = allHomeCandidates.get(i);
19941            if (ri.priority > lastPriority) {
19942                lastComponent = ri.activityInfo.getComponentName();
19943                lastPriority = ri.priority;
19944            } else if (ri.priority == lastPriority) {
19945                // Two components found with same priority.
19946                lastComponent = null;
19947            }
19948        }
19949        return lastComponent;
19950    }
19951
19952    private Intent getHomeIntent() {
19953        Intent intent = new Intent(Intent.ACTION_MAIN);
19954        intent.addCategory(Intent.CATEGORY_HOME);
19955        intent.addCategory(Intent.CATEGORY_DEFAULT);
19956        return intent;
19957    }
19958
19959    private IntentFilter getHomeFilter() {
19960        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19961        filter.addCategory(Intent.CATEGORY_HOME);
19962        filter.addCategory(Intent.CATEGORY_DEFAULT);
19963        return filter;
19964    }
19965
19966    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19967            int userId) {
19968        Intent intent  = getHomeIntent();
19969        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19970                PackageManager.GET_META_DATA, userId);
19971        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19972                true, false, false, userId);
19973
19974        allHomeCandidates.clear();
19975        if (list != null) {
19976            for (ResolveInfo ri : list) {
19977                allHomeCandidates.add(ri);
19978            }
19979        }
19980        return (preferred == null || preferred.activityInfo == null)
19981                ? null
19982                : new ComponentName(preferred.activityInfo.packageName,
19983                        preferred.activityInfo.name);
19984    }
19985
19986    @Override
19987    public void setHomeActivity(ComponentName comp, int userId) {
19988        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19989            return;
19990        }
19991        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19992        getHomeActivitiesAsUser(homeActivities, userId);
19993
19994        boolean found = false;
19995
19996        final int size = homeActivities.size();
19997        final ComponentName[] set = new ComponentName[size];
19998        for (int i = 0; i < size; i++) {
19999            final ResolveInfo candidate = homeActivities.get(i);
20000            final ActivityInfo info = candidate.activityInfo;
20001            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20002            set[i] = activityName;
20003            if (!found && activityName.equals(comp)) {
20004                found = true;
20005            }
20006        }
20007        if (!found) {
20008            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20009                    + userId);
20010        }
20011        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20012                set, comp, userId);
20013    }
20014
20015    private @Nullable String getSetupWizardPackageName() {
20016        final Intent intent = new Intent(Intent.ACTION_MAIN);
20017        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20018
20019        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20020                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20021                        | MATCH_DISABLED_COMPONENTS,
20022                UserHandle.myUserId());
20023        if (matches.size() == 1) {
20024            return matches.get(0).getComponentInfo().packageName;
20025        } else {
20026            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20027                    + ": matches=" + matches);
20028            return null;
20029        }
20030    }
20031
20032    private @Nullable String getStorageManagerPackageName() {
20033        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20034
20035        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20036                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20037                        | MATCH_DISABLED_COMPONENTS,
20038                UserHandle.myUserId());
20039        if (matches.size() == 1) {
20040            return matches.get(0).getComponentInfo().packageName;
20041        } else {
20042            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20043                    + matches.size() + ": matches=" + matches);
20044            return null;
20045        }
20046    }
20047
20048    @Override
20049    public void setApplicationEnabledSetting(String appPackageName,
20050            int newState, int flags, int userId, String callingPackage) {
20051        if (!sUserManager.exists(userId)) return;
20052        if (callingPackage == null) {
20053            callingPackage = Integer.toString(Binder.getCallingUid());
20054        }
20055        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20056    }
20057
20058    @Override
20059    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20060        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20061        synchronized (mPackages) {
20062            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20063            if (pkgSetting != null) {
20064                pkgSetting.setUpdateAvailable(updateAvailable);
20065            }
20066        }
20067    }
20068
20069    @Override
20070    public void setComponentEnabledSetting(ComponentName componentName,
20071            int newState, int flags, int userId) {
20072        if (!sUserManager.exists(userId)) return;
20073        setEnabledSetting(componentName.getPackageName(),
20074                componentName.getClassName(), newState, flags, userId, null);
20075    }
20076
20077    private void setEnabledSetting(final String packageName, String className, int newState,
20078            final int flags, int userId, String callingPackage) {
20079        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20080              || newState == COMPONENT_ENABLED_STATE_ENABLED
20081              || newState == COMPONENT_ENABLED_STATE_DISABLED
20082              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20083              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20084            throw new IllegalArgumentException("Invalid new component state: "
20085                    + newState);
20086        }
20087        PackageSetting pkgSetting;
20088        final int callingUid = Binder.getCallingUid();
20089        final int permission;
20090        if (callingUid == Process.SYSTEM_UID) {
20091            permission = PackageManager.PERMISSION_GRANTED;
20092        } else {
20093            permission = mContext.checkCallingOrSelfPermission(
20094                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20095        }
20096        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20097                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20098        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20099        boolean sendNow = false;
20100        boolean isApp = (className == null);
20101        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20102        String componentName = isApp ? packageName : className;
20103        int packageUid = -1;
20104        ArrayList<String> components;
20105
20106        // reader
20107        synchronized (mPackages) {
20108            pkgSetting = mSettings.mPackages.get(packageName);
20109            if (pkgSetting == null) {
20110                if (!isCallerInstantApp) {
20111                    if (className == null) {
20112                        throw new IllegalArgumentException("Unknown package: " + packageName);
20113                    }
20114                    throw new IllegalArgumentException(
20115                            "Unknown component: " + packageName + "/" + className);
20116                } else {
20117                    // throw SecurityException to prevent leaking package information
20118                    throw new SecurityException(
20119                            "Attempt to change component state; "
20120                            + "pid=" + Binder.getCallingPid()
20121                            + ", uid=" + callingUid
20122                            + (className == null
20123                                    ? ", package=" + packageName
20124                                    : ", component=" + packageName + "/" + className));
20125                }
20126            }
20127        }
20128
20129        // Limit who can change which apps
20130        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20131            // Don't allow apps that don't have permission to modify other apps
20132            if (!allowedByPermission
20133                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20134                throw new SecurityException(
20135                        "Attempt to change component state; "
20136                        + "pid=" + Binder.getCallingPid()
20137                        + ", uid=" + callingUid
20138                        + (className == null
20139                                ? ", package=" + packageName
20140                                : ", component=" + packageName + "/" + className));
20141            }
20142            // Don't allow changing protected packages.
20143            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20144                throw new SecurityException("Cannot disable a protected package: " + packageName);
20145            }
20146        }
20147
20148        synchronized (mPackages) {
20149            if (callingUid == Process.SHELL_UID
20150                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20151                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20152                // unless it is a test package.
20153                int oldState = pkgSetting.getEnabled(userId);
20154                if (className == null
20155                        &&
20156                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20157                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20158                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20159                        &&
20160                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20161                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20162                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20163                    // ok
20164                } else {
20165                    throw new SecurityException(
20166                            "Shell cannot change component state for " + packageName + "/"
20167                                    + className + " to " + newState);
20168                }
20169            }
20170        }
20171        if (className == null) {
20172            // We're dealing with an application/package level state change
20173            synchronized (mPackages) {
20174                if (pkgSetting.getEnabled(userId) == newState) {
20175                    // Nothing to do
20176                    return;
20177                }
20178            }
20179            // If we're enabling a system stub, there's a little more work to do.
20180            // Prior to enabling the package, we need to decompress the APK(s) to the
20181            // data partition and then replace the version on the system partition.
20182            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20183            final boolean isSystemStub = deletedPkg.isStub
20184                    && deletedPkg.isSystem();
20185            if (isSystemStub
20186                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20187                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20188                final File codePath = decompressPackage(deletedPkg);
20189                if (codePath == null) {
20190                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20191                    return;
20192                }
20193                // TODO remove direct parsing of the package object during internal cleanup
20194                // of scan package
20195                // We need to call parse directly here for no other reason than we need
20196                // the new package in order to disable the old one [we use the information
20197                // for some internal optimization to optionally create a new package setting
20198                // object on replace]. However, we can't get the package from the scan
20199                // because the scan modifies live structures and we need to remove the
20200                // old [system] package from the system before a scan can be attempted.
20201                // Once scan is indempotent we can remove this parse and use the package
20202                // object we scanned, prior to adding it to package settings.
20203                final PackageParser pp = new PackageParser();
20204                pp.setSeparateProcesses(mSeparateProcesses);
20205                pp.setDisplayMetrics(mMetrics);
20206                pp.setCallback(mPackageParserCallback);
20207                final PackageParser.Package tmpPkg;
20208                try {
20209                    final @ParseFlags int parseFlags = mDefParseFlags
20210                            | PackageParser.PARSE_MUST_BE_APK
20211                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20212                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20213                } catch (PackageParserException e) {
20214                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20215                    return;
20216                }
20217                synchronized (mInstallLock) {
20218                    // Disable the stub and remove any package entries
20219                    removePackageLI(deletedPkg, true);
20220                    synchronized (mPackages) {
20221                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20222                    }
20223                    final PackageParser.Package pkg;
20224                    try (PackageFreezer freezer =
20225                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20226                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20227                                | PackageParser.PARSE_ENFORCE_CODE;
20228                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20229                                0 /*currentTime*/, null /*user*/);
20230                        prepareAppDataAfterInstallLIF(pkg);
20231                        synchronized (mPackages) {
20232                            try {
20233                                updateSharedLibrariesLPr(pkg, null);
20234                            } catch (PackageManagerException e) {
20235                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20236                            }
20237                            mPermissionManager.updatePermissions(
20238                                    pkg.packageName, pkg, true, mPackages.values(),
20239                                    mPermissionCallback);
20240                            mSettings.writeLPr();
20241                        }
20242                    } catch (PackageManagerException e) {
20243                        // Whoops! Something went wrong; try to roll back to the stub
20244                        Slog.w(TAG, "Failed to install compressed system package:"
20245                                + pkgSetting.name, e);
20246                        // Remove the failed install
20247                        removeCodePathLI(codePath);
20248
20249                        // Install the system package
20250                        try (PackageFreezer freezer =
20251                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20252                            synchronized (mPackages) {
20253                                // NOTE: The system package always needs to be enabled; even
20254                                // if it's for a compressed stub. If we don't, installing the
20255                                // system package fails during scan [scanning checks the disabled
20256                                // packages]. We will reverse this later, after we've "installed"
20257                                // the stub.
20258                                // This leaves us in a fragile state; the stub should never be
20259                                // enabled, so, cross your fingers and hope nothing goes wrong
20260                                // until we can disable the package later.
20261                                enableSystemPackageLPw(deletedPkg);
20262                            }
20263                            installPackageFromSystemLIF(deletedPkg.codePath,
20264                                    false /*isPrivileged*/, null /*allUserHandles*/,
20265                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20266                                    true /*writeSettings*/);
20267                        } catch (PackageManagerException pme) {
20268                            Slog.w(TAG, "Failed to restore system package:"
20269                                    + deletedPkg.packageName, pme);
20270                        } finally {
20271                            synchronized (mPackages) {
20272                                mSettings.disableSystemPackageLPw(
20273                                        deletedPkg.packageName, true /*replaced*/);
20274                                mSettings.writeLPr();
20275                            }
20276                        }
20277                        return;
20278                    }
20279                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20280                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20281                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20282                    mDexManager.notifyPackageUpdated(pkg.packageName,
20283                            pkg.baseCodePath, pkg.splitCodePaths);
20284                }
20285            }
20286            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20287                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20288                // Don't care about who enables an app.
20289                callingPackage = null;
20290            }
20291            synchronized (mPackages) {
20292                pkgSetting.setEnabled(newState, userId, callingPackage);
20293            }
20294        } else {
20295            synchronized (mPackages) {
20296                // We're dealing with a component level state change
20297                // First, verify that this is a valid class name.
20298                PackageParser.Package pkg = pkgSetting.pkg;
20299                if (pkg == null || !pkg.hasComponentClassName(className)) {
20300                    if (pkg != null &&
20301                            pkg.applicationInfo.targetSdkVersion >=
20302                                    Build.VERSION_CODES.JELLY_BEAN) {
20303                        throw new IllegalArgumentException("Component class " + className
20304                                + " does not exist in " + packageName);
20305                    } else {
20306                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20307                                + className + " does not exist in " + packageName);
20308                    }
20309                }
20310                switch (newState) {
20311                    case COMPONENT_ENABLED_STATE_ENABLED:
20312                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20313                            return;
20314                        }
20315                        break;
20316                    case COMPONENT_ENABLED_STATE_DISABLED:
20317                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20318                            return;
20319                        }
20320                        break;
20321                    case COMPONENT_ENABLED_STATE_DEFAULT:
20322                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20323                            return;
20324                        }
20325                        break;
20326                    default:
20327                        Slog.e(TAG, "Invalid new component state: " + newState);
20328                        return;
20329                }
20330            }
20331        }
20332        synchronized (mPackages) {
20333            scheduleWritePackageRestrictionsLocked(userId);
20334            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20335            final long callingId = Binder.clearCallingIdentity();
20336            try {
20337                updateInstantAppInstallerLocked(packageName);
20338            } finally {
20339                Binder.restoreCallingIdentity(callingId);
20340            }
20341            components = mPendingBroadcasts.get(userId, packageName);
20342            final boolean newPackage = components == null;
20343            if (newPackage) {
20344                components = new ArrayList<String>();
20345            }
20346            if (!components.contains(componentName)) {
20347                components.add(componentName);
20348            }
20349            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20350                sendNow = true;
20351                // Purge entry from pending broadcast list if another one exists already
20352                // since we are sending one right away.
20353                mPendingBroadcasts.remove(userId, packageName);
20354            } else {
20355                if (newPackage) {
20356                    mPendingBroadcasts.put(userId, packageName, components);
20357                }
20358                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20359                    // Schedule a message
20360                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20361                }
20362            }
20363        }
20364
20365        long callingId = Binder.clearCallingIdentity();
20366        try {
20367            if (sendNow) {
20368                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20369                sendPackageChangedBroadcast(packageName,
20370                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20371            }
20372        } finally {
20373            Binder.restoreCallingIdentity(callingId);
20374        }
20375    }
20376
20377    @Override
20378    public void flushPackageRestrictionsAsUser(int userId) {
20379        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20380            return;
20381        }
20382        if (!sUserManager.exists(userId)) {
20383            return;
20384        }
20385        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20386                false /* checkShell */, "flushPackageRestrictions");
20387        synchronized (mPackages) {
20388            mSettings.writePackageRestrictionsLPr(userId);
20389            mDirtyUsers.remove(userId);
20390            if (mDirtyUsers.isEmpty()) {
20391                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20392            }
20393        }
20394    }
20395
20396    private void sendPackageChangedBroadcast(String packageName,
20397            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20398        if (DEBUG_INSTALL)
20399            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20400                    + componentNames);
20401        Bundle extras = new Bundle(4);
20402        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20403        String nameList[] = new String[componentNames.size()];
20404        componentNames.toArray(nameList);
20405        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20406        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20407        extras.putInt(Intent.EXTRA_UID, packageUid);
20408        // If this is not reporting a change of the overall package, then only send it
20409        // to registered receivers.  We don't want to launch a swath of apps for every
20410        // little component state change.
20411        final int flags = !componentNames.contains(packageName)
20412                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20413        final int userId = UserHandle.getUserId(packageUid);
20414        final boolean isInstantApp = isInstantApp(packageName, userId);
20415        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20416        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20417        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20418                userIds, instantUserIds);
20419    }
20420
20421    @Override
20422    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20423        if (!sUserManager.exists(userId)) return;
20424        final int callingUid = Binder.getCallingUid();
20425        if (getInstantAppPackageName(callingUid) != null) {
20426            return;
20427        }
20428        final int permission = mContext.checkCallingOrSelfPermission(
20429                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20430        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20431        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20432                true /* requireFullPermission */, true /* checkShell */, "stop package");
20433        // writer
20434        synchronized (mPackages) {
20435            final PackageSetting ps = mSettings.mPackages.get(packageName);
20436            if (!filterAppAccessLPr(ps, callingUid, userId)
20437                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20438                            allowedByPermission, callingUid, userId)) {
20439                scheduleWritePackageRestrictionsLocked(userId);
20440            }
20441        }
20442    }
20443
20444    @Override
20445    public String getInstallerPackageName(String packageName) {
20446        final int callingUid = Binder.getCallingUid();
20447        if (getInstantAppPackageName(callingUid) != null) {
20448            return null;
20449        }
20450        // reader
20451        synchronized (mPackages) {
20452            final PackageSetting ps = mSettings.mPackages.get(packageName);
20453            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20454                return null;
20455            }
20456            return mSettings.getInstallerPackageNameLPr(packageName);
20457        }
20458    }
20459
20460    public boolean isOrphaned(String packageName) {
20461        // reader
20462        synchronized (mPackages) {
20463            return mSettings.isOrphaned(packageName);
20464        }
20465    }
20466
20467    @Override
20468    public int getApplicationEnabledSetting(String packageName, int userId) {
20469        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20470        int callingUid = Binder.getCallingUid();
20471        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20472                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20473        // reader
20474        synchronized (mPackages) {
20475            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20476                return COMPONENT_ENABLED_STATE_DISABLED;
20477            }
20478            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20479        }
20480    }
20481
20482    @Override
20483    public int getComponentEnabledSetting(ComponentName component, int userId) {
20484        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20485        int callingUid = Binder.getCallingUid();
20486        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20487                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20488        synchronized (mPackages) {
20489            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20490                    component, TYPE_UNKNOWN, userId)) {
20491                return COMPONENT_ENABLED_STATE_DISABLED;
20492            }
20493            return mSettings.getComponentEnabledSettingLPr(component, userId);
20494        }
20495    }
20496
20497    @Override
20498    public void enterSafeMode() {
20499        enforceSystemOrRoot("Only the system can request entering safe mode");
20500
20501        if (!mSystemReady) {
20502            mSafeMode = true;
20503        }
20504    }
20505
20506    @Override
20507    public void systemReady() {
20508        enforceSystemOrRoot("Only the system can claim the system is ready");
20509
20510        mSystemReady = true;
20511        final ContentResolver resolver = mContext.getContentResolver();
20512        ContentObserver co = new ContentObserver(mHandler) {
20513            @Override
20514            public void onChange(boolean selfChange) {
20515                mEphemeralAppsDisabled =
20516                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20517                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20518            }
20519        };
20520        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20521                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20522                false, co, UserHandle.USER_SYSTEM);
20523        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20524                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20525        co.onChange(true);
20526
20527        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20528        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20529        // it is done.
20530        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20531            @Override
20532            public void onChange(boolean selfChange) {
20533                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20534                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20535                        oobEnabled == 1 ? "true" : "false");
20536            }
20537        };
20538        mContext.getContentResolver().registerContentObserver(
20539                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20540                UserHandle.USER_SYSTEM);
20541        // At boot, restore the value from the setting, which persists across reboot.
20542        privAppOobObserver.onChange(true);
20543
20544        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20545        // disabled after already being started.
20546        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20547                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20548
20549        // Read the compatibilty setting when the system is ready.
20550        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20551                mContext.getContentResolver(),
20552                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20553        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20554        if (DEBUG_SETTINGS) {
20555            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20556        }
20557
20558        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20559
20560        synchronized (mPackages) {
20561            // Verify that all of the preferred activity components actually
20562            // exist.  It is possible for applications to be updated and at
20563            // that point remove a previously declared activity component that
20564            // had been set as a preferred activity.  We try to clean this up
20565            // the next time we encounter that preferred activity, but it is
20566            // possible for the user flow to never be able to return to that
20567            // situation so here we do a sanity check to make sure we haven't
20568            // left any junk around.
20569            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20570            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20571                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20572                removed.clear();
20573                for (PreferredActivity pa : pir.filterSet()) {
20574                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20575                        removed.add(pa);
20576                    }
20577                }
20578                if (removed.size() > 0) {
20579                    for (int r=0; r<removed.size(); r++) {
20580                        PreferredActivity pa = removed.get(r);
20581                        Slog.w(TAG, "Removing dangling preferred activity: "
20582                                + pa.mPref.mComponent);
20583                        pir.removeFilter(pa);
20584                    }
20585                    mSettings.writePackageRestrictionsLPr(
20586                            mSettings.mPreferredActivities.keyAt(i));
20587                }
20588            }
20589
20590            for (int userId : UserManagerService.getInstance().getUserIds()) {
20591                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20592                    grantPermissionsUserIds = ArrayUtils.appendInt(
20593                            grantPermissionsUserIds, userId);
20594                }
20595            }
20596        }
20597        sUserManager.systemReady();
20598        // If we upgraded grant all default permissions before kicking off.
20599        for (int userId : grantPermissionsUserIds) {
20600            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20601        }
20602
20603        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20604            // If we did not grant default permissions, we preload from this the
20605            // default permission exceptions lazily to ensure we don't hit the
20606            // disk on a new user creation.
20607            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20608        }
20609
20610        // Now that we've scanned all packages, and granted any default
20611        // permissions, ensure permissions are updated. Beware of dragons if you
20612        // try optimizing this.
20613        synchronized (mPackages) {
20614            mPermissionManager.updateAllPermissions(
20615                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20616                    mPermissionCallback);
20617        }
20618
20619        // Kick off any messages waiting for system ready
20620        if (mPostSystemReadyMessages != null) {
20621            for (Message msg : mPostSystemReadyMessages) {
20622                msg.sendToTarget();
20623            }
20624            mPostSystemReadyMessages = null;
20625        }
20626
20627        // Watch for external volumes that come and go over time
20628        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20629        storage.registerListener(mStorageListener);
20630
20631        mInstallerService.systemReady();
20632        mPackageDexOptimizer.systemReady();
20633
20634        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20635                StorageManagerInternal.class);
20636        StorageManagerInternal.addExternalStoragePolicy(
20637                new StorageManagerInternal.ExternalStorageMountPolicy() {
20638            @Override
20639            public int getMountMode(int uid, String packageName) {
20640                if (Process.isIsolated(uid)) {
20641                    return Zygote.MOUNT_EXTERNAL_NONE;
20642                }
20643                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20644                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20645                }
20646                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20647                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20648                }
20649                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20650                    return Zygote.MOUNT_EXTERNAL_READ;
20651                }
20652                return Zygote.MOUNT_EXTERNAL_WRITE;
20653            }
20654
20655            @Override
20656            public boolean hasExternalStorage(int uid, String packageName) {
20657                return true;
20658            }
20659        });
20660
20661        // Now that we're mostly running, clean up stale users and apps
20662        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20663        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20664
20665        mPermissionManager.systemReady();
20666    }
20667
20668    public void waitForAppDataPrepared() {
20669        if (mPrepareAppDataFuture == null) {
20670            return;
20671        }
20672        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20673        mPrepareAppDataFuture = null;
20674    }
20675
20676    @Override
20677    public boolean isSafeMode() {
20678        // allow instant applications
20679        return mSafeMode;
20680    }
20681
20682    @Override
20683    public boolean hasSystemUidErrors() {
20684        // allow instant applications
20685        return mHasSystemUidErrors;
20686    }
20687
20688    static String arrayToString(int[] array) {
20689        StringBuffer buf = new StringBuffer(128);
20690        buf.append('[');
20691        if (array != null) {
20692            for (int i=0; i<array.length; i++) {
20693                if (i > 0) buf.append(", ");
20694                buf.append(array[i]);
20695            }
20696        }
20697        buf.append(']');
20698        return buf.toString();
20699    }
20700
20701    @Override
20702    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20703            FileDescriptor err, String[] args, ShellCallback callback,
20704            ResultReceiver resultReceiver) {
20705        (new PackageManagerShellCommand(this)).exec(
20706                this, in, out, err, args, callback, resultReceiver);
20707    }
20708
20709    @Override
20710    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20711        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20712
20713        DumpState dumpState = new DumpState();
20714        boolean fullPreferred = false;
20715        boolean checkin = false;
20716
20717        String packageName = null;
20718        ArraySet<String> permissionNames = null;
20719
20720        int opti = 0;
20721        while (opti < args.length) {
20722            String opt = args[opti];
20723            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20724                break;
20725            }
20726            opti++;
20727
20728            if ("-a".equals(opt)) {
20729                // Right now we only know how to print all.
20730            } else if ("-h".equals(opt)) {
20731                pw.println("Package manager dump options:");
20732                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20733                pw.println("    --checkin: dump for a checkin");
20734                pw.println("    -f: print details of intent filters");
20735                pw.println("    -h: print this help");
20736                pw.println("  cmd may be one of:");
20737                pw.println("    l[ibraries]: list known shared libraries");
20738                pw.println("    f[eatures]: list device features");
20739                pw.println("    k[eysets]: print known keysets");
20740                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20741                pw.println("    perm[issions]: dump permissions");
20742                pw.println("    permission [name ...]: dump declaration and use of given permission");
20743                pw.println("    pref[erred]: print preferred package settings");
20744                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20745                pw.println("    prov[iders]: dump content providers");
20746                pw.println("    p[ackages]: dump installed packages");
20747                pw.println("    s[hared-users]: dump shared user IDs");
20748                pw.println("    m[essages]: print collected runtime messages");
20749                pw.println("    v[erifiers]: print package verifier info");
20750                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20751                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20752                pw.println("    version: print database version info");
20753                pw.println("    write: write current settings now");
20754                pw.println("    installs: details about install sessions");
20755                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20756                pw.println("    dexopt: dump dexopt state");
20757                pw.println("    compiler-stats: dump compiler statistics");
20758                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20759                pw.println("    service-permissions: dump permissions required by services");
20760                pw.println("    <package.name>: info about given package");
20761                return;
20762            } else if ("--checkin".equals(opt)) {
20763                checkin = true;
20764            } else if ("-f".equals(opt)) {
20765                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20766            } else if ("--proto".equals(opt)) {
20767                dumpProto(fd);
20768                return;
20769            } else {
20770                pw.println("Unknown argument: " + opt + "; use -h for help");
20771            }
20772        }
20773
20774        // Is the caller requesting to dump a particular piece of data?
20775        if (opti < args.length) {
20776            String cmd = args[opti];
20777            opti++;
20778            // Is this a package name?
20779            if ("android".equals(cmd) || cmd.contains(".")) {
20780                packageName = cmd;
20781                // When dumping a single package, we always dump all of its
20782                // filter information since the amount of data will be reasonable.
20783                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20784            } else if ("check-permission".equals(cmd)) {
20785                if (opti >= args.length) {
20786                    pw.println("Error: check-permission missing permission argument");
20787                    return;
20788                }
20789                String perm = args[opti];
20790                opti++;
20791                if (opti >= args.length) {
20792                    pw.println("Error: check-permission missing package argument");
20793                    return;
20794                }
20795
20796                String pkg = args[opti];
20797                opti++;
20798                int user = UserHandle.getUserId(Binder.getCallingUid());
20799                if (opti < args.length) {
20800                    try {
20801                        user = Integer.parseInt(args[opti]);
20802                    } catch (NumberFormatException e) {
20803                        pw.println("Error: check-permission user argument is not a number: "
20804                                + args[opti]);
20805                        return;
20806                    }
20807                }
20808
20809                // Normalize package name to handle renamed packages and static libs
20810                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20811
20812                pw.println(checkPermission(perm, pkg, user));
20813                return;
20814            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20815                dumpState.setDump(DumpState.DUMP_LIBS);
20816            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20817                dumpState.setDump(DumpState.DUMP_FEATURES);
20818            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20819                if (opti >= args.length) {
20820                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20821                            | DumpState.DUMP_SERVICE_RESOLVERS
20822                            | DumpState.DUMP_RECEIVER_RESOLVERS
20823                            | DumpState.DUMP_CONTENT_RESOLVERS);
20824                } else {
20825                    while (opti < args.length) {
20826                        String name = args[opti];
20827                        if ("a".equals(name) || "activity".equals(name)) {
20828                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20829                        } else if ("s".equals(name) || "service".equals(name)) {
20830                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20831                        } else if ("r".equals(name) || "receiver".equals(name)) {
20832                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20833                        } else if ("c".equals(name) || "content".equals(name)) {
20834                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20835                        } else {
20836                            pw.println("Error: unknown resolver table type: " + name);
20837                            return;
20838                        }
20839                        opti++;
20840                    }
20841                }
20842            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20843                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20844            } else if ("permission".equals(cmd)) {
20845                if (opti >= args.length) {
20846                    pw.println("Error: permission requires permission name");
20847                    return;
20848                }
20849                permissionNames = new ArraySet<>();
20850                while (opti < args.length) {
20851                    permissionNames.add(args[opti]);
20852                    opti++;
20853                }
20854                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20855                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20856            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20857                dumpState.setDump(DumpState.DUMP_PREFERRED);
20858            } else if ("preferred-xml".equals(cmd)) {
20859                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20860                if (opti < args.length && "--full".equals(args[opti])) {
20861                    fullPreferred = true;
20862                    opti++;
20863                }
20864            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20865                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20866            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20867                dumpState.setDump(DumpState.DUMP_PACKAGES);
20868            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20869                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20870            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20871                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20872            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20873                dumpState.setDump(DumpState.DUMP_MESSAGES);
20874            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20875                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20876            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20877                    || "intent-filter-verifiers".equals(cmd)) {
20878                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20879            } else if ("version".equals(cmd)) {
20880                dumpState.setDump(DumpState.DUMP_VERSION);
20881            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20882                dumpState.setDump(DumpState.DUMP_KEYSETS);
20883            } else if ("installs".equals(cmd)) {
20884                dumpState.setDump(DumpState.DUMP_INSTALLS);
20885            } else if ("frozen".equals(cmd)) {
20886                dumpState.setDump(DumpState.DUMP_FROZEN);
20887            } else if ("volumes".equals(cmd)) {
20888                dumpState.setDump(DumpState.DUMP_VOLUMES);
20889            } else if ("dexopt".equals(cmd)) {
20890                dumpState.setDump(DumpState.DUMP_DEXOPT);
20891            } else if ("compiler-stats".equals(cmd)) {
20892                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20893            } else if ("changes".equals(cmd)) {
20894                dumpState.setDump(DumpState.DUMP_CHANGES);
20895            } else if ("service-permissions".equals(cmd)) {
20896                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
20897            } else if ("write".equals(cmd)) {
20898                synchronized (mPackages) {
20899                    mSettings.writeLPr();
20900                    pw.println("Settings written.");
20901                    return;
20902                }
20903            }
20904        }
20905
20906        if (checkin) {
20907            pw.println("vers,1");
20908        }
20909
20910        // reader
20911        synchronized (mPackages) {
20912            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20913                if (!checkin) {
20914                    if (dumpState.onTitlePrinted())
20915                        pw.println();
20916                    pw.println("Database versions:");
20917                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20918                }
20919            }
20920
20921            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20922                if (!checkin) {
20923                    if (dumpState.onTitlePrinted())
20924                        pw.println();
20925                    pw.println("Verifiers:");
20926                    pw.print("  Required: ");
20927                    pw.print(mRequiredVerifierPackage);
20928                    pw.print(" (uid=");
20929                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20930                            UserHandle.USER_SYSTEM));
20931                    pw.println(")");
20932                } else if (mRequiredVerifierPackage != null) {
20933                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20934                    pw.print(",");
20935                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20936                            UserHandle.USER_SYSTEM));
20937                }
20938            }
20939
20940            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20941                    packageName == null) {
20942                if (mIntentFilterVerifierComponent != null) {
20943                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20944                    if (!checkin) {
20945                        if (dumpState.onTitlePrinted())
20946                            pw.println();
20947                        pw.println("Intent Filter Verifier:");
20948                        pw.print("  Using: ");
20949                        pw.print(verifierPackageName);
20950                        pw.print(" (uid=");
20951                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20952                                UserHandle.USER_SYSTEM));
20953                        pw.println(")");
20954                    } else if (verifierPackageName != null) {
20955                        pw.print("ifv,"); pw.print(verifierPackageName);
20956                        pw.print(",");
20957                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20958                                UserHandle.USER_SYSTEM));
20959                    }
20960                } else {
20961                    pw.println();
20962                    pw.println("No Intent Filter Verifier available!");
20963                }
20964            }
20965
20966            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20967                boolean printedHeader = false;
20968                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20969                while (it.hasNext()) {
20970                    String libName = it.next();
20971                    LongSparseArray<SharedLibraryEntry> versionedLib
20972                            = mSharedLibraries.get(libName);
20973                    if (versionedLib == null) {
20974                        continue;
20975                    }
20976                    final int versionCount = versionedLib.size();
20977                    for (int i = 0; i < versionCount; i++) {
20978                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20979                        if (!checkin) {
20980                            if (!printedHeader) {
20981                                if (dumpState.onTitlePrinted())
20982                                    pw.println();
20983                                pw.println("Libraries:");
20984                                printedHeader = true;
20985                            }
20986                            pw.print("  ");
20987                        } else {
20988                            pw.print("lib,");
20989                        }
20990                        pw.print(libEntry.info.getName());
20991                        if (libEntry.info.isStatic()) {
20992                            pw.print(" version=" + libEntry.info.getLongVersion());
20993                        }
20994                        if (!checkin) {
20995                            pw.print(" -> ");
20996                        }
20997                        if (libEntry.path != null) {
20998                            pw.print(" (jar) ");
20999                            pw.print(libEntry.path);
21000                        } else {
21001                            pw.print(" (apk) ");
21002                            pw.print(libEntry.apk);
21003                        }
21004                        pw.println();
21005                    }
21006                }
21007            }
21008
21009            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21010                if (dumpState.onTitlePrinted())
21011                    pw.println();
21012                if (!checkin) {
21013                    pw.println("Features:");
21014                }
21015
21016                synchronized (mAvailableFeatures) {
21017                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21018                        if (checkin) {
21019                            pw.print("feat,");
21020                            pw.print(feat.name);
21021                            pw.print(",");
21022                            pw.println(feat.version);
21023                        } else {
21024                            pw.print("  ");
21025                            pw.print(feat.name);
21026                            if (feat.version > 0) {
21027                                pw.print(" version=");
21028                                pw.print(feat.version);
21029                            }
21030                            pw.println();
21031                        }
21032                    }
21033                }
21034            }
21035
21036            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21037                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21038                        : "Activity Resolver Table:", "  ", packageName,
21039                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21040                    dumpState.setTitlePrinted(true);
21041                }
21042            }
21043            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21044                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21045                        : "Receiver Resolver Table:", "  ", packageName,
21046                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21047                    dumpState.setTitlePrinted(true);
21048                }
21049            }
21050            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21051                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21052                        : "Service Resolver Table:", "  ", packageName,
21053                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21054                    dumpState.setTitlePrinted(true);
21055                }
21056            }
21057            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21058                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21059                        : "Provider Resolver Table:", "  ", packageName,
21060                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21061                    dumpState.setTitlePrinted(true);
21062                }
21063            }
21064
21065            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21066                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21067                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21068                    int user = mSettings.mPreferredActivities.keyAt(i);
21069                    if (pir.dump(pw,
21070                            dumpState.getTitlePrinted()
21071                                ? "\nPreferred Activities User " + user + ":"
21072                                : "Preferred Activities User " + user + ":", "  ",
21073                            packageName, true, false)) {
21074                        dumpState.setTitlePrinted(true);
21075                    }
21076                }
21077            }
21078
21079            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21080                pw.flush();
21081                FileOutputStream fout = new FileOutputStream(fd);
21082                BufferedOutputStream str = new BufferedOutputStream(fout);
21083                XmlSerializer serializer = new FastXmlSerializer();
21084                try {
21085                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21086                    serializer.startDocument(null, true);
21087                    serializer.setFeature(
21088                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21089                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21090                    serializer.endDocument();
21091                    serializer.flush();
21092                } catch (IllegalArgumentException e) {
21093                    pw.println("Failed writing: " + e);
21094                } catch (IllegalStateException e) {
21095                    pw.println("Failed writing: " + e);
21096                } catch (IOException e) {
21097                    pw.println("Failed writing: " + e);
21098                }
21099            }
21100
21101            if (!checkin
21102                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21103                    && packageName == null) {
21104                pw.println();
21105                int count = mSettings.mPackages.size();
21106                if (count == 0) {
21107                    pw.println("No applications!");
21108                    pw.println();
21109                } else {
21110                    final String prefix = "  ";
21111                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21112                    if (allPackageSettings.size() == 0) {
21113                        pw.println("No domain preferred apps!");
21114                        pw.println();
21115                    } else {
21116                        pw.println("App verification status:");
21117                        pw.println();
21118                        count = 0;
21119                        for (PackageSetting ps : allPackageSettings) {
21120                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21121                            if (ivi == null || ivi.getPackageName() == null) continue;
21122                            pw.println(prefix + "Package: " + ivi.getPackageName());
21123                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21124                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21125                            pw.println();
21126                            count++;
21127                        }
21128                        if (count == 0) {
21129                            pw.println(prefix + "No app verification established.");
21130                            pw.println();
21131                        }
21132                        for (int userId : sUserManager.getUserIds()) {
21133                            pw.println("App linkages for user " + userId + ":");
21134                            pw.println();
21135                            count = 0;
21136                            for (PackageSetting ps : allPackageSettings) {
21137                                final long status = ps.getDomainVerificationStatusForUser(userId);
21138                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21139                                        && !DEBUG_DOMAIN_VERIFICATION) {
21140                                    continue;
21141                                }
21142                                pw.println(prefix + "Package: " + ps.name);
21143                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21144                                String statusStr = IntentFilterVerificationInfo.
21145                                        getStatusStringFromValue(status);
21146                                pw.println(prefix + "Status:  " + statusStr);
21147                                pw.println();
21148                                count++;
21149                            }
21150                            if (count == 0) {
21151                                pw.println(prefix + "No configured app linkages.");
21152                                pw.println();
21153                            }
21154                        }
21155                    }
21156                }
21157            }
21158
21159            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21160                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21161            }
21162
21163            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21164                boolean printedSomething = false;
21165                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21166                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21167                        continue;
21168                    }
21169                    if (!printedSomething) {
21170                        if (dumpState.onTitlePrinted())
21171                            pw.println();
21172                        pw.println("Registered ContentProviders:");
21173                        printedSomething = true;
21174                    }
21175                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21176                    pw.print("    "); pw.println(p.toString());
21177                }
21178                printedSomething = false;
21179                for (Map.Entry<String, PackageParser.Provider> entry :
21180                        mProvidersByAuthority.entrySet()) {
21181                    PackageParser.Provider p = entry.getValue();
21182                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21183                        continue;
21184                    }
21185                    if (!printedSomething) {
21186                        if (dumpState.onTitlePrinted())
21187                            pw.println();
21188                        pw.println("ContentProvider Authorities:");
21189                        printedSomething = true;
21190                    }
21191                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21192                    pw.print("    "); pw.println(p.toString());
21193                    if (p.info != null && p.info.applicationInfo != null) {
21194                        final String appInfo = p.info.applicationInfo.toString();
21195                        pw.print("      applicationInfo="); pw.println(appInfo);
21196                    }
21197                }
21198            }
21199
21200            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21201                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21202            }
21203
21204            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21205                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21206            }
21207
21208            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21209                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21210            }
21211
21212            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21213                if (dumpState.onTitlePrinted()) pw.println();
21214                pw.println("Package Changes:");
21215                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21216                final int K = mChangedPackages.size();
21217                for (int i = 0; i < K; i++) {
21218                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21219                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21220                    final int N = changes.size();
21221                    if (N == 0) {
21222                        pw.print("    "); pw.println("No packages changed");
21223                    } else {
21224                        for (int j = 0; j < N; j++) {
21225                            final String pkgName = changes.valueAt(j);
21226                            final int sequenceNumber = changes.keyAt(j);
21227                            pw.print("    ");
21228                            pw.print("seq=");
21229                            pw.print(sequenceNumber);
21230                            pw.print(", package=");
21231                            pw.println(pkgName);
21232                        }
21233                    }
21234                }
21235            }
21236
21237            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21238                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21239            }
21240
21241            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21242                // XXX should handle packageName != null by dumping only install data that
21243                // the given package is involved with.
21244                if (dumpState.onTitlePrinted()) pw.println();
21245
21246                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21247                ipw.println();
21248                ipw.println("Frozen packages:");
21249                ipw.increaseIndent();
21250                if (mFrozenPackages.size() == 0) {
21251                    ipw.println("(none)");
21252                } else {
21253                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21254                        ipw.println(mFrozenPackages.valueAt(i));
21255                    }
21256                }
21257                ipw.decreaseIndent();
21258            }
21259
21260            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21261                if (dumpState.onTitlePrinted()) pw.println();
21262
21263                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21264                ipw.println();
21265                ipw.println("Loaded volumes:");
21266                ipw.increaseIndent();
21267                if (mLoadedVolumes.size() == 0) {
21268                    ipw.println("(none)");
21269                } else {
21270                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21271                        ipw.println(mLoadedVolumes.valueAt(i));
21272                    }
21273                }
21274                ipw.decreaseIndent();
21275            }
21276
21277            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21278                    && packageName == null) {
21279                if (dumpState.onTitlePrinted()) pw.println();
21280                pw.println("Service permissions:");
21281
21282                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21283                while (filterIterator.hasNext()) {
21284                    final ServiceIntentInfo info = filterIterator.next();
21285                    final ServiceInfo serviceInfo = info.service.info;
21286                    final String permission = serviceInfo.permission;
21287                    if (permission != null) {
21288                        pw.print("    ");
21289                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21290                        pw.print(": ");
21291                        pw.println(permission);
21292                    }
21293                }
21294            }
21295
21296            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21297                if (dumpState.onTitlePrinted()) pw.println();
21298                dumpDexoptStateLPr(pw, packageName);
21299            }
21300
21301            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21302                if (dumpState.onTitlePrinted()) pw.println();
21303                dumpCompilerStatsLPr(pw, packageName);
21304            }
21305
21306            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21307                if (dumpState.onTitlePrinted()) pw.println();
21308                mSettings.dumpReadMessagesLPr(pw, dumpState);
21309
21310                pw.println();
21311                pw.println("Package warning messages:");
21312                dumpCriticalInfo(pw, null);
21313            }
21314
21315            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21316                dumpCriticalInfo(pw, "msg,");
21317            }
21318        }
21319
21320        // PackageInstaller should be called outside of mPackages lock
21321        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21322            // XXX should handle packageName != null by dumping only install data that
21323            // the given package is involved with.
21324            if (dumpState.onTitlePrinted()) pw.println();
21325            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21326        }
21327    }
21328
21329    private void dumpProto(FileDescriptor fd) {
21330        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21331
21332        synchronized (mPackages) {
21333            final long requiredVerifierPackageToken =
21334                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21335            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21336            proto.write(
21337                    PackageServiceDumpProto.PackageShortProto.UID,
21338                    getPackageUid(
21339                            mRequiredVerifierPackage,
21340                            MATCH_DEBUG_TRIAGED_MISSING,
21341                            UserHandle.USER_SYSTEM));
21342            proto.end(requiredVerifierPackageToken);
21343
21344            if (mIntentFilterVerifierComponent != null) {
21345                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21346                final long verifierPackageToken =
21347                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21348                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21349                proto.write(
21350                        PackageServiceDumpProto.PackageShortProto.UID,
21351                        getPackageUid(
21352                                verifierPackageName,
21353                                MATCH_DEBUG_TRIAGED_MISSING,
21354                                UserHandle.USER_SYSTEM));
21355                proto.end(verifierPackageToken);
21356            }
21357
21358            dumpSharedLibrariesProto(proto);
21359            dumpFeaturesProto(proto);
21360            mSettings.dumpPackagesProto(proto);
21361            mSettings.dumpSharedUsersProto(proto);
21362            dumpCriticalInfo(proto);
21363        }
21364        proto.flush();
21365    }
21366
21367    private void dumpFeaturesProto(ProtoOutputStream proto) {
21368        synchronized (mAvailableFeatures) {
21369            final int count = mAvailableFeatures.size();
21370            for (int i = 0; i < count; i++) {
21371                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21372            }
21373        }
21374    }
21375
21376    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21377        final int count = mSharedLibraries.size();
21378        for (int i = 0; i < count; i++) {
21379            final String libName = mSharedLibraries.keyAt(i);
21380            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21381            if (versionedLib == null) {
21382                continue;
21383            }
21384            final int versionCount = versionedLib.size();
21385            for (int j = 0; j < versionCount; j++) {
21386                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21387                final long sharedLibraryToken =
21388                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21389                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21390                final boolean isJar = (libEntry.path != null);
21391                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21392                if (isJar) {
21393                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21394                } else {
21395                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21396                }
21397                proto.end(sharedLibraryToken);
21398            }
21399        }
21400    }
21401
21402    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21403        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21404        ipw.println();
21405        ipw.println("Dexopt state:");
21406        ipw.increaseIndent();
21407        Collection<PackageParser.Package> packages = null;
21408        if (packageName != null) {
21409            PackageParser.Package targetPackage = mPackages.get(packageName);
21410            if (targetPackage != null) {
21411                packages = Collections.singletonList(targetPackage);
21412            } else {
21413                ipw.println("Unable to find package: " + packageName);
21414                return;
21415            }
21416        } else {
21417            packages = mPackages.values();
21418        }
21419
21420        for (PackageParser.Package pkg : packages) {
21421            ipw.println("[" + pkg.packageName + "]");
21422            ipw.increaseIndent();
21423            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21424                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21425            ipw.decreaseIndent();
21426        }
21427    }
21428
21429    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21430        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21431        ipw.println();
21432        ipw.println("Compiler stats:");
21433        ipw.increaseIndent();
21434        Collection<PackageParser.Package> packages = null;
21435        if (packageName != null) {
21436            PackageParser.Package targetPackage = mPackages.get(packageName);
21437            if (targetPackage != null) {
21438                packages = Collections.singletonList(targetPackage);
21439            } else {
21440                ipw.println("Unable to find package: " + packageName);
21441                return;
21442            }
21443        } else {
21444            packages = mPackages.values();
21445        }
21446
21447        for (PackageParser.Package pkg : packages) {
21448            ipw.println("[" + pkg.packageName + "]");
21449            ipw.increaseIndent();
21450
21451            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21452            if (stats == null) {
21453                ipw.println("(No recorded stats)");
21454            } else {
21455                stats.dump(ipw);
21456            }
21457            ipw.decreaseIndent();
21458        }
21459    }
21460
21461    private String dumpDomainString(String packageName) {
21462        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21463                .getList();
21464        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21465
21466        ArraySet<String> result = new ArraySet<>();
21467        if (iviList.size() > 0) {
21468            for (IntentFilterVerificationInfo ivi : iviList) {
21469                for (String host : ivi.getDomains()) {
21470                    result.add(host);
21471                }
21472            }
21473        }
21474        if (filters != null && filters.size() > 0) {
21475            for (IntentFilter filter : filters) {
21476                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21477                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21478                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21479                    result.addAll(filter.getHostsList());
21480                }
21481            }
21482        }
21483
21484        StringBuilder sb = new StringBuilder(result.size() * 16);
21485        for (String domain : result) {
21486            if (sb.length() > 0) sb.append(" ");
21487            sb.append(domain);
21488        }
21489        return sb.toString();
21490    }
21491
21492    // ------- apps on sdcard specific code -------
21493    static final boolean DEBUG_SD_INSTALL = false;
21494
21495    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21496
21497    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21498
21499    private boolean mMediaMounted = false;
21500
21501    static String getEncryptKey() {
21502        try {
21503            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21504                    SD_ENCRYPTION_KEYSTORE_NAME);
21505            if (sdEncKey == null) {
21506                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21507                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21508                if (sdEncKey == null) {
21509                    Slog.e(TAG, "Failed to create encryption keys");
21510                    return null;
21511                }
21512            }
21513            return sdEncKey;
21514        } catch (NoSuchAlgorithmException nsae) {
21515            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21516            return null;
21517        } catch (IOException ioe) {
21518            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21519            return null;
21520        }
21521    }
21522
21523    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21524            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21525        final int size = infos.size();
21526        final String[] packageNames = new String[size];
21527        final int[] packageUids = new int[size];
21528        for (int i = 0; i < size; i++) {
21529            final ApplicationInfo info = infos.get(i);
21530            packageNames[i] = info.packageName;
21531            packageUids[i] = info.uid;
21532        }
21533        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21534                finishedReceiver);
21535    }
21536
21537    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21538            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21539        sendResourcesChangedBroadcast(mediaStatus, replacing,
21540                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21541    }
21542
21543    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21544            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21545        int size = pkgList.length;
21546        if (size > 0) {
21547            // Send broadcasts here
21548            Bundle extras = new Bundle();
21549            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21550            if (uidArr != null) {
21551                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21552            }
21553            if (replacing) {
21554                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21555            }
21556            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21557                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21558            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21559        }
21560    }
21561
21562    private void loadPrivatePackages(final VolumeInfo vol) {
21563        mHandler.post(new Runnable() {
21564            @Override
21565            public void run() {
21566                loadPrivatePackagesInner(vol);
21567            }
21568        });
21569    }
21570
21571    private void loadPrivatePackagesInner(VolumeInfo vol) {
21572        final String volumeUuid = vol.fsUuid;
21573        if (TextUtils.isEmpty(volumeUuid)) {
21574            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21575            return;
21576        }
21577
21578        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21579        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21580        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21581
21582        final VersionInfo ver;
21583        final List<PackageSetting> packages;
21584        synchronized (mPackages) {
21585            ver = mSettings.findOrCreateVersion(volumeUuid);
21586            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21587        }
21588
21589        for (PackageSetting ps : packages) {
21590            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21591            synchronized (mInstallLock) {
21592                final PackageParser.Package pkg;
21593                try {
21594                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21595                    loaded.add(pkg.applicationInfo);
21596
21597                } catch (PackageManagerException e) {
21598                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21599                }
21600
21601                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21602                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21603                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21604                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21605                }
21606            }
21607        }
21608
21609        // Reconcile app data for all started/unlocked users
21610        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21611        final UserManager um = mContext.getSystemService(UserManager.class);
21612        UserManagerInternal umInternal = getUserManagerInternal();
21613        for (UserInfo user : um.getUsers()) {
21614            final int flags;
21615            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21616                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21617            } else if (umInternal.isUserRunning(user.id)) {
21618                flags = StorageManager.FLAG_STORAGE_DE;
21619            } else {
21620                continue;
21621            }
21622
21623            try {
21624                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21625                synchronized (mInstallLock) {
21626                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21627                }
21628            } catch (IllegalStateException e) {
21629                // Device was probably ejected, and we'll process that event momentarily
21630                Slog.w(TAG, "Failed to prepare storage: " + e);
21631            }
21632        }
21633
21634        synchronized (mPackages) {
21635            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21636            if (sdkUpdated) {
21637                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21638                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21639            }
21640            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21641                    mPermissionCallback);
21642
21643            // Yay, everything is now upgraded
21644            ver.forceCurrent();
21645
21646            mSettings.writeLPr();
21647        }
21648
21649        for (PackageFreezer freezer : freezers) {
21650            freezer.close();
21651        }
21652
21653        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21654        sendResourcesChangedBroadcast(true, false, loaded, null);
21655        mLoadedVolumes.add(vol.getId());
21656    }
21657
21658    private void unloadPrivatePackages(final VolumeInfo vol) {
21659        mHandler.post(new Runnable() {
21660            @Override
21661            public void run() {
21662                unloadPrivatePackagesInner(vol);
21663            }
21664        });
21665    }
21666
21667    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21668        final String volumeUuid = vol.fsUuid;
21669        if (TextUtils.isEmpty(volumeUuid)) {
21670            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21671            return;
21672        }
21673
21674        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21675        synchronized (mInstallLock) {
21676        synchronized (mPackages) {
21677            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21678            for (PackageSetting ps : packages) {
21679                if (ps.pkg == null) continue;
21680
21681                final ApplicationInfo info = ps.pkg.applicationInfo;
21682                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21683                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21684
21685                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21686                        "unloadPrivatePackagesInner")) {
21687                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21688                            false, null)) {
21689                        unloaded.add(info);
21690                    } else {
21691                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21692                    }
21693                }
21694
21695                // Try very hard to release any references to this package
21696                // so we don't risk the system server being killed due to
21697                // open FDs
21698                AttributeCache.instance().removePackage(ps.name);
21699            }
21700
21701            mSettings.writeLPr();
21702        }
21703        }
21704
21705        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21706        sendResourcesChangedBroadcast(false, false, unloaded, null);
21707        mLoadedVolumes.remove(vol.getId());
21708
21709        // Try very hard to release any references to this path so we don't risk
21710        // the system server being killed due to open FDs
21711        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21712
21713        for (int i = 0; i < 3; i++) {
21714            System.gc();
21715            System.runFinalization();
21716        }
21717    }
21718
21719    private void assertPackageKnown(String volumeUuid, String packageName)
21720            throws PackageManagerException {
21721        synchronized (mPackages) {
21722            // Normalize package name to handle renamed packages
21723            packageName = normalizePackageNameLPr(packageName);
21724
21725            final PackageSetting ps = mSettings.mPackages.get(packageName);
21726            if (ps == null) {
21727                throw new PackageManagerException("Package " + packageName + " is unknown");
21728            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21729                throw new PackageManagerException(
21730                        "Package " + packageName + " found on unknown volume " + volumeUuid
21731                                + "; expected volume " + ps.volumeUuid);
21732            }
21733        }
21734    }
21735
21736    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21737            throws PackageManagerException {
21738        synchronized (mPackages) {
21739            // Normalize package name to handle renamed packages
21740            packageName = normalizePackageNameLPr(packageName);
21741
21742            final PackageSetting ps = mSettings.mPackages.get(packageName);
21743            if (ps == null) {
21744                throw new PackageManagerException("Package " + packageName + " is unknown");
21745            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21746                throw new PackageManagerException(
21747                        "Package " + packageName + " found on unknown volume " + volumeUuid
21748                                + "; expected volume " + ps.volumeUuid);
21749            } else if (!ps.getInstalled(userId)) {
21750                throw new PackageManagerException(
21751                        "Package " + packageName + " not installed for user " + userId);
21752            }
21753        }
21754    }
21755
21756    private List<String> collectAbsoluteCodePaths() {
21757        synchronized (mPackages) {
21758            List<String> codePaths = new ArrayList<>();
21759            final int packageCount = mSettings.mPackages.size();
21760            for (int i = 0; i < packageCount; i++) {
21761                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21762                codePaths.add(ps.codePath.getAbsolutePath());
21763            }
21764            return codePaths;
21765        }
21766    }
21767
21768    /**
21769     * Examine all apps present on given mounted volume, and destroy apps that
21770     * aren't expected, either due to uninstallation or reinstallation on
21771     * another volume.
21772     */
21773    private void reconcileApps(String volumeUuid) {
21774        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21775        List<File> filesToDelete = null;
21776
21777        final File[] files = FileUtils.listFilesOrEmpty(
21778                Environment.getDataAppDirectory(volumeUuid));
21779        for (File file : files) {
21780            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21781                    && !PackageInstallerService.isStageName(file.getName());
21782            if (!isPackage) {
21783                // Ignore entries which are not packages
21784                continue;
21785            }
21786
21787            String absolutePath = file.getAbsolutePath();
21788
21789            boolean pathValid = false;
21790            final int absoluteCodePathCount = absoluteCodePaths.size();
21791            for (int i = 0; i < absoluteCodePathCount; i++) {
21792                String absoluteCodePath = absoluteCodePaths.get(i);
21793                if (absolutePath.startsWith(absoluteCodePath)) {
21794                    pathValid = true;
21795                    break;
21796                }
21797            }
21798
21799            if (!pathValid) {
21800                if (filesToDelete == null) {
21801                    filesToDelete = new ArrayList<>();
21802                }
21803                filesToDelete.add(file);
21804            }
21805        }
21806
21807        if (filesToDelete != null) {
21808            final int fileToDeleteCount = filesToDelete.size();
21809            for (int i = 0; i < fileToDeleteCount; i++) {
21810                File fileToDelete = filesToDelete.get(i);
21811                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21812                synchronized (mInstallLock) {
21813                    removeCodePathLI(fileToDelete);
21814                }
21815            }
21816        }
21817    }
21818
21819    /**
21820     * Reconcile all app data for the given user.
21821     * <p>
21822     * Verifies that directories exist and that ownership and labeling is
21823     * correct for all installed apps on all mounted volumes.
21824     */
21825    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21826        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21827        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21828            final String volumeUuid = vol.getFsUuid();
21829            synchronized (mInstallLock) {
21830                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21831            }
21832        }
21833    }
21834
21835    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21836            boolean migrateAppData) {
21837        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21838    }
21839
21840    /**
21841     * Reconcile all app data on given mounted volume.
21842     * <p>
21843     * Destroys app data that isn't expected, either due to uninstallation or
21844     * reinstallation on another volume.
21845     * <p>
21846     * Verifies that directories exist and that ownership and labeling is
21847     * correct for all installed apps.
21848     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21849     */
21850    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21851            boolean migrateAppData, boolean onlyCoreApps) {
21852        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21853                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21854        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21855
21856        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21857        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21858
21859        // First look for stale data that doesn't belong, and check if things
21860        // have changed since we did our last restorecon
21861        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21862            if (StorageManager.isFileEncryptedNativeOrEmulated()
21863                    && !StorageManager.isUserKeyUnlocked(userId)) {
21864                throw new RuntimeException(
21865                        "Yikes, someone asked us to reconcile CE storage while " + userId
21866                                + " was still locked; this would have caused massive data loss!");
21867            }
21868
21869            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21870            for (File file : files) {
21871                final String packageName = file.getName();
21872                try {
21873                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21874                } catch (PackageManagerException e) {
21875                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21876                    try {
21877                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21878                                StorageManager.FLAG_STORAGE_CE, 0);
21879                    } catch (InstallerException e2) {
21880                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21881                    }
21882                }
21883            }
21884        }
21885        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21886            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21887            for (File file : files) {
21888                final String packageName = file.getName();
21889                try {
21890                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21891                } catch (PackageManagerException e) {
21892                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21893                    try {
21894                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21895                                StorageManager.FLAG_STORAGE_DE, 0);
21896                    } catch (InstallerException e2) {
21897                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21898                    }
21899                }
21900            }
21901        }
21902
21903        // Ensure that data directories are ready to roll for all packages
21904        // installed for this volume and user
21905        final List<PackageSetting> packages;
21906        synchronized (mPackages) {
21907            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21908        }
21909        int preparedCount = 0;
21910        for (PackageSetting ps : packages) {
21911            final String packageName = ps.name;
21912            if (ps.pkg == null) {
21913                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21914                // TODO: might be due to legacy ASEC apps; we should circle back
21915                // and reconcile again once they're scanned
21916                continue;
21917            }
21918            // Skip non-core apps if requested
21919            if (onlyCoreApps && !ps.pkg.coreApp) {
21920                result.add(packageName);
21921                continue;
21922            }
21923
21924            if (ps.getInstalled(userId)) {
21925                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21926                preparedCount++;
21927            }
21928        }
21929
21930        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21931        return result;
21932    }
21933
21934    /**
21935     * Prepare app data for the given app just after it was installed or
21936     * upgraded. This method carefully only touches users that it's installed
21937     * for, and it forces a restorecon to handle any seinfo changes.
21938     * <p>
21939     * Verifies that directories exist and that ownership and labeling is
21940     * correct for all installed apps. If there is an ownership mismatch, it
21941     * will try recovering system apps by wiping data; third-party app data is
21942     * left intact.
21943     * <p>
21944     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21945     */
21946    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21947        final PackageSetting ps;
21948        synchronized (mPackages) {
21949            ps = mSettings.mPackages.get(pkg.packageName);
21950            mSettings.writeKernelMappingLPr(ps);
21951        }
21952
21953        final UserManager um = mContext.getSystemService(UserManager.class);
21954        UserManagerInternal umInternal = getUserManagerInternal();
21955        for (UserInfo user : um.getUsers()) {
21956            final int flags;
21957            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21958                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21959            } else if (umInternal.isUserRunning(user.id)) {
21960                flags = StorageManager.FLAG_STORAGE_DE;
21961            } else {
21962                continue;
21963            }
21964
21965            if (ps.getInstalled(user.id)) {
21966                // TODO: when user data is locked, mark that we're still dirty
21967                prepareAppDataLIF(pkg, user.id, flags);
21968            }
21969        }
21970    }
21971
21972    /**
21973     * Prepare app data for the given app.
21974     * <p>
21975     * Verifies that directories exist and that ownership and labeling is
21976     * correct for all installed apps. If there is an ownership mismatch, this
21977     * will try recovering system apps by wiping data; third-party app data is
21978     * left intact.
21979     */
21980    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21981        if (pkg == null) {
21982            Slog.wtf(TAG, "Package was null!", new Throwable());
21983            return;
21984        }
21985        prepareAppDataLeafLIF(pkg, userId, flags);
21986        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21987        for (int i = 0; i < childCount; i++) {
21988            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21989        }
21990    }
21991
21992    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21993            boolean maybeMigrateAppData) {
21994        prepareAppDataLIF(pkg, userId, flags);
21995
21996        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21997            // We may have just shuffled around app data directories, so
21998            // prepare them one more time
21999            prepareAppDataLIF(pkg, userId, flags);
22000        }
22001    }
22002
22003    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22004        if (DEBUG_APP_DATA) {
22005            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22006                    + Integer.toHexString(flags));
22007        }
22008
22009        final String volumeUuid = pkg.volumeUuid;
22010        final String packageName = pkg.packageName;
22011        final ApplicationInfo app = pkg.applicationInfo;
22012        final int appId = UserHandle.getAppId(app.uid);
22013
22014        Preconditions.checkNotNull(app.seInfo);
22015
22016        long ceDataInode = -1;
22017        try {
22018            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22019                    appId, app.seInfo, app.targetSdkVersion);
22020        } catch (InstallerException e) {
22021            if (app.isSystemApp()) {
22022                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22023                        + ", but trying to recover: " + e);
22024                destroyAppDataLeafLIF(pkg, userId, flags);
22025                try {
22026                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22027                            appId, app.seInfo, app.targetSdkVersion);
22028                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22029                } catch (InstallerException e2) {
22030                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22031                }
22032            } else {
22033                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22034            }
22035        }
22036
22037        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22038            // TODO: mark this structure as dirty so we persist it!
22039            synchronized (mPackages) {
22040                final PackageSetting ps = mSettings.mPackages.get(packageName);
22041                if (ps != null) {
22042                    ps.setCeDataInode(ceDataInode, userId);
22043                }
22044            }
22045        }
22046
22047        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22048    }
22049
22050    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22051        if (pkg == null) {
22052            Slog.wtf(TAG, "Package was null!", new Throwable());
22053            return;
22054        }
22055        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22056        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22057        for (int i = 0; i < childCount; i++) {
22058            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22059        }
22060    }
22061
22062    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22063        final String volumeUuid = pkg.volumeUuid;
22064        final String packageName = pkg.packageName;
22065        final ApplicationInfo app = pkg.applicationInfo;
22066
22067        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22068            // Create a native library symlink only if we have native libraries
22069            // and if the native libraries are 32 bit libraries. We do not provide
22070            // this symlink for 64 bit libraries.
22071            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22072                final String nativeLibPath = app.nativeLibraryDir;
22073                try {
22074                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22075                            nativeLibPath, userId);
22076                } catch (InstallerException e) {
22077                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22078                }
22079            }
22080        }
22081    }
22082
22083    /**
22084     * For system apps on non-FBE devices, this method migrates any existing
22085     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22086     * requested by the app.
22087     */
22088    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22089        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22090                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22091            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22092                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22093            try {
22094                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22095                        storageTarget);
22096            } catch (InstallerException e) {
22097                logCriticalInfo(Log.WARN,
22098                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22099            }
22100            return true;
22101        } else {
22102            return false;
22103        }
22104    }
22105
22106    public PackageFreezer freezePackage(String packageName, String killReason) {
22107        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22108    }
22109
22110    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22111        return new PackageFreezer(packageName, userId, killReason);
22112    }
22113
22114    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22115            String killReason) {
22116        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22117    }
22118
22119    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22120            String killReason) {
22121        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22122            return new PackageFreezer();
22123        } else {
22124            return freezePackage(packageName, userId, killReason);
22125        }
22126    }
22127
22128    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22129            String killReason) {
22130        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22131    }
22132
22133    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22134            String killReason) {
22135        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22136            return new PackageFreezer();
22137        } else {
22138            return freezePackage(packageName, userId, killReason);
22139        }
22140    }
22141
22142    /**
22143     * Class that freezes and kills the given package upon creation, and
22144     * unfreezes it upon closing. This is typically used when doing surgery on
22145     * app code/data to prevent the app from running while you're working.
22146     */
22147    private class PackageFreezer implements AutoCloseable {
22148        private final String mPackageName;
22149        private final PackageFreezer[] mChildren;
22150
22151        private final boolean mWeFroze;
22152
22153        private final AtomicBoolean mClosed = new AtomicBoolean();
22154        private final CloseGuard mCloseGuard = CloseGuard.get();
22155
22156        /**
22157         * Create and return a stub freezer that doesn't actually do anything,
22158         * typically used when someone requested
22159         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22160         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22161         */
22162        public PackageFreezer() {
22163            mPackageName = null;
22164            mChildren = null;
22165            mWeFroze = false;
22166            mCloseGuard.open("close");
22167        }
22168
22169        public PackageFreezer(String packageName, int userId, String killReason) {
22170            synchronized (mPackages) {
22171                mPackageName = packageName;
22172                mWeFroze = mFrozenPackages.add(mPackageName);
22173
22174                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22175                if (ps != null) {
22176                    killApplication(ps.name, ps.appId, userId, killReason);
22177                }
22178
22179                final PackageParser.Package p = mPackages.get(packageName);
22180                if (p != null && p.childPackages != null) {
22181                    final int N = p.childPackages.size();
22182                    mChildren = new PackageFreezer[N];
22183                    for (int i = 0; i < N; i++) {
22184                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22185                                userId, killReason);
22186                    }
22187                } else {
22188                    mChildren = null;
22189                }
22190            }
22191            mCloseGuard.open("close");
22192        }
22193
22194        @Override
22195        protected void finalize() throws Throwable {
22196            try {
22197                if (mCloseGuard != null) {
22198                    mCloseGuard.warnIfOpen();
22199                }
22200
22201                close();
22202            } finally {
22203                super.finalize();
22204            }
22205        }
22206
22207        @Override
22208        public void close() {
22209            mCloseGuard.close();
22210            if (mClosed.compareAndSet(false, true)) {
22211                synchronized (mPackages) {
22212                    if (mWeFroze) {
22213                        mFrozenPackages.remove(mPackageName);
22214                    }
22215
22216                    if (mChildren != null) {
22217                        for (PackageFreezer freezer : mChildren) {
22218                            freezer.close();
22219                        }
22220                    }
22221                }
22222            }
22223        }
22224    }
22225
22226    /**
22227     * Verify that given package is currently frozen.
22228     */
22229    private void checkPackageFrozen(String packageName) {
22230        synchronized (mPackages) {
22231            if (!mFrozenPackages.contains(packageName)) {
22232                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22233            }
22234        }
22235    }
22236
22237    @Override
22238    public int movePackage(final String packageName, final String volumeUuid) {
22239        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22240
22241        final int callingUid = Binder.getCallingUid();
22242        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22243        final int moveId = mNextMoveId.getAndIncrement();
22244        mHandler.post(new Runnable() {
22245            @Override
22246            public void run() {
22247                try {
22248                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22249                } catch (PackageManagerException e) {
22250                    Slog.w(TAG, "Failed to move " + packageName, e);
22251                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22252                }
22253            }
22254        });
22255        return moveId;
22256    }
22257
22258    private void movePackageInternal(final String packageName, final String volumeUuid,
22259            final int moveId, final int callingUid, UserHandle user)
22260                    throws PackageManagerException {
22261        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22262        final PackageManager pm = mContext.getPackageManager();
22263
22264        final boolean currentAsec;
22265        final String currentVolumeUuid;
22266        final File codeFile;
22267        final String installerPackageName;
22268        final String packageAbiOverride;
22269        final int appId;
22270        final String seinfo;
22271        final String label;
22272        final int targetSdkVersion;
22273        final PackageFreezer freezer;
22274        final int[] installedUserIds;
22275
22276        // reader
22277        synchronized (mPackages) {
22278            final PackageParser.Package pkg = mPackages.get(packageName);
22279            final PackageSetting ps = mSettings.mPackages.get(packageName);
22280            if (pkg == null
22281                    || ps == null
22282                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22283                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22284            }
22285            if (pkg.applicationInfo.isSystemApp()) {
22286                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22287                        "Cannot move system application");
22288            }
22289
22290            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22291            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22292                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22293            if (isInternalStorage && !allow3rdPartyOnInternal) {
22294                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22295                        "3rd party apps are not allowed on internal storage");
22296            }
22297
22298            if (pkg.applicationInfo.isExternalAsec()) {
22299                currentAsec = true;
22300                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22301            } else if (pkg.applicationInfo.isForwardLocked()) {
22302                currentAsec = true;
22303                currentVolumeUuid = "forward_locked";
22304            } else {
22305                currentAsec = false;
22306                currentVolumeUuid = ps.volumeUuid;
22307
22308                final File probe = new File(pkg.codePath);
22309                final File probeOat = new File(probe, "oat");
22310                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22311                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22312                            "Move only supported for modern cluster style installs");
22313                }
22314            }
22315
22316            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22317                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22318                        "Package already moved to " + volumeUuid);
22319            }
22320            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22321                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22322                        "Device admin cannot be moved");
22323            }
22324
22325            if (mFrozenPackages.contains(packageName)) {
22326                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22327                        "Failed to move already frozen package");
22328            }
22329
22330            codeFile = new File(pkg.codePath);
22331            installerPackageName = ps.installerPackageName;
22332            packageAbiOverride = ps.cpuAbiOverrideString;
22333            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22334            seinfo = pkg.applicationInfo.seInfo;
22335            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22336            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22337            freezer = freezePackage(packageName, "movePackageInternal");
22338            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22339        }
22340
22341        final Bundle extras = new Bundle();
22342        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22343        extras.putString(Intent.EXTRA_TITLE, label);
22344        mMoveCallbacks.notifyCreated(moveId, extras);
22345
22346        int installFlags;
22347        final boolean moveCompleteApp;
22348        final File measurePath;
22349
22350        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22351            installFlags = INSTALL_INTERNAL;
22352            moveCompleteApp = !currentAsec;
22353            measurePath = Environment.getDataAppDirectory(volumeUuid);
22354        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22355            installFlags = INSTALL_EXTERNAL;
22356            moveCompleteApp = false;
22357            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22358        } else {
22359            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22360            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22361                    || !volume.isMountedWritable()) {
22362                freezer.close();
22363                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22364                        "Move location not mounted private volume");
22365            }
22366
22367            Preconditions.checkState(!currentAsec);
22368
22369            installFlags = INSTALL_INTERNAL;
22370            moveCompleteApp = true;
22371            measurePath = Environment.getDataAppDirectory(volumeUuid);
22372        }
22373
22374        // If we're moving app data around, we need all the users unlocked
22375        if (moveCompleteApp) {
22376            for (int userId : installedUserIds) {
22377                if (StorageManager.isFileEncryptedNativeOrEmulated()
22378                        && !StorageManager.isUserKeyUnlocked(userId)) {
22379                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22380                            "User " + userId + " must be unlocked");
22381                }
22382            }
22383        }
22384
22385        final PackageStats stats = new PackageStats(null, -1);
22386        synchronized (mInstaller) {
22387            for (int userId : installedUserIds) {
22388                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22389                    freezer.close();
22390                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22391                            "Failed to measure package size");
22392                }
22393            }
22394        }
22395
22396        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22397                + stats.dataSize);
22398
22399        final long startFreeBytes = measurePath.getUsableSpace();
22400        final long sizeBytes;
22401        if (moveCompleteApp) {
22402            sizeBytes = stats.codeSize + stats.dataSize;
22403        } else {
22404            sizeBytes = stats.codeSize;
22405        }
22406
22407        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22408            freezer.close();
22409            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22410                    "Not enough free space to move");
22411        }
22412
22413        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22414
22415        final CountDownLatch installedLatch = new CountDownLatch(1);
22416        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22417            @Override
22418            public void onUserActionRequired(Intent intent) throws RemoteException {
22419                throw new IllegalStateException();
22420            }
22421
22422            @Override
22423            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22424                    Bundle extras) throws RemoteException {
22425                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22426                        + PackageManager.installStatusToString(returnCode, msg));
22427
22428                installedLatch.countDown();
22429                freezer.close();
22430
22431                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22432                switch (status) {
22433                    case PackageInstaller.STATUS_SUCCESS:
22434                        mMoveCallbacks.notifyStatusChanged(moveId,
22435                                PackageManager.MOVE_SUCCEEDED);
22436                        break;
22437                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22438                        mMoveCallbacks.notifyStatusChanged(moveId,
22439                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22440                        break;
22441                    default:
22442                        mMoveCallbacks.notifyStatusChanged(moveId,
22443                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22444                        break;
22445                }
22446            }
22447        };
22448
22449        final MoveInfo move;
22450        if (moveCompleteApp) {
22451            // Kick off a thread to report progress estimates
22452            new Thread() {
22453                @Override
22454                public void run() {
22455                    while (true) {
22456                        try {
22457                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22458                                break;
22459                            }
22460                        } catch (InterruptedException ignored) {
22461                        }
22462
22463                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22464                        final int progress = 10 + (int) MathUtils.constrain(
22465                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22466                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22467                    }
22468                }
22469            }.start();
22470
22471            final String dataAppName = codeFile.getName();
22472            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22473                    dataAppName, appId, seinfo, targetSdkVersion);
22474        } else {
22475            move = null;
22476        }
22477
22478        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22479
22480        final Message msg = mHandler.obtainMessage(INIT_COPY);
22481        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22482        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22483                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22484                packageAbiOverride, null /*grantedPermissions*/,
22485                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22486        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22487        msg.obj = params;
22488
22489        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22490                System.identityHashCode(msg.obj));
22491        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22492                System.identityHashCode(msg.obj));
22493
22494        mHandler.sendMessage(msg);
22495    }
22496
22497    @Override
22498    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22499        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22500
22501        final int realMoveId = mNextMoveId.getAndIncrement();
22502        final Bundle extras = new Bundle();
22503        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22504        mMoveCallbacks.notifyCreated(realMoveId, extras);
22505
22506        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22507            @Override
22508            public void onCreated(int moveId, Bundle extras) {
22509                // Ignored
22510            }
22511
22512            @Override
22513            public void onStatusChanged(int moveId, int status, long estMillis) {
22514                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22515            }
22516        };
22517
22518        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22519        storage.setPrimaryStorageUuid(volumeUuid, callback);
22520        return realMoveId;
22521    }
22522
22523    @Override
22524    public int getMoveStatus(int moveId) {
22525        mContext.enforceCallingOrSelfPermission(
22526                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22527        return mMoveCallbacks.mLastStatus.get(moveId);
22528    }
22529
22530    @Override
22531    public void registerMoveCallback(IPackageMoveObserver callback) {
22532        mContext.enforceCallingOrSelfPermission(
22533                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22534        mMoveCallbacks.register(callback);
22535    }
22536
22537    @Override
22538    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22539        mContext.enforceCallingOrSelfPermission(
22540                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22541        mMoveCallbacks.unregister(callback);
22542    }
22543
22544    @Override
22545    public boolean setInstallLocation(int loc) {
22546        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22547                null);
22548        if (getInstallLocation() == loc) {
22549            return true;
22550        }
22551        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22552                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22553            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22554                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22555            return true;
22556        }
22557        return false;
22558   }
22559
22560    @Override
22561    public int getInstallLocation() {
22562        // allow instant app access
22563        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22564                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22565                PackageHelper.APP_INSTALL_AUTO);
22566    }
22567
22568    /** Called by UserManagerService */
22569    void cleanUpUser(UserManagerService userManager, int userHandle) {
22570        synchronized (mPackages) {
22571            mDirtyUsers.remove(userHandle);
22572            mUserNeedsBadging.delete(userHandle);
22573            mSettings.removeUserLPw(userHandle);
22574            mPendingBroadcasts.remove(userHandle);
22575            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22576            removeUnusedPackagesLPw(userManager, userHandle);
22577        }
22578    }
22579
22580    /**
22581     * We're removing userHandle and would like to remove any downloaded packages
22582     * that are no longer in use by any other user.
22583     * @param userHandle the user being removed
22584     */
22585    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22586        final boolean DEBUG_CLEAN_APKS = false;
22587        int [] users = userManager.getUserIds();
22588        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22589        while (psit.hasNext()) {
22590            PackageSetting ps = psit.next();
22591            if (ps.pkg == null) {
22592                continue;
22593            }
22594            final String packageName = ps.pkg.packageName;
22595            // Skip over if system app
22596            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22597                continue;
22598            }
22599            if (DEBUG_CLEAN_APKS) {
22600                Slog.i(TAG, "Checking package " + packageName);
22601            }
22602            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22603            if (keep) {
22604                if (DEBUG_CLEAN_APKS) {
22605                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22606                }
22607            } else {
22608                for (int i = 0; i < users.length; i++) {
22609                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22610                        keep = true;
22611                        if (DEBUG_CLEAN_APKS) {
22612                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22613                                    + users[i]);
22614                        }
22615                        break;
22616                    }
22617                }
22618            }
22619            if (!keep) {
22620                if (DEBUG_CLEAN_APKS) {
22621                    Slog.i(TAG, "  Removing package " + packageName);
22622                }
22623                mHandler.post(new Runnable() {
22624                    public void run() {
22625                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22626                                userHandle, 0);
22627                    } //end run
22628                });
22629            }
22630        }
22631    }
22632
22633    /** Called by UserManagerService */
22634    void createNewUser(int userId, String[] disallowedPackages) {
22635        synchronized (mInstallLock) {
22636            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22637        }
22638        synchronized (mPackages) {
22639            scheduleWritePackageRestrictionsLocked(userId);
22640            scheduleWritePackageListLocked(userId);
22641            applyFactoryDefaultBrowserLPw(userId);
22642            primeDomainVerificationsLPw(userId);
22643        }
22644    }
22645
22646    void onNewUserCreated(final int userId) {
22647        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22648        synchronized(mPackages) {
22649            // If permission review for legacy apps is required, we represent
22650            // dagerous permissions for such apps as always granted runtime
22651            // permissions to keep per user flag state whether review is needed.
22652            // Hence, if a new user is added we have to propagate dangerous
22653            // permission grants for these legacy apps.
22654            if (mSettings.mPermissions.mPermissionReviewRequired) {
22655// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22656                mPermissionManager.updateAllPermissions(
22657                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22658                        mPermissionCallback);
22659            }
22660        }
22661    }
22662
22663    @Override
22664    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22665        mContext.enforceCallingOrSelfPermission(
22666                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22667                "Only package verification agents can read the verifier device identity");
22668
22669        synchronized (mPackages) {
22670            return mSettings.getVerifierDeviceIdentityLPw();
22671        }
22672    }
22673
22674    @Override
22675    public void setPermissionEnforced(String permission, boolean enforced) {
22676        // TODO: Now that we no longer change GID for storage, this should to away.
22677        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22678                "setPermissionEnforced");
22679        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22680            synchronized (mPackages) {
22681                if (mSettings.mReadExternalStorageEnforced == null
22682                        || mSettings.mReadExternalStorageEnforced != enforced) {
22683                    mSettings.mReadExternalStorageEnforced =
22684                            enforced ? Boolean.TRUE : Boolean.FALSE;
22685                    mSettings.writeLPr();
22686                }
22687            }
22688            // kill any non-foreground processes so we restart them and
22689            // grant/revoke the GID.
22690            final IActivityManager am = ActivityManager.getService();
22691            if (am != null) {
22692                final long token = Binder.clearCallingIdentity();
22693                try {
22694                    am.killProcessesBelowForeground("setPermissionEnforcement");
22695                } catch (RemoteException e) {
22696                } finally {
22697                    Binder.restoreCallingIdentity(token);
22698                }
22699            }
22700        } else {
22701            throw new IllegalArgumentException("No selective enforcement for " + permission);
22702        }
22703    }
22704
22705    @Override
22706    @Deprecated
22707    public boolean isPermissionEnforced(String permission) {
22708        // allow instant applications
22709        return true;
22710    }
22711
22712    @Override
22713    public boolean isStorageLow() {
22714        // allow instant applications
22715        final long token = Binder.clearCallingIdentity();
22716        try {
22717            final DeviceStorageMonitorInternal
22718                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22719            if (dsm != null) {
22720                return dsm.isMemoryLow();
22721            } else {
22722                return false;
22723            }
22724        } finally {
22725            Binder.restoreCallingIdentity(token);
22726        }
22727    }
22728
22729    @Override
22730    public IPackageInstaller getPackageInstaller() {
22731        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22732            return null;
22733        }
22734        return mInstallerService;
22735    }
22736
22737    @Override
22738    public IArtManager getArtManager() {
22739        return mArtManagerService;
22740    }
22741
22742    private boolean userNeedsBadging(int userId) {
22743        int index = mUserNeedsBadging.indexOfKey(userId);
22744        if (index < 0) {
22745            final UserInfo userInfo;
22746            final long token = Binder.clearCallingIdentity();
22747            try {
22748                userInfo = sUserManager.getUserInfo(userId);
22749            } finally {
22750                Binder.restoreCallingIdentity(token);
22751            }
22752            final boolean b;
22753            if (userInfo != null && userInfo.isManagedProfile()) {
22754                b = true;
22755            } else {
22756                b = false;
22757            }
22758            mUserNeedsBadging.put(userId, b);
22759            return b;
22760        }
22761        return mUserNeedsBadging.valueAt(index);
22762    }
22763
22764    @Override
22765    public KeySet getKeySetByAlias(String packageName, String alias) {
22766        if (packageName == null || alias == null) {
22767            return null;
22768        }
22769        synchronized(mPackages) {
22770            final PackageParser.Package pkg = mPackages.get(packageName);
22771            if (pkg == null) {
22772                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22773                throw new IllegalArgumentException("Unknown package: " + packageName);
22774            }
22775            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22776            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22777                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22778                throw new IllegalArgumentException("Unknown package: " + packageName);
22779            }
22780            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22781            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22782        }
22783    }
22784
22785    @Override
22786    public KeySet getSigningKeySet(String packageName) {
22787        if (packageName == null) {
22788            return null;
22789        }
22790        synchronized(mPackages) {
22791            final int callingUid = Binder.getCallingUid();
22792            final int callingUserId = UserHandle.getUserId(callingUid);
22793            final PackageParser.Package pkg = mPackages.get(packageName);
22794            if (pkg == null) {
22795                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22796                throw new IllegalArgumentException("Unknown package: " + packageName);
22797            }
22798            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22799            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22800                // filter and pretend the package doesn't exist
22801                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22802                        + ", uid:" + callingUid);
22803                throw new IllegalArgumentException("Unknown package: " + packageName);
22804            }
22805            if (pkg.applicationInfo.uid != callingUid
22806                    && Process.SYSTEM_UID != callingUid) {
22807                throw new SecurityException("May not access signing KeySet of other apps.");
22808            }
22809            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22810            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22811        }
22812    }
22813
22814    @Override
22815    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22816        final int callingUid = Binder.getCallingUid();
22817        if (getInstantAppPackageName(callingUid) != null) {
22818            return false;
22819        }
22820        if (packageName == null || ks == null) {
22821            return false;
22822        }
22823        synchronized(mPackages) {
22824            final PackageParser.Package pkg = mPackages.get(packageName);
22825            if (pkg == null
22826                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22827                            UserHandle.getUserId(callingUid))) {
22828                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22829                throw new IllegalArgumentException("Unknown package: " + packageName);
22830            }
22831            IBinder ksh = ks.getToken();
22832            if (ksh instanceof KeySetHandle) {
22833                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22834                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22835            }
22836            return false;
22837        }
22838    }
22839
22840    @Override
22841    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22842        final int callingUid = Binder.getCallingUid();
22843        if (getInstantAppPackageName(callingUid) != null) {
22844            return false;
22845        }
22846        if (packageName == null || ks == null) {
22847            return false;
22848        }
22849        synchronized(mPackages) {
22850            final PackageParser.Package pkg = mPackages.get(packageName);
22851            if (pkg == null
22852                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22853                            UserHandle.getUserId(callingUid))) {
22854                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22855                throw new IllegalArgumentException("Unknown package: " + packageName);
22856            }
22857            IBinder ksh = ks.getToken();
22858            if (ksh instanceof KeySetHandle) {
22859                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22860                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22861            }
22862            return false;
22863        }
22864    }
22865
22866    private void deletePackageIfUnusedLPr(final String packageName) {
22867        PackageSetting ps = mSettings.mPackages.get(packageName);
22868        if (ps == null) {
22869            return;
22870        }
22871        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22872            // TODO Implement atomic delete if package is unused
22873            // It is currently possible that the package will be deleted even if it is installed
22874            // after this method returns.
22875            mHandler.post(new Runnable() {
22876                public void run() {
22877                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22878                            0, PackageManager.DELETE_ALL_USERS);
22879                }
22880            });
22881        }
22882    }
22883
22884    /**
22885     * Check and throw if the given before/after packages would be considered a
22886     * downgrade.
22887     */
22888    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22889            throws PackageManagerException {
22890        if (after.getLongVersionCode() < before.getLongVersionCode()) {
22891            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22892                    "Update version code " + after.versionCode + " is older than current "
22893                    + before.getLongVersionCode());
22894        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
22895            if (after.baseRevisionCode < before.baseRevisionCode) {
22896                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22897                        "Update base revision code " + after.baseRevisionCode
22898                        + " is older than current " + before.baseRevisionCode);
22899            }
22900
22901            if (!ArrayUtils.isEmpty(after.splitNames)) {
22902                for (int i = 0; i < after.splitNames.length; i++) {
22903                    final String splitName = after.splitNames[i];
22904                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22905                    if (j != -1) {
22906                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22907                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22908                                    "Update split " + splitName + " revision code "
22909                                    + after.splitRevisionCodes[i] + " is older than current "
22910                                    + before.splitRevisionCodes[j]);
22911                        }
22912                    }
22913                }
22914            }
22915        }
22916    }
22917
22918    private static class MoveCallbacks extends Handler {
22919        private static final int MSG_CREATED = 1;
22920        private static final int MSG_STATUS_CHANGED = 2;
22921
22922        private final RemoteCallbackList<IPackageMoveObserver>
22923                mCallbacks = new RemoteCallbackList<>();
22924
22925        private final SparseIntArray mLastStatus = new SparseIntArray();
22926
22927        public MoveCallbacks(Looper looper) {
22928            super(looper);
22929        }
22930
22931        public void register(IPackageMoveObserver callback) {
22932            mCallbacks.register(callback);
22933        }
22934
22935        public void unregister(IPackageMoveObserver callback) {
22936            mCallbacks.unregister(callback);
22937        }
22938
22939        @Override
22940        public void handleMessage(Message msg) {
22941            final SomeArgs args = (SomeArgs) msg.obj;
22942            final int n = mCallbacks.beginBroadcast();
22943            for (int i = 0; i < n; i++) {
22944                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22945                try {
22946                    invokeCallback(callback, msg.what, args);
22947                } catch (RemoteException ignored) {
22948                }
22949            }
22950            mCallbacks.finishBroadcast();
22951            args.recycle();
22952        }
22953
22954        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22955                throws RemoteException {
22956            switch (what) {
22957                case MSG_CREATED: {
22958                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22959                    break;
22960                }
22961                case MSG_STATUS_CHANGED: {
22962                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22963                    break;
22964                }
22965            }
22966        }
22967
22968        private void notifyCreated(int moveId, Bundle extras) {
22969            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22970
22971            final SomeArgs args = SomeArgs.obtain();
22972            args.argi1 = moveId;
22973            args.arg2 = extras;
22974            obtainMessage(MSG_CREATED, args).sendToTarget();
22975        }
22976
22977        private void notifyStatusChanged(int moveId, int status) {
22978            notifyStatusChanged(moveId, status, -1);
22979        }
22980
22981        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22982            Slog.v(TAG, "Move " + moveId + " status " + status);
22983
22984            final SomeArgs args = SomeArgs.obtain();
22985            args.argi1 = moveId;
22986            args.argi2 = status;
22987            args.arg3 = estMillis;
22988            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22989
22990            synchronized (mLastStatus) {
22991                mLastStatus.put(moveId, status);
22992            }
22993        }
22994    }
22995
22996    private final static class OnPermissionChangeListeners extends Handler {
22997        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22998
22999        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23000                new RemoteCallbackList<>();
23001
23002        public OnPermissionChangeListeners(Looper looper) {
23003            super(looper);
23004        }
23005
23006        @Override
23007        public void handleMessage(Message msg) {
23008            switch (msg.what) {
23009                case MSG_ON_PERMISSIONS_CHANGED: {
23010                    final int uid = msg.arg1;
23011                    handleOnPermissionsChanged(uid);
23012                } break;
23013            }
23014        }
23015
23016        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23017            mPermissionListeners.register(listener);
23018
23019        }
23020
23021        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23022            mPermissionListeners.unregister(listener);
23023        }
23024
23025        public void onPermissionsChanged(int uid) {
23026            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23027                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23028            }
23029        }
23030
23031        private void handleOnPermissionsChanged(int uid) {
23032            final int count = mPermissionListeners.beginBroadcast();
23033            try {
23034                for (int i = 0; i < count; i++) {
23035                    IOnPermissionsChangeListener callback = mPermissionListeners
23036                            .getBroadcastItem(i);
23037                    try {
23038                        callback.onPermissionsChanged(uid);
23039                    } catch (RemoteException e) {
23040                        Log.e(TAG, "Permission listener is dead", e);
23041                    }
23042                }
23043            } finally {
23044                mPermissionListeners.finishBroadcast();
23045            }
23046        }
23047    }
23048
23049    private class PackageManagerNative extends IPackageManagerNative.Stub {
23050        @Override
23051        public String[] getNamesForUids(int[] uids) throws RemoteException {
23052            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23053            // massage results so they can be parsed by the native binder
23054            for (int i = results.length - 1; i >= 0; --i) {
23055                if (results[i] == null) {
23056                    results[i] = "";
23057                }
23058            }
23059            return results;
23060        }
23061
23062        // NB: this differentiates between preloads and sideloads
23063        @Override
23064        public String getInstallerForPackage(String packageName) throws RemoteException {
23065            final String installerName = getInstallerPackageName(packageName);
23066            if (!TextUtils.isEmpty(installerName)) {
23067                return installerName;
23068            }
23069            // differentiate between preload and sideload
23070            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23071            ApplicationInfo appInfo = getApplicationInfo(packageName,
23072                                    /*flags*/ 0,
23073                                    /*userId*/ callingUser);
23074            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23075                return "preload";
23076            }
23077            return "";
23078        }
23079
23080        @Override
23081        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23082            try {
23083                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23084                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23085                if (pInfo != null) {
23086                    return pInfo.getLongVersionCode();
23087                }
23088            } catch (Exception e) {
23089            }
23090            return 0;
23091        }
23092    }
23093
23094    private class PackageManagerInternalImpl extends PackageManagerInternal {
23095        @Override
23096        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23097                int flagValues, int userId) {
23098            PackageManagerService.this.updatePermissionFlags(
23099                    permName, packageName, flagMask, flagValues, userId);
23100        }
23101
23102        @Override
23103        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23104            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23105        }
23106
23107        @Override
23108        public boolean isInstantApp(String packageName, int userId) {
23109            return PackageManagerService.this.isInstantApp(packageName, userId);
23110        }
23111
23112        @Override
23113        public String getInstantAppPackageName(int uid) {
23114            return PackageManagerService.this.getInstantAppPackageName(uid);
23115        }
23116
23117        @Override
23118        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23119            synchronized (mPackages) {
23120                return PackageManagerService.this.filterAppAccessLPr(
23121                        (PackageSetting) pkg.mExtras, callingUid, userId);
23122            }
23123        }
23124
23125        @Override
23126        public PackageParser.Package getPackage(String packageName) {
23127            synchronized (mPackages) {
23128                packageName = resolveInternalPackageNameLPr(
23129                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23130                return mPackages.get(packageName);
23131            }
23132        }
23133
23134        @Override
23135        public PackageList getPackageList(PackageListObserver observer) {
23136            synchronized (mPackages) {
23137                final int N = mPackages.size();
23138                final ArrayList<String> list = new ArrayList<>(N);
23139                for (int i = 0; i < N; i++) {
23140                    list.add(mPackages.keyAt(i));
23141                }
23142                final PackageList packageList = new PackageList(list, observer);
23143                if (observer != null) {
23144                    mPackageListObservers.add(packageList);
23145                }
23146                return packageList;
23147            }
23148        }
23149
23150        @Override
23151        public void removePackageListObserver(PackageListObserver observer) {
23152            synchronized (mPackages) {
23153                mPackageListObservers.remove(observer);
23154            }
23155        }
23156
23157        @Override
23158        public PackageParser.Package getDisabledPackage(String packageName) {
23159            synchronized (mPackages) {
23160                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23161                return (ps != null) ? ps.pkg : null;
23162            }
23163        }
23164
23165        @Override
23166        public String getKnownPackageName(int knownPackage, int userId) {
23167            switch(knownPackage) {
23168                case PackageManagerInternal.PACKAGE_BROWSER:
23169                    return getDefaultBrowserPackageName(userId);
23170                case PackageManagerInternal.PACKAGE_INSTALLER:
23171                    return mRequiredInstallerPackage;
23172                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23173                    return mSetupWizardPackage;
23174                case PackageManagerInternal.PACKAGE_SYSTEM:
23175                    return "android";
23176                case PackageManagerInternal.PACKAGE_VERIFIER:
23177                    return mRequiredVerifierPackage;
23178            }
23179            return null;
23180        }
23181
23182        @Override
23183        public boolean isResolveActivityComponent(ComponentInfo component) {
23184            return mResolveActivity.packageName.equals(component.packageName)
23185                    && mResolveActivity.name.equals(component.name);
23186        }
23187
23188        @Override
23189        public void setLocationPackagesProvider(PackagesProvider provider) {
23190            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23191        }
23192
23193        @Override
23194        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23195            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23196        }
23197
23198        @Override
23199        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23200            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23201        }
23202
23203        @Override
23204        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23205            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23206        }
23207
23208        @Override
23209        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23210            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23211        }
23212
23213        @Override
23214        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23215            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23216        }
23217
23218        @Override
23219        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23220            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23221        }
23222
23223        @Override
23224        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23225            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23226        }
23227
23228        @Override
23229        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23230            synchronized (mPackages) {
23231                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23232            }
23233            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23234        }
23235
23236        @Override
23237        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23238            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23239                    packageName, userId);
23240        }
23241
23242        @Override
23243        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23244            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23245                    packageName, userId);
23246        }
23247
23248        @Override
23249        public void setKeepUninstalledPackages(final List<String> packageList) {
23250            Preconditions.checkNotNull(packageList);
23251            List<String> removedFromList = null;
23252            synchronized (mPackages) {
23253                if (mKeepUninstalledPackages != null) {
23254                    final int packagesCount = mKeepUninstalledPackages.size();
23255                    for (int i = 0; i < packagesCount; i++) {
23256                        String oldPackage = mKeepUninstalledPackages.get(i);
23257                        if (packageList != null && packageList.contains(oldPackage)) {
23258                            continue;
23259                        }
23260                        if (removedFromList == null) {
23261                            removedFromList = new ArrayList<>();
23262                        }
23263                        removedFromList.add(oldPackage);
23264                    }
23265                }
23266                mKeepUninstalledPackages = new ArrayList<>(packageList);
23267                if (removedFromList != null) {
23268                    final int removedCount = removedFromList.size();
23269                    for (int i = 0; i < removedCount; i++) {
23270                        deletePackageIfUnusedLPr(removedFromList.get(i));
23271                    }
23272                }
23273            }
23274        }
23275
23276        @Override
23277        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23278            synchronized (mPackages) {
23279                return mPermissionManager.isPermissionsReviewRequired(
23280                        mPackages.get(packageName), userId);
23281            }
23282        }
23283
23284        @Override
23285        public PackageInfo getPackageInfo(
23286                String packageName, int flags, int filterCallingUid, int userId) {
23287            return PackageManagerService.this
23288                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23289                            flags, filterCallingUid, userId);
23290        }
23291
23292        @Override
23293        public int getPackageUid(String packageName, int flags, int userId) {
23294            return PackageManagerService.this
23295                    .getPackageUid(packageName, flags, userId);
23296        }
23297
23298        @Override
23299        public ApplicationInfo getApplicationInfo(
23300                String packageName, int flags, int filterCallingUid, int userId) {
23301            return PackageManagerService.this
23302                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23303        }
23304
23305        @Override
23306        public ActivityInfo getActivityInfo(
23307                ComponentName component, int flags, int filterCallingUid, int userId) {
23308            return PackageManagerService.this
23309                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23310        }
23311
23312        @Override
23313        public List<ResolveInfo> queryIntentActivities(
23314                Intent intent, int flags, int filterCallingUid, int userId) {
23315            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23316            return PackageManagerService.this
23317                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23318                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23319        }
23320
23321        @Override
23322        public List<ResolveInfo> queryIntentServices(
23323                Intent intent, int flags, int callingUid, int userId) {
23324            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23325            return PackageManagerService.this
23326                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23327                            false);
23328        }
23329
23330        @Override
23331        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23332                int userId) {
23333            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23334        }
23335
23336        @Override
23337        public void setDeviceAndProfileOwnerPackages(
23338                int deviceOwnerUserId, String deviceOwnerPackage,
23339                SparseArray<String> profileOwnerPackages) {
23340            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23341                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23342        }
23343
23344        @Override
23345        public boolean isPackageDataProtected(int userId, String packageName) {
23346            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23347        }
23348
23349        @Override
23350        public boolean isPackageEphemeral(int userId, String packageName) {
23351            synchronized (mPackages) {
23352                final PackageSetting ps = mSettings.mPackages.get(packageName);
23353                return ps != null ? ps.getInstantApp(userId) : false;
23354            }
23355        }
23356
23357        @Override
23358        public boolean wasPackageEverLaunched(String packageName, int userId) {
23359            synchronized (mPackages) {
23360                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23361            }
23362        }
23363
23364        @Override
23365        public void grantRuntimePermission(String packageName, String permName, int userId,
23366                boolean overridePolicy) {
23367            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23368                    permName, packageName, overridePolicy, getCallingUid(), userId,
23369                    mPermissionCallback);
23370        }
23371
23372        @Override
23373        public void revokeRuntimePermission(String packageName, String permName, int userId,
23374                boolean overridePolicy) {
23375            mPermissionManager.revokeRuntimePermission(
23376                    permName, packageName, overridePolicy, getCallingUid(), userId,
23377                    mPermissionCallback);
23378        }
23379
23380        @Override
23381        public String getNameForUid(int uid) {
23382            return PackageManagerService.this.getNameForUid(uid);
23383        }
23384
23385        @Override
23386        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23387                Intent origIntent, String resolvedType, String callingPackage,
23388                Bundle verificationBundle, int userId) {
23389            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23390                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23391                    userId);
23392        }
23393
23394        @Override
23395        public void grantEphemeralAccess(int userId, Intent intent,
23396                int targetAppId, int ephemeralAppId) {
23397            synchronized (mPackages) {
23398                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23399                        targetAppId, ephemeralAppId);
23400            }
23401        }
23402
23403        @Override
23404        public boolean isInstantAppInstallerComponent(ComponentName component) {
23405            synchronized (mPackages) {
23406                return mInstantAppInstallerActivity != null
23407                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23408            }
23409        }
23410
23411        @Override
23412        public void pruneInstantApps() {
23413            mInstantAppRegistry.pruneInstantApps();
23414        }
23415
23416        @Override
23417        public String getSetupWizardPackageName() {
23418            return mSetupWizardPackage;
23419        }
23420
23421        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23422            if (policy != null) {
23423                mExternalSourcesPolicy = policy;
23424            }
23425        }
23426
23427        @Override
23428        public boolean isPackagePersistent(String packageName) {
23429            synchronized (mPackages) {
23430                PackageParser.Package pkg = mPackages.get(packageName);
23431                return pkg != null
23432                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23433                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23434                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23435                        : false;
23436            }
23437        }
23438
23439        @Override
23440        public boolean isLegacySystemApp(Package pkg) {
23441            synchronized (mPackages) {
23442                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23443                return mPromoteSystemApps
23444                        && ps.isSystem()
23445                        && mExistingSystemPackages.contains(ps.name);
23446            }
23447        }
23448
23449        @Override
23450        public List<PackageInfo> getOverlayPackages(int userId) {
23451            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23452            synchronized (mPackages) {
23453                for (PackageParser.Package p : mPackages.values()) {
23454                    if (p.mOverlayTarget != null) {
23455                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23456                        if (pkg != null) {
23457                            overlayPackages.add(pkg);
23458                        }
23459                    }
23460                }
23461            }
23462            return overlayPackages;
23463        }
23464
23465        @Override
23466        public List<String> getTargetPackageNames(int userId) {
23467            List<String> targetPackages = new ArrayList<>();
23468            synchronized (mPackages) {
23469                for (PackageParser.Package p : mPackages.values()) {
23470                    if (p.mOverlayTarget == null) {
23471                        targetPackages.add(p.packageName);
23472                    }
23473                }
23474            }
23475            return targetPackages;
23476        }
23477
23478        @Override
23479        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23480                @Nullable List<String> overlayPackageNames) {
23481            synchronized (mPackages) {
23482                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23483                    Slog.e(TAG, "failed to find package " + targetPackageName);
23484                    return false;
23485                }
23486                ArrayList<String> overlayPaths = null;
23487                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23488                    final int N = overlayPackageNames.size();
23489                    overlayPaths = new ArrayList<>(N);
23490                    for (int i = 0; i < N; i++) {
23491                        final String packageName = overlayPackageNames.get(i);
23492                        final PackageParser.Package pkg = mPackages.get(packageName);
23493                        if (pkg == null) {
23494                            Slog.e(TAG, "failed to find package " + packageName);
23495                            return false;
23496                        }
23497                        overlayPaths.add(pkg.baseCodePath);
23498                    }
23499                }
23500
23501                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23502                ps.setOverlayPaths(overlayPaths, userId);
23503                return true;
23504            }
23505        }
23506
23507        @Override
23508        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23509                int flags, int userId, boolean resolveForStart) {
23510            return resolveIntentInternal(
23511                    intent, resolvedType, flags, userId, resolveForStart);
23512        }
23513
23514        @Override
23515        public ResolveInfo resolveService(Intent intent, String resolvedType,
23516                int flags, int userId, int callingUid) {
23517            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23518        }
23519
23520        @Override
23521        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23522            return PackageManagerService.this.resolveContentProviderInternal(
23523                    name, flags, userId);
23524        }
23525
23526        @Override
23527        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23528            synchronized (mPackages) {
23529                mIsolatedOwners.put(isolatedUid, ownerUid);
23530            }
23531        }
23532
23533        @Override
23534        public void removeIsolatedUid(int isolatedUid) {
23535            synchronized (mPackages) {
23536                mIsolatedOwners.delete(isolatedUid);
23537            }
23538        }
23539
23540        @Override
23541        public int getUidTargetSdkVersion(int uid) {
23542            synchronized (mPackages) {
23543                return getUidTargetSdkVersionLockedLPr(uid);
23544            }
23545        }
23546
23547        @Override
23548        public int getPackageTargetSdkVersion(String packageName) {
23549            synchronized (mPackages) {
23550                return getPackageTargetSdkVersionLockedLPr(packageName);
23551            }
23552        }
23553
23554        @Override
23555        public boolean canAccessInstantApps(int callingUid, int userId) {
23556            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23557        }
23558
23559        @Override
23560        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23561            synchronized (mPackages) {
23562                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23563            }
23564        }
23565
23566        @Override
23567        public void notifyPackageUse(String packageName, int reason) {
23568            synchronized (mPackages) {
23569                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23570            }
23571        }
23572    }
23573
23574    @Override
23575    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23576        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23577        synchronized (mPackages) {
23578            final long identity = Binder.clearCallingIdentity();
23579            try {
23580                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23581                        packageNames, userId);
23582            } finally {
23583                Binder.restoreCallingIdentity(identity);
23584            }
23585        }
23586    }
23587
23588    @Override
23589    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23590        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23591        synchronized (mPackages) {
23592            final long identity = Binder.clearCallingIdentity();
23593            try {
23594                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23595                        packageNames, userId);
23596            } finally {
23597                Binder.restoreCallingIdentity(identity);
23598            }
23599        }
23600    }
23601
23602    private static void enforceSystemOrPhoneCaller(String tag) {
23603        int callingUid = Binder.getCallingUid();
23604        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23605            throw new SecurityException(
23606                    "Cannot call " + tag + " from UID " + callingUid);
23607        }
23608    }
23609
23610    boolean isHistoricalPackageUsageAvailable() {
23611        return mPackageUsage.isHistoricalPackageUsageAvailable();
23612    }
23613
23614    /**
23615     * Return a <b>copy</b> of the collection of packages known to the package manager.
23616     * @return A copy of the values of mPackages.
23617     */
23618    Collection<PackageParser.Package> getPackages() {
23619        synchronized (mPackages) {
23620            return new ArrayList<>(mPackages.values());
23621        }
23622    }
23623
23624    /**
23625     * Logs process start information (including base APK hash) to the security log.
23626     * @hide
23627     */
23628    @Override
23629    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23630            String apkFile, int pid) {
23631        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23632            return;
23633        }
23634        if (!SecurityLog.isLoggingEnabled()) {
23635            return;
23636        }
23637        Bundle data = new Bundle();
23638        data.putLong("startTimestamp", System.currentTimeMillis());
23639        data.putString("processName", processName);
23640        data.putInt("uid", uid);
23641        data.putString("seinfo", seinfo);
23642        data.putString("apkFile", apkFile);
23643        data.putInt("pid", pid);
23644        Message msg = mProcessLoggingHandler.obtainMessage(
23645                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23646        msg.setData(data);
23647        mProcessLoggingHandler.sendMessage(msg);
23648    }
23649
23650    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23651        return mCompilerStats.getPackageStats(pkgName);
23652    }
23653
23654    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23655        return getOrCreateCompilerPackageStats(pkg.packageName);
23656    }
23657
23658    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23659        return mCompilerStats.getOrCreatePackageStats(pkgName);
23660    }
23661
23662    public void deleteCompilerPackageStats(String pkgName) {
23663        mCompilerStats.deletePackageStats(pkgName);
23664    }
23665
23666    @Override
23667    public int getInstallReason(String packageName, int userId) {
23668        final int callingUid = Binder.getCallingUid();
23669        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23670                true /* requireFullPermission */, false /* checkShell */,
23671                "get install reason");
23672        synchronized (mPackages) {
23673            final PackageSetting ps = mSettings.mPackages.get(packageName);
23674            if (filterAppAccessLPr(ps, callingUid, userId)) {
23675                return PackageManager.INSTALL_REASON_UNKNOWN;
23676            }
23677            if (ps != null) {
23678                return ps.getInstallReason(userId);
23679            }
23680        }
23681        return PackageManager.INSTALL_REASON_UNKNOWN;
23682    }
23683
23684    @Override
23685    public boolean canRequestPackageInstalls(String packageName, int userId) {
23686        return canRequestPackageInstallsInternal(packageName, 0, userId,
23687                true /* throwIfPermNotDeclared*/);
23688    }
23689
23690    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23691            boolean throwIfPermNotDeclared) {
23692        int callingUid = Binder.getCallingUid();
23693        int uid = getPackageUid(packageName, 0, userId);
23694        if (callingUid != uid && callingUid != Process.ROOT_UID
23695                && callingUid != Process.SYSTEM_UID) {
23696            throw new SecurityException(
23697                    "Caller uid " + callingUid + " does not own package " + packageName);
23698        }
23699        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23700        if (info == null) {
23701            return false;
23702        }
23703        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23704            return false;
23705        }
23706        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23707        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23708        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23709            if (throwIfPermNotDeclared) {
23710                throw new SecurityException("Need to declare " + appOpPermission
23711                        + " to call this api");
23712            } else {
23713                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23714                return false;
23715            }
23716        }
23717        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23718            return false;
23719        }
23720        if (mExternalSourcesPolicy != null) {
23721            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23722            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23723                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23724            }
23725        }
23726        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23727    }
23728
23729    @Override
23730    public ComponentName getInstantAppResolverSettingsComponent() {
23731        return mInstantAppResolverSettingsComponent;
23732    }
23733
23734    @Override
23735    public ComponentName getInstantAppInstallerComponent() {
23736        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23737            return null;
23738        }
23739        return mInstantAppInstallerActivity == null
23740                ? null : mInstantAppInstallerActivity.getComponentName();
23741    }
23742
23743    @Override
23744    public String getInstantAppAndroidId(String packageName, int userId) {
23745        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23746                "getInstantAppAndroidId");
23747        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23748                true /* requireFullPermission */, false /* checkShell */,
23749                "getInstantAppAndroidId");
23750        // Make sure the target is an Instant App.
23751        if (!isInstantApp(packageName, userId)) {
23752            return null;
23753        }
23754        synchronized (mPackages) {
23755            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23756        }
23757    }
23758
23759    boolean canHaveOatDir(String packageName) {
23760        synchronized (mPackages) {
23761            PackageParser.Package p = mPackages.get(packageName);
23762            if (p == null) {
23763                return false;
23764            }
23765            return p.canHaveOatDir();
23766        }
23767    }
23768
23769    private String getOatDir(PackageParser.Package pkg) {
23770        if (!pkg.canHaveOatDir()) {
23771            return null;
23772        }
23773        File codePath = new File(pkg.codePath);
23774        if (codePath.isDirectory()) {
23775            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23776        }
23777        return null;
23778    }
23779
23780    void deleteOatArtifactsOfPackage(String packageName) {
23781        final String[] instructionSets;
23782        final List<String> codePaths;
23783        final String oatDir;
23784        final PackageParser.Package pkg;
23785        synchronized (mPackages) {
23786            pkg = mPackages.get(packageName);
23787        }
23788        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23789        codePaths = pkg.getAllCodePaths();
23790        oatDir = getOatDir(pkg);
23791
23792        for (String codePath : codePaths) {
23793            for (String isa : instructionSets) {
23794                try {
23795                    mInstaller.deleteOdex(codePath, isa, oatDir);
23796                } catch (InstallerException e) {
23797                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23798                }
23799            }
23800        }
23801    }
23802
23803    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23804        Set<String> unusedPackages = new HashSet<>();
23805        long currentTimeInMillis = System.currentTimeMillis();
23806        synchronized (mPackages) {
23807            for (PackageParser.Package pkg : mPackages.values()) {
23808                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23809                if (ps == null) {
23810                    continue;
23811                }
23812                PackageDexUsage.PackageUseInfo packageUseInfo =
23813                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23814                if (PackageManagerServiceUtils
23815                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23816                                downgradeTimeThresholdMillis, packageUseInfo,
23817                                pkg.getLatestPackageUseTimeInMills(),
23818                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23819                    unusedPackages.add(pkg.packageName);
23820                }
23821            }
23822        }
23823        return unusedPackages;
23824    }
23825
23826    @Override
23827    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
23828            int userId) {
23829        final int callingUid = Binder.getCallingUid();
23830        final int callingAppId = UserHandle.getAppId(callingUid);
23831
23832        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23833                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
23834
23835        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
23836                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
23837            throw new SecurityException("Caller must have the "
23838                    + SET_HARMFUL_APP_WARNINGS + " permission.");
23839        }
23840
23841        synchronized(mPackages) {
23842            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
23843            scheduleWritePackageRestrictionsLocked(userId);
23844        }
23845    }
23846
23847    @Nullable
23848    @Override
23849    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
23850        final int callingUid = Binder.getCallingUid();
23851        final int callingAppId = UserHandle.getAppId(callingUid);
23852
23853        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23854                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
23855
23856        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
23857                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
23858            throw new SecurityException("Caller must have the "
23859                    + SET_HARMFUL_APP_WARNINGS + " permission.");
23860        }
23861
23862        synchronized(mPackages) {
23863            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
23864        }
23865    }
23866}
23867
23868interface PackageSender {
23869    /**
23870     * @param userIds User IDs where the action occurred on a full application
23871     * @param instantUserIds User IDs where the action occurred on an instant application
23872     */
23873    void sendPackageBroadcast(final String action, final String pkg,
23874        final Bundle extras, final int flags, final String targetPkg,
23875        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
23876    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23877        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
23878    void notifyPackageAdded(String packageName);
23879    void notifyPackageRemoved(String packageName);
23880}
23881