PackageManagerService.java revision 86684240eb5753bb97c2cfc93d1d25fa1870f8f1
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_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.app.ActivityManager;
121import android.app.ActivityManagerInternal;
122import android.app.AppOpsManager;
123import android.app.IActivityManager;
124import android.app.ResourcesManager;
125import android.app.admin.IDevicePolicyManager;
126import android.app.admin.SecurityLog;
127import android.app.backup.IBackupManager;
128import android.content.BroadcastReceiver;
129import android.content.ComponentName;
130import android.content.ContentResolver;
131import android.content.Context;
132import android.content.IIntentReceiver;
133import android.content.Intent;
134import android.content.IntentFilter;
135import android.content.IntentSender;
136import android.content.IntentSender.SendIntentException;
137import android.content.ServiceConnection;
138import android.content.pm.ActivityInfo;
139import android.content.pm.ApplicationInfo;
140import android.content.pm.AppsQueryHelper;
141import android.content.pm.AuxiliaryResolveInfo;
142import android.content.pm.ChangedPackages;
143import android.content.pm.ComponentInfo;
144import android.content.pm.FallbackCategoryProvider;
145import android.content.pm.FeatureInfo;
146import android.content.pm.IDexModuleRegisterCallback;
147import android.content.pm.IOnPermissionsChangeListener;
148import android.content.pm.IPackageDataObserver;
149import android.content.pm.IPackageDeleteObserver;
150import android.content.pm.IPackageDeleteObserver2;
151import android.content.pm.IPackageInstallObserver2;
152import android.content.pm.IPackageInstaller;
153import android.content.pm.IPackageManager;
154import android.content.pm.IPackageManagerNative;
155import android.content.pm.IPackageMoveObserver;
156import android.content.pm.IPackageStatsObserver;
157import android.content.pm.InstantAppInfo;
158import android.content.pm.InstantAppRequest;
159import android.content.pm.InstantAppResolveInfo;
160import android.content.pm.InstrumentationInfo;
161import android.content.pm.IntentFilterVerificationInfo;
162import android.content.pm.KeySet;
163import android.content.pm.PackageCleanItem;
164import android.content.pm.PackageInfo;
165import android.content.pm.PackageInfoLite;
166import android.content.pm.PackageInstaller;
167import android.content.pm.PackageList;
168import android.content.pm.PackageManager;
169import android.content.pm.PackageManagerInternal;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal.PackageListObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageParser.ParseFlags;
178import android.content.pm.PackageParser.ServiceIntentInfo;
179import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
180import android.content.pm.PackageStats;
181import android.content.pm.PackageUserState;
182import android.content.pm.ParceledListSlice;
183import android.content.pm.PermissionGroupInfo;
184import android.content.pm.PermissionInfo;
185import android.content.pm.ProviderInfo;
186import android.content.pm.ResolveInfo;
187import android.content.pm.ServiceInfo;
188import android.content.pm.SharedLibraryInfo;
189import android.content.pm.Signature;
190import android.content.pm.UserInfo;
191import android.content.pm.VerifierDeviceIdentity;
192import android.content.pm.VerifierInfo;
193import android.content.pm.VersionedPackage;
194import android.content.pm.dex.ArtManager;
195import android.content.pm.dex.DexMetadataHelper;
196import android.content.pm.dex.IArtManager;
197import android.content.res.Resources;
198import android.database.ContentObserver;
199import android.graphics.Bitmap;
200import android.hardware.display.DisplayManager;
201import android.net.Uri;
202import android.os.Binder;
203import android.os.Build;
204import android.os.Bundle;
205import android.os.Debug;
206import android.os.Environment;
207import android.os.Environment.UserEnvironment;
208import android.os.FileUtils;
209import android.os.Handler;
210import android.os.IBinder;
211import android.os.Looper;
212import android.os.Message;
213import android.os.Parcel;
214import android.os.ParcelFileDescriptor;
215import android.os.PatternMatcher;
216import android.os.Process;
217import android.os.RemoteCallbackList;
218import android.os.RemoteException;
219import android.os.ResultReceiver;
220import android.os.SELinux;
221import android.os.ServiceManager;
222import android.os.ShellCallback;
223import android.os.SystemClock;
224import android.os.SystemProperties;
225import android.os.Trace;
226import android.os.UserHandle;
227import android.os.UserManager;
228import android.os.UserManagerInternal;
229import android.os.storage.IStorageManager;
230import android.os.storage.StorageEventListener;
231import android.os.storage.StorageManager;
232import android.os.storage.StorageManagerInternal;
233import android.os.storage.VolumeInfo;
234import android.os.storage.VolumeRecord;
235import android.provider.Settings.Global;
236import android.provider.Settings.Secure;
237import android.security.KeyStore;
238import android.security.SystemKeyStore;
239import android.service.pm.PackageServiceDumpProto;
240import android.system.ErrnoException;
241import android.system.Os;
242import android.text.TextUtils;
243import android.text.format.DateUtils;
244import android.util.ArrayMap;
245import android.util.ArraySet;
246import android.util.Base64;
247import android.util.ByteStringUtils;
248import android.util.DisplayMetrics;
249import android.util.EventLog;
250import android.util.ExceptionUtils;
251import android.util.Log;
252import android.util.LogPrinter;
253import android.util.LongSparseArray;
254import android.util.LongSparseLongArray;
255import android.util.MathUtils;
256import android.util.PackageUtils;
257import android.util.Pair;
258import android.util.PrintStreamPrinter;
259import android.util.Slog;
260import android.util.SparseArray;
261import android.util.SparseBooleanArray;
262import android.util.SparseIntArray;
263import android.util.TimingsTraceLog;
264import android.util.Xml;
265import android.util.jar.StrictJarFile;
266import android.util.proto.ProtoOutputStream;
267import android.view.Display;
268
269import com.android.internal.R;
270import com.android.internal.annotations.GuardedBy;
271import com.android.internal.app.IMediaContainerService;
272import com.android.internal.app.ResolverActivity;
273import com.android.internal.content.NativeLibraryHelper;
274import com.android.internal.content.PackageHelper;
275import com.android.internal.logging.MetricsLogger;
276import com.android.internal.os.IParcelFileDescriptorFactory;
277import com.android.internal.os.SomeArgs;
278import com.android.internal.os.Zygote;
279import com.android.internal.telephony.CarrierAppUtils;
280import com.android.internal.util.ArrayUtils;
281import com.android.internal.util.ConcurrentUtils;
282import com.android.internal.util.DumpUtils;
283import com.android.internal.util.FastXmlSerializer;
284import com.android.internal.util.IndentingPrintWriter;
285import com.android.internal.util.Preconditions;
286import com.android.internal.util.XmlUtils;
287import com.android.server.AttributeCache;
288import com.android.server.DeviceIdleController;
289import com.android.server.EventLogTags;
290import com.android.server.FgThread;
291import com.android.server.IntentResolver;
292import com.android.server.LocalServices;
293import com.android.server.LockGuard;
294import com.android.server.ServiceThread;
295import com.android.server.SystemConfig;
296import com.android.server.SystemServerInitThreadPool;
297import com.android.server.Watchdog;
298import com.android.server.net.NetworkPolicyManagerInternal;
299import com.android.server.pm.Installer.InstallerException;
300import com.android.server.pm.Settings.DatabaseVersion;
301import com.android.server.pm.Settings.VersionInfo;
302import com.android.server.pm.dex.ArtManagerService;
303import com.android.server.pm.dex.DexLogger;
304import com.android.server.pm.dex.DexManager;
305import com.android.server.pm.dex.DexoptOptions;
306import com.android.server.pm.dex.PackageDexUsage;
307import com.android.server.pm.permission.BasePermission;
308import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
309import com.android.server.pm.permission.PermissionManagerService;
310import com.android.server.pm.permission.PermissionManagerInternal;
311import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
312import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
313import com.android.server.pm.permission.PermissionsState;
314import com.android.server.pm.permission.PermissionsState.PermissionState;
315import com.android.server.security.VerityUtils;
316import com.android.server.storage.DeviceStorageMonitorInternal;
317
318import dalvik.system.CloseGuard;
319import dalvik.system.VMRuntime;
320
321import libcore.io.IoUtils;
322
323import org.xmlpull.v1.XmlPullParser;
324import org.xmlpull.v1.XmlPullParserException;
325import org.xmlpull.v1.XmlSerializer;
326
327import java.io.BufferedOutputStream;
328import java.io.ByteArrayInputStream;
329import java.io.ByteArrayOutputStream;
330import java.io.File;
331import java.io.FileDescriptor;
332import java.io.FileInputStream;
333import java.io.FileOutputStream;
334import java.io.FilenameFilter;
335import java.io.IOException;
336import java.io.PrintWriter;
337import java.lang.annotation.Retention;
338import java.lang.annotation.RetentionPolicy;
339import java.nio.charset.StandardCharsets;
340import java.security.DigestException;
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_INSTANT = 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    private static final int SE_UID = Process.SE_UID;
444
445    // Suffix used during package installation when copying/moving
446    // package apks to install directory.
447    private static final String INSTALL_PACKAGE_SUFFIX = "-";
448
449    static final int SCAN_NO_DEX = 1<<0;
450    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
451    static final int SCAN_NEW_INSTALL = 1<<2;
452    static final int SCAN_UPDATE_TIME = 1<<3;
453    static final int SCAN_BOOTING = 1<<4;
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    static final int SCAN_AS_PRODUCT = 1<<21;
470
471    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
472            SCAN_NO_DEX,
473            SCAN_UPDATE_SIGNATURE,
474            SCAN_NEW_INSTALL,
475            SCAN_UPDATE_TIME,
476            SCAN_BOOTING,
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 PRODUCT_OVERLAY_DIR = "/product/overlay";
575
576    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
577
578    /** Canonical intent used to identify what counts as a "web browser" app */
579    private static final Intent sBrowserIntent;
580    static {
581        sBrowserIntent = new Intent();
582        sBrowserIntent.setAction(Intent.ACTION_VIEW);
583        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
584        sBrowserIntent.setData(Uri.parse("http:"));
585        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
586    }
587
588    /**
589     * The set of all protected actions [i.e. those actions for which a high priority
590     * intent filter is disallowed].
591     */
592    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
593    static {
594        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
597        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
598    }
599
600    // Compilation reasons.
601    public static final int REASON_FIRST_BOOT = 0;
602    public static final int REASON_BOOT = 1;
603    public static final int REASON_INSTALL = 2;
604    public static final int REASON_BACKGROUND_DEXOPT = 3;
605    public static final int REASON_AB_OTA = 4;
606    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
607    public static final int REASON_SHARED = 6;
608
609    public static final int REASON_LAST = REASON_SHARED;
610
611    /**
612     * Version number for the package parser cache. Increment this whenever the format or
613     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
614     */
615    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
616
617    /**
618     * Whether the package parser cache is enabled.
619     */
620    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
621
622    /**
623     * Permissions required in order to receive instant application lifecycle broadcasts.
624     */
625    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
626            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed applications are stored */
665    private static final File sAppInstallDir =
666            new File(Environment.getDataDirectory(), "app");
667    /** Directory where installed application's 32-bit native libraries are copied. */
668    private static final File sAppLib32InstallDir =
669            new File(Environment.getDataDirectory(), "app-lib");
670    /** Directory where code and non-resource assets of forward-locked applications are stored */
671    private static final File sDrmAppPrivateInstallDir =
672            new File(Environment.getDataDirectory(), "app-private");
673
674    // ----------------------------------------------------------------
675
676    // Lock for state used when installing and doing other long running
677    // operations.  Methods that must be called with this lock held have
678    // the suffix "LI".
679    final Object mInstallLock = new Object();
680
681    // ----------------------------------------------------------------
682
683    // Keys are String (package name), values are Package.  This also serves
684    // as the lock for the global state.  Methods that must be called with
685    // this lock held have the prefix "LP".
686    @GuardedBy("mPackages")
687    final ArrayMap<String, PackageParser.Package> mPackages =
688            new ArrayMap<String, PackageParser.Package>();
689
690    final ArrayMap<String, Set<String>> mKnownCodebase =
691            new ArrayMap<String, Set<String>>();
692
693    // Keys are isolated uids and values are the uid of the application
694    // that created the isolated proccess.
695    @GuardedBy("mPackages")
696    final SparseIntArray mIsolatedOwners = new SparseIntArray();
697
698    /**
699     * Tracks new system packages [received in an OTA] that we expect to
700     * find updated user-installed versions. Keys are package name, values
701     * are package location.
702     */
703    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
704    /**
705     * Tracks high priority intent filters for protected actions. During boot, certain
706     * filter actions are protected and should never be allowed to have a high priority
707     * intent filter for them. However, there is one, and only one exception -- the
708     * setup wizard. It must be able to define a high priority intent filter for these
709     * actions to ensure there are no escapes from the wizard. We need to delay processing
710     * of these during boot as we need to look at all of the system packages in order
711     * to know which component is the setup wizard.
712     */
713    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
714    /**
715     * Whether or not processing protected filters should be deferred.
716     */
717    private boolean mDeferProtectedFilters = true;
718
719    /**
720     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
721     */
722    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
723    /**
724     * Whether or not system app permissions should be promoted from install to runtime.
725     */
726    boolean mPromoteSystemApps;
727
728    @GuardedBy("mPackages")
729    final Settings mSettings;
730
731    /**
732     * Set of package names that are currently "frozen", which means active
733     * surgery is being done on the code/data for that package. The platform
734     * will refuse to launch frozen packages to avoid race conditions.
735     *
736     * @see PackageFreezer
737     */
738    @GuardedBy("mPackages")
739    final ArraySet<String> mFrozenPackages = new ArraySet<>();
740
741    final ProtectedPackages mProtectedPackages;
742
743    @GuardedBy("mLoadedVolumes")
744    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
745
746    boolean mFirstBoot;
747
748    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
749
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    private final InstantAppRegistry mInstantAppRegistry;
754
755    @GuardedBy("mPackages")
756    int mChangedPackagesSequenceNumber;
757    /**
758     * List of changed [installed, removed or updated] packages.
759     * mapping from user id -> sequence number -> package name
760     */
761    @GuardedBy("mPackages")
762    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
763    /**
764     * The sequence number of the last change to a package.
765     * mapping from user id -> package name -> sequence number
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
769
770    @GuardedBy("mPackages")
771    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
801                String targetPackageName, String targetPath) {
802            if ("android".equals(targetPackageName)) {
803                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
804                // native AssetManager.
805                return null;
806            }
807            List<PackageParser.Package> overlayPackages =
808                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
809            if (overlayPackages == null || overlayPackages.isEmpty()) {
810                return null;
811            }
812            List<String> overlayPathList = null;
813            for (PackageParser.Package overlayPackage : overlayPackages) {
814                if (targetPath == null) {
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                    continue;
820                }
821
822                try {
823                    // Creates idmaps for system to parse correctly the Android manifest of the
824                    // target package.
825                    //
826                    // OverlayManagerService will update each of them with a correct gid from its
827                    // target package app id.
828                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
829                            UserHandle.getSharedAppGid(
830                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
831                    if (overlayPathList == null) {
832                        overlayPathList = new ArrayList<String>();
833                    }
834                    overlayPathList.add(overlayPackage.baseCodePath);
835                } catch (InstallerException e) {
836                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
837                            overlayPackage.baseCodePath);
838                }
839            }
840            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
841        }
842
843        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
844            synchronized (mPackages) {
845                return getStaticOverlayPathsLocked(
846                        mPackages.values(), targetPackageName, targetPath);
847            }
848        }
849
850        @Override public final String[] getOverlayApks(String targetPackageName) {
851            return getStaticOverlayPaths(targetPackageName, null);
852        }
853
854        @Override public final String[] getOverlayPaths(String targetPackageName,
855                String targetPath) {
856            return getStaticOverlayPaths(targetPackageName, targetPath);
857        }
858    }
859
860    class ParallelPackageParserCallback extends PackageParserCallback {
861        List<PackageParser.Package> mOverlayPackages = null;
862
863        void findStaticOverlayPackages() {
864            synchronized (mPackages) {
865                for (PackageParser.Package p : mPackages.values()) {
866                    if (p.mOverlayIsStatic) {
867                        if (mOverlayPackages == null) {
868                            mOverlayPackages = new ArrayList<PackageParser.Package>();
869                        }
870                        mOverlayPackages.add(p);
871                    }
872                }
873            }
874        }
875
876        @Override
877        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
878            // We can trust mOverlayPackages without holding mPackages because package uninstall
879            // can't happen while running parallel parsing.
880            // Moreover holding mPackages on each parsing thread causes dead-lock.
881            return mOverlayPackages == null ? null :
882                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
883        }
884    }
885
886    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
887    final ParallelPackageParserCallback mParallelPackageParserCallback =
888            new ParallelPackageParserCallback();
889
890    public static final class SharedLibraryEntry {
891        public final @Nullable String path;
892        public final @Nullable String apk;
893        public final @NonNull SharedLibraryInfo info;
894
895        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
896                String declaringPackageName, long declaringPackageVersionCode) {
897            path = _path;
898            apk = _apk;
899            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
900                    declaringPackageName, declaringPackageVersionCode), null);
901        }
902    }
903
904    // Currently known shared libraries.
905    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
906    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
907            new ArrayMap<>();
908
909    // All available activities, for your resolving pleasure.
910    final ActivityIntentResolver mActivities =
911            new ActivityIntentResolver();
912
913    // All available receivers, for your resolving pleasure.
914    final ActivityIntentResolver mReceivers =
915            new ActivityIntentResolver();
916
917    // All available services, for your resolving pleasure.
918    final ServiceIntentResolver mServices = new ServiceIntentResolver();
919
920    // All available providers, for your resolving pleasure.
921    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
922
923    // Mapping from provider base names (first directory in content URI codePath)
924    // to the provider information.
925    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
926            new ArrayMap<String, PackageParser.Provider>();
927
928    // Mapping from instrumentation class names to info about them.
929    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
930            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
931
932    // Packages whose data we have transfered into another package, thus
933    // should no longer exist.
934    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
935
936    // Broadcast actions that are only available to the system.
937    @GuardedBy("mProtectedBroadcasts")
938    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
939
940    /** List of packages waiting for verification. */
941    final SparseArray<PackageVerificationState> mPendingVerification
942            = new SparseArray<PackageVerificationState>();
943
944    final PackageInstallerService mInstallerService;
945
946    final ArtManagerService mArtManagerService;
947
948    private final PackageDexOptimizer mPackageDexOptimizer;
949    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
950    // is used by other apps).
951    private final DexManager mDexManager;
952
953    private AtomicInteger mNextMoveId = new AtomicInteger();
954    private final MoveCallbacks mMoveCallbacks;
955
956    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
957
958    // Cache of users who need badging.
959    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
960
961    /** Token for keys in mPendingVerification. */
962    private int mPendingVerificationToken = 0;
963
964    volatile boolean mSystemReady;
965    volatile boolean mSafeMode;
966    volatile boolean mHasSystemUidErrors;
967    private volatile boolean mEphemeralAppsDisabled;
968
969    ApplicationInfo mAndroidApplication;
970    final ActivityInfo mResolveActivity = new ActivityInfo();
971    final ResolveInfo mResolveInfo = new ResolveInfo();
972    ComponentName mResolveComponentName;
973    PackageParser.Package mPlatformPackage;
974    ComponentName mCustomResolverComponentName;
975
976    boolean mResolverReplaced = false;
977
978    private final @Nullable ComponentName mIntentFilterVerifierComponent;
979    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
980
981    private int mIntentFilterVerificationToken = 0;
982
983    /** The service connection to the ephemeral resolver */
984    final InstantAppResolverConnection mInstantAppResolverConnection;
985    /** Component used to show resolver settings for Instant Apps */
986    final ComponentName mInstantAppResolverSettingsComponent;
987
988    /** Activity used to install instant applications */
989    ActivityInfo mInstantAppInstallerActivity;
990    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
991
992    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
993            = new SparseArray<IntentFilterVerificationState>();
994
995    // TODO remove this and go through mPermissonManager directly
996    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
997    private final PermissionManagerInternal mPermissionManager;
998
999    // List of packages names to keep cached, even if they are uninstalled for all users
1000    private List<String> mKeepUninstalledPackages;
1001
1002    private UserManagerInternal mUserManagerInternal;
1003    private ActivityManagerInternal mActivityManagerInternal;
1004
1005    private DeviceIdleController.LocalService mDeviceIdleController;
1006
1007    private File mCacheDir;
1008
1009    private Future<?> mPrepareAppDataFuture;
1010
1011    private static class IFVerificationParams {
1012        PackageParser.Package pkg;
1013        boolean replacing;
1014        int userId;
1015        int verifierUid;
1016
1017        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1018                int _userId, int _verifierUid) {
1019            pkg = _pkg;
1020            replacing = _replacing;
1021            userId = _userId;
1022            replacing = _replacing;
1023            verifierUid = _verifierUid;
1024        }
1025    }
1026
1027    private interface IntentFilterVerifier<T extends IntentFilter> {
1028        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1029                                               T filter, String packageName);
1030        void startVerifications(int userId);
1031        void receiveVerificationResponse(int verificationId);
1032    }
1033
1034    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1035        private Context mContext;
1036        private ComponentName mIntentFilterVerifierComponent;
1037        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1038
1039        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1040            mContext = context;
1041            mIntentFilterVerifierComponent = verifierComponent;
1042        }
1043
1044        private String getDefaultScheme() {
1045            return IntentFilter.SCHEME_HTTPS;
1046        }
1047
1048        @Override
1049        public void startVerifications(int userId) {
1050            // Launch verifications requests
1051            int count = mCurrentIntentFilterVerifications.size();
1052            for (int n=0; n<count; n++) {
1053                int verificationId = mCurrentIntentFilterVerifications.get(n);
1054                final IntentFilterVerificationState ivs =
1055                        mIntentFilterVerificationStates.get(verificationId);
1056
1057                String packageName = ivs.getPackageName();
1058
1059                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1060                final int filterCount = filters.size();
1061                ArraySet<String> domainsSet = new ArraySet<>();
1062                for (int m=0; m<filterCount; m++) {
1063                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1064                    domainsSet.addAll(filter.getHostsList());
1065                }
1066                synchronized (mPackages) {
1067                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1068                            packageName, domainsSet) != null) {
1069                        scheduleWriteSettingsLocked();
1070                    }
1071                }
1072                sendVerificationRequest(verificationId, ivs);
1073            }
1074            mCurrentIntentFilterVerifications.clear();
1075        }
1076
1077        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1078            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1081                    verificationId);
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1084                    getDefaultScheme());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1087                    ivs.getHostsString());
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1090                    ivs.getPackageName());
1091            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1092            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1093
1094            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1095            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1096                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1097                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1098
1099            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1100            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1101                    "Sending IntentFilter verification broadcast");
1102        }
1103
1104        public void receiveVerificationResponse(int verificationId) {
1105            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1106
1107            final boolean verified = ivs.isVerified();
1108
1109            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1110            final int count = filters.size();
1111            if (DEBUG_DOMAIN_VERIFICATION) {
1112                Slog.i(TAG, "Received verification response " + verificationId
1113                        + " for " + count + " filters, verified=" + verified);
1114            }
1115            for (int n=0; n<count; n++) {
1116                PackageParser.ActivityIntentInfo filter = filters.get(n);
1117                filter.setVerified(verified);
1118
1119                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1120                        + " verified with result:" + verified + " and hosts:"
1121                        + ivs.getHostsString());
1122            }
1123
1124            mIntentFilterVerificationStates.remove(verificationId);
1125
1126            final String packageName = ivs.getPackageName();
1127            IntentFilterVerificationInfo ivi = null;
1128
1129            synchronized (mPackages) {
1130                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1131            }
1132            if (ivi == null) {
1133                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1134                        + verificationId + " packageName:" + packageName);
1135                return;
1136            }
1137            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1138                    "Updating IntentFilterVerificationInfo for package " + packageName
1139                            +" verificationId:" + verificationId);
1140
1141            synchronized (mPackages) {
1142                if (verified) {
1143                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1144                } else {
1145                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1146                }
1147                scheduleWriteSettingsLocked();
1148
1149                final int userId = ivs.getUserId();
1150                if (userId != UserHandle.USER_ALL) {
1151                    final int userStatus =
1152                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1153
1154                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1155                    boolean needUpdate = false;
1156
1157                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1158                    // already been set by the User thru the Disambiguation dialog
1159                    switch (userStatus) {
1160                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1161                            if (verified) {
1162                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1163                            } else {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1165                            }
1166                            needUpdate = true;
1167                            break;
1168
1169                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1170                            if (verified) {
1171                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1172                                needUpdate = true;
1173                            }
1174                            break;
1175
1176                        default:
1177                            // Nothing to do
1178                    }
1179
1180                    if (needUpdate) {
1181                        mSettings.updateIntentFilterVerificationStatusLPw(
1182                                packageName, updatedStatus, userId);
1183                        scheduleWritePackageRestrictionsLocked(userId);
1184                    }
1185                }
1186            }
1187        }
1188
1189        @Override
1190        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1191                    ActivityIntentInfo filter, String packageName) {
1192            if (!hasValidDomains(filter)) {
1193                return false;
1194            }
1195            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1196            if (ivs == null) {
1197                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1198                        packageName);
1199            }
1200            if (DEBUG_DOMAIN_VERIFICATION) {
1201                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1202            }
1203            ivs.addFilter(filter);
1204            return true;
1205        }
1206
1207        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1208                int userId, int verificationId, String packageName) {
1209            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1210                    verifierUid, userId, packageName);
1211            ivs.setPendingState();
1212            synchronized (mPackages) {
1213                mIntentFilterVerificationStates.append(verificationId, ivs);
1214                mCurrentIntentFilterVerifications.add(verificationId);
1215            }
1216            return ivs;
1217        }
1218    }
1219
1220    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1221        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1222                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1223                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1224    }
1225
1226    // Set of pending broadcasts for aggregating enable/disable of components.
1227    static class PendingPackageBroadcasts {
1228        // for each user id, a map of <package name -> components within that package>
1229        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1230
1231        public PendingPackageBroadcasts() {
1232            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1233        }
1234
1235        public ArrayList<String> get(int userId, String packageName) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            return packages.get(packageName);
1238        }
1239
1240        public void put(int userId, String packageName, ArrayList<String> components) {
1241            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1242            packages.put(packageName, components);
1243        }
1244
1245        public void remove(int userId, String packageName) {
1246            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1247            if (packages != null) {
1248                packages.remove(packageName);
1249            }
1250        }
1251
1252        public void remove(int userId) {
1253            mUidMap.remove(userId);
1254        }
1255
1256        public int userIdCount() {
1257            return mUidMap.size();
1258        }
1259
1260        public int userIdAt(int n) {
1261            return mUidMap.keyAt(n);
1262        }
1263
1264        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1265            return mUidMap.get(userId);
1266        }
1267
1268        public int size() {
1269            // total number of pending broadcast entries across all userIds
1270            int num = 0;
1271            for (int i = 0; i< mUidMap.size(); i++) {
1272                num += mUidMap.valueAt(i).size();
1273            }
1274            return num;
1275        }
1276
1277        public void clear() {
1278            mUidMap.clear();
1279        }
1280
1281        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1282            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1283            if (map == null) {
1284                map = new ArrayMap<String, ArrayList<String>>();
1285                mUidMap.put(userId, map);
1286            }
1287            return map;
1288        }
1289    }
1290    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1291
1292    // Service Connection to remote media container service to copy
1293    // package uri's from external media onto secure containers
1294    // or internal storage.
1295    private IMediaContainerService mContainerService = null;
1296
1297    static final int SEND_PENDING_BROADCAST = 1;
1298    static final int MCS_BOUND = 3;
1299    static final int END_COPY = 4;
1300    static final int INIT_COPY = 5;
1301    static final int MCS_UNBIND = 6;
1302    static final int START_CLEANING_PACKAGE = 7;
1303    static final int FIND_INSTALL_LOC = 8;
1304    static final int POST_INSTALL = 9;
1305    static final int MCS_RECONNECT = 10;
1306    static final int MCS_GIVE_UP = 11;
1307    static final int WRITE_SETTINGS = 13;
1308    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1309    static final int PACKAGE_VERIFIED = 15;
1310    static final int CHECK_PENDING_VERIFICATION = 16;
1311    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1312    static final int INTENT_FILTER_VERIFIED = 18;
1313    static final int WRITE_PACKAGE_LIST = 19;
1314    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1315
1316    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1317
1318    // Delay time in millisecs
1319    static final int BROADCAST_DELAY = 10 * 1000;
1320
1321    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1322            2 * 60 * 60 * 1000L; /* two hours */
1323
1324    static UserManagerService sUserManager;
1325
1326    // Stores a list of users whose package restrictions file needs to be updated
1327    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1328
1329    final private DefaultContainerConnection mDefContainerConn =
1330            new DefaultContainerConnection();
1331    class DefaultContainerConnection implements ServiceConnection {
1332        public void onServiceConnected(ComponentName name, IBinder service) {
1333            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1334            final IMediaContainerService imcs = IMediaContainerService.Stub
1335                    .asInterface(Binder.allowBlocking(service));
1336            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1337        }
1338
1339        public void onServiceDisconnected(ComponentName name) {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1341        }
1342    }
1343
1344    // Recordkeeping of restore-after-install operations that are currently in flight
1345    // between the Package Manager and the Backup Manager
1346    static class PostInstallData {
1347        public InstallArgs args;
1348        public PackageInstalledInfo res;
1349
1350        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1351            args = _a;
1352            res = _r;
1353        }
1354    }
1355
1356    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1357    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1358
1359    // XML tags for backup/restore of various bits of state
1360    private static final String TAG_PREFERRED_BACKUP = "pa";
1361    private static final String TAG_DEFAULT_APPS = "da";
1362    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1363
1364    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1365    private static final String TAG_ALL_GRANTS = "rt-grants";
1366    private static final String TAG_GRANT = "grant";
1367    private static final String ATTR_PACKAGE_NAME = "pkg";
1368
1369    private static final String TAG_PERMISSION = "perm";
1370    private static final String ATTR_PERMISSION_NAME = "name";
1371    private static final String ATTR_IS_GRANTED = "g";
1372    private static final String ATTR_USER_SET = "set";
1373    private static final String ATTR_USER_FIXED = "fixed";
1374    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1375
1376    // System/policy permission grants are not backed up
1377    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1378            FLAG_PERMISSION_POLICY_FIXED
1379            | FLAG_PERMISSION_SYSTEM_FIXED
1380            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1381
1382    // And we back up these user-adjusted states
1383    private static final int USER_RUNTIME_GRANT_MASK =
1384            FLAG_PERMISSION_USER_SET
1385            | FLAG_PERMISSION_USER_FIXED
1386            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1387
1388    final @Nullable String mRequiredVerifierPackage;
1389    final @NonNull String mRequiredInstallerPackage;
1390    final @NonNull String mRequiredUninstallerPackage;
1391    final @Nullable String mSetupWizardPackage;
1392    final @Nullable String mStorageManagerPackage;
1393    final @NonNull String mServicesSystemSharedLibraryPackageName;
1394    final @NonNull String mSharedSystemSharedLibraryPackageName;
1395
1396    private final PackageUsage mPackageUsage = new PackageUsage();
1397    private final CompilerStats mCompilerStats = new CompilerStats();
1398
1399    class PackageHandler extends Handler {
1400        private boolean mBound = false;
1401        final ArrayList<HandlerParams> mPendingInstalls =
1402            new ArrayList<HandlerParams>();
1403
1404        private boolean connectToService() {
1405            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1406                    " DefaultContainerService");
1407            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1410                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                mBound = true;
1413                return true;
1414            }
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416            return false;
1417        }
1418
1419        private void disconnectService() {
1420            mContainerService = null;
1421            mBound = false;
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            mContext.unbindService(mDefContainerConn);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425        }
1426
1427        PackageHandler(Looper looper) {
1428            super(looper);
1429        }
1430
1431        public void handleMessage(Message msg) {
1432            try {
1433                doHandleMessage(msg);
1434            } finally {
1435                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            }
1437        }
1438
1439        void doHandleMessage(Message msg) {
1440            switch (msg.what) {
1441                case INIT_COPY: {
1442                    HandlerParams params = (HandlerParams) msg.obj;
1443                    int idx = mPendingInstalls.size();
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1445                    // If a bind was already initiated we dont really
1446                    // need to do anything. The pending install
1447                    // will be processed later on.
1448                    if (!mBound) {
1449                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                System.identityHashCode(mHandler));
1451                        // If this is the only one pending we might
1452                        // have to bind to the service again.
1453                        if (!connectToService()) {
1454                            Slog.e(TAG, "Failed to bind to media container service");
1455                            params.serviceError();
1456                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                    System.identityHashCode(mHandler));
1458                            if (params.traceMethod != null) {
1459                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1460                                        params.traceCookie);
1461                            }
1462                            return;
1463                        } else {
1464                            // Once we bind to the service, the first
1465                            // pending request will be processed.
1466                            mPendingInstalls.add(idx, params);
1467                        }
1468                    } else {
1469                        mPendingInstalls.add(idx, params);
1470                        // Already bound to the service. Just make
1471                        // sure we trigger off processing the first request.
1472                        if (idx == 0) {
1473                            mHandler.sendEmptyMessage(MCS_BOUND);
1474                        }
1475                    }
1476                    break;
1477                }
1478                case MCS_BOUND: {
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1480                    if (msg.obj != null) {
1481                        mContainerService = (IMediaContainerService) msg.obj;
1482                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                System.identityHashCode(mHandler));
1484                    }
1485                    if (mContainerService == null) {
1486                        if (!mBound) {
1487                            // Something seriously wrong since we are not bound and we are not
1488                            // waiting for connection. Bail out.
1489                            Slog.e(TAG, "Cannot bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                                if (params.traceMethod != null) {
1496                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1497                                            params.traceMethod, params.traceCookie);
1498                                }
1499                                return;
1500                            }
1501                            mPendingInstalls.clear();
1502                        } else {
1503                            Slog.w(TAG, "Waiting to connect to media container service");
1504                        }
1505                    } else if (mPendingInstalls.size() > 0) {
1506                        HandlerParams params = mPendingInstalls.get(0);
1507                        if (params != null) {
1508                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                    System.identityHashCode(params));
1510                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1511                            if (params.startCopy()) {
1512                                // We are done...  look for more work or to
1513                                // go idle.
1514                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                        "Checking for more work or unbind...");
1516                                // Delete pending install
1517                                if (mPendingInstalls.size() > 0) {
1518                                    mPendingInstalls.remove(0);
1519                                }
1520                                if (mPendingInstalls.size() == 0) {
1521                                    if (mBound) {
1522                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                                "Posting delayed MCS_UNBIND");
1524                                        removeMessages(MCS_UNBIND);
1525                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1526                                        // Unbind after a little delay, to avoid
1527                                        // continual thrashing.
1528                                        sendMessageDelayed(ubmsg, 10000);
1529                                    }
1530                                } else {
1531                                    // There are more pending requests in queue.
1532                                    // Just post MCS_BOUND message to trigger processing
1533                                    // of next pending install.
1534                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                            "Posting MCS_BOUND for next work");
1536                                    mHandler.sendEmptyMessage(MCS_BOUND);
1537                                }
1538                            }
1539                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1540                        }
1541                    } else {
1542                        // Should never happen ideally.
1543                        Slog.w(TAG, "Empty queue");
1544                    }
1545                    break;
1546                }
1547                case MCS_RECONNECT: {
1548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1549                    if (mPendingInstalls.size() > 0) {
1550                        if (mBound) {
1551                            disconnectService();
1552                        }
1553                        if (!connectToService()) {
1554                            Slog.e(TAG, "Failed to bind to media container service");
1555                            for (HandlerParams params : mPendingInstalls) {
1556                                // Indicate service bind error
1557                                params.serviceError();
1558                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1559                                        System.identityHashCode(params));
1560                            }
1561                            mPendingInstalls.clear();
1562                        }
1563                    }
1564                    break;
1565                }
1566                case MCS_UNBIND: {
1567                    // If there is no actual work left, then time to unbind.
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1569
1570                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1571                        if (mBound) {
1572                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1573
1574                            disconnectService();
1575                        }
1576                    } else if (mPendingInstalls.size() > 0) {
1577                        // There are more pending requests in queue.
1578                        // Just post MCS_BOUND message to trigger processing
1579                        // of next pending install.
1580                        mHandler.sendEmptyMessage(MCS_BOUND);
1581                    }
1582
1583                    break;
1584                }
1585                case MCS_GIVE_UP: {
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1587                    HandlerParams params = mPendingInstalls.remove(0);
1588                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1589                            System.identityHashCode(params));
1590                    break;
1591                }
1592                case SEND_PENDING_BROADCAST: {
1593                    String packages[];
1594                    ArrayList<String> components[];
1595                    int size = 0;
1596                    int uids[];
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        if (mPendingBroadcasts == null) {
1600                            return;
1601                        }
1602                        size = mPendingBroadcasts.size();
1603                        if (size <= 0) {
1604                            // Nothing to be done. Just return
1605                            return;
1606                        }
1607                        packages = new String[size];
1608                        components = new ArrayList[size];
1609                        uids = new int[size];
1610                        int i = 0;  // filling out the above arrays
1611
1612                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1613                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1614                            Iterator<Map.Entry<String, ArrayList<String>>> it
1615                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1616                                            .entrySet().iterator();
1617                            while (it.hasNext() && i < size) {
1618                                Map.Entry<String, ArrayList<String>> ent = it.next();
1619                                packages[i] = ent.getKey();
1620                                components[i] = ent.getValue();
1621                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1622                                uids[i] = (ps != null)
1623                                        ? UserHandle.getUid(packageUserId, ps.appId)
1624                                        : -1;
1625                                i++;
1626                            }
1627                        }
1628                        size = i;
1629                        mPendingBroadcasts.clear();
1630                    }
1631                    // Send broadcasts
1632                    for (int i = 0; i < size; i++) {
1633                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1634                    }
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1636                    break;
1637                }
1638                case START_CLEANING_PACKAGE: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    final String packageName = (String)msg.obj;
1641                    final int userId = msg.arg1;
1642                    final boolean andCode = msg.arg2 != 0;
1643                    synchronized (mPackages) {
1644                        if (userId == UserHandle.USER_ALL) {
1645                            int[] users = sUserManager.getUserIds();
1646                            for (int user : users) {
1647                                mSettings.addPackageToCleanLPw(
1648                                        new PackageCleanItem(user, packageName, andCode));
1649                            }
1650                        } else {
1651                            mSettings.addPackageToCleanLPw(
1652                                    new PackageCleanItem(userId, packageName, andCode));
1653                        }
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    startCleaningPackages();
1657                } break;
1658                case POST_INSTALL: {
1659                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1660
1661                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1662                    final boolean didRestore = (msg.arg2 != 0);
1663                    mRunningInstalls.delete(msg.arg1);
1664
1665                    if (data != null) {
1666                        InstallArgs args = data.args;
1667                        PackageInstalledInfo parentRes = data.res;
1668
1669                        final boolean grantPermissions = (args.installFlags
1670                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1671                        final boolean killApp = (args.installFlags
1672                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1673                        final boolean virtualPreload = ((args.installFlags
1674                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1675                        final String[] grantedPermissions = args.installGrantPermissions;
1676
1677                        // Handle the parent package
1678                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1679                                virtualPreload, grantedPermissions, didRestore,
1680                                args.installerPackageName, args.observer);
1681
1682                        // Handle the child packages
1683                        final int childCount = (parentRes.addedChildPackages != null)
1684                                ? parentRes.addedChildPackages.size() : 0;
1685                        for (int i = 0; i < childCount; i++) {
1686                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1687                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1688                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1689                                    args.installerPackageName, args.observer);
1690                        }
1691
1692                        // Log tracing if needed
1693                        if (args.traceMethod != null) {
1694                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1695                                    args.traceCookie);
1696                        }
1697                    } else {
1698                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1699                    }
1700
1701                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1702                } break;
1703                case WRITE_SETTINGS: {
1704                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1705                    synchronized (mPackages) {
1706                        removeMessages(WRITE_SETTINGS);
1707                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1708                        mSettings.writeLPr();
1709                        mDirtyUsers.clear();
1710                    }
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1712                } break;
1713                case WRITE_PACKAGE_RESTRICTIONS: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1717                        for (int userId : mDirtyUsers) {
1718                            mSettings.writePackageRestrictionsLPr(userId);
1719                        }
1720                        mDirtyUsers.clear();
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case WRITE_PACKAGE_LIST: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_PACKAGE_LIST);
1728                        mSettings.writePackageListLPr(msg.arg1);
1729                    }
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1731                } break;
1732                case CHECK_PENDING_VERIFICATION: {
1733                    final int verificationId = msg.arg1;
1734                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1735
1736                    if ((state != null) && !state.timeoutExtended()) {
1737                        final InstallArgs args = state.getInstallArgs();
1738                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1739
1740                        Slog.i(TAG, "Verification timed out for " + originUri);
1741                        mPendingVerification.remove(verificationId);
1742
1743                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1744
1745                        final UserHandle user = args.getUser();
1746                        if (getDefaultVerificationResponse(user)
1747                                == PackageManager.VERIFICATION_ALLOW) {
1748                            Slog.i(TAG, "Continuing with installation of " + originUri);
1749                            state.setVerifierResponse(Binder.getCallingUid(),
1750                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    PackageManager.VERIFICATION_ALLOW, user);
1753                            try {
1754                                ret = args.copyApk(mContainerService, true);
1755                            } catch (RemoteException e) {
1756                                Slog.e(TAG, "Could not contact the ContainerService");
1757                            }
1758                        } else {
1759                            broadcastPackageVerified(verificationId, originUri,
1760                                    PackageManager.VERIFICATION_REJECT, user);
1761                        }
1762
1763                        Trace.asyncTraceEnd(
1764                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1765
1766                        processPendingInstall(args, ret);
1767                        mHandler.sendEmptyMessage(MCS_UNBIND);
1768                    }
1769                    break;
1770                }
1771                case PACKAGE_VERIFIED: {
1772                    final int verificationId = msg.arg1;
1773
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775                    if (state == null) {
1776                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1777                        break;
1778                    }
1779
1780                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1781
1782                    state.setVerifierResponse(response.callerUid, response.code);
1783
1784                    if (state.isVerificationComplete()) {
1785                        mPendingVerification.remove(verificationId);
1786
1787                        final InstallArgs args = state.getInstallArgs();
1788                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1789
1790                        int ret;
1791                        if (state.isInstallAllowed()) {
1792                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    response.code, state.getInstallArgs().getUser());
1795                            try {
1796                                ret = args.copyApk(mContainerService, true);
1797                            } catch (RemoteException e) {
1798                                Slog.e(TAG, "Could not contact the ContainerService");
1799                            }
1800                        } else {
1801                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1802                        }
1803
1804                        Trace.asyncTraceEnd(
1805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806
1807                        processPendingInstall(args, ret);
1808                        mHandler.sendEmptyMessage(MCS_UNBIND);
1809                    }
1810
1811                    break;
1812                }
1813                case START_INTENT_FILTER_VERIFICATIONS: {
1814                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1815                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1816                            params.replacing, params.pkg);
1817                    break;
1818                }
1819                case INTENT_FILTER_VERIFIED: {
1820                    final int verificationId = msg.arg1;
1821
1822                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1823                            verificationId);
1824                    if (state == null) {
1825                        Slog.w(TAG, "Invalid IntentFilter verification token "
1826                                + verificationId + " received");
1827                        break;
1828                    }
1829
1830                    final int userId = state.getUserId();
1831
1832                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1833                            "Processing IntentFilter verification with token:"
1834                            + verificationId + " and userId:" + userId);
1835
1836                    final IntentFilterVerificationResponse response =
1837                            (IntentFilterVerificationResponse) msg.obj;
1838
1839                    state.setVerifierResponse(response.callerUid, response.code);
1840
1841                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1842                            "IntentFilter verification with token:" + verificationId
1843                            + " and userId:" + userId
1844                            + " is settings verifier response with response code:"
1845                            + response.code);
1846
1847                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1848                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1849                                + response.getFailedDomainsString());
1850                    }
1851
1852                    if (state.isVerificationComplete()) {
1853                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1854                    } else {
1855                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                                "IntentFilter verification with token:" + verificationId
1857                                + " was not said to be complete");
1858                    }
1859
1860                    break;
1861                }
1862                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1863                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1864                            mInstantAppResolverConnection,
1865                            (InstantAppRequest) msg.obj,
1866                            mInstantAppInstallerActivity,
1867                            mHandler);
1868                }
1869            }
1870        }
1871    }
1872
1873    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1874        @Override
1875        public void onGidsChanged(int appId, int userId) {
1876            mHandler.post(new Runnable() {
1877                @Override
1878                public void run() {
1879                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1880                }
1881            });
1882        }
1883        @Override
1884        public void onPermissionGranted(int uid, int userId) {
1885            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1886
1887            // Not critical; if this is lost, the application has to request again.
1888            synchronized (mPackages) {
1889                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1890            }
1891        }
1892        @Override
1893        public void onInstallPermissionGranted() {
1894            synchronized (mPackages) {
1895                scheduleWriteSettingsLocked();
1896            }
1897        }
1898        @Override
1899        public void onPermissionRevoked(int uid, int userId) {
1900            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1901
1902            synchronized (mPackages) {
1903                // Critical; after this call the application should never have the permission
1904                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1905            }
1906
1907            final int appId = UserHandle.getAppId(uid);
1908            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1909        }
1910        @Override
1911        public void onInstallPermissionRevoked() {
1912            synchronized (mPackages) {
1913                scheduleWriteSettingsLocked();
1914            }
1915        }
1916        @Override
1917        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1918            synchronized (mPackages) {
1919                for (int userId : updatedUserIds) {
1920                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1921                }
1922            }
1923        }
1924        @Override
1925        public void onInstallPermissionUpdated() {
1926            synchronized (mPackages) {
1927                scheduleWriteSettingsLocked();
1928            }
1929        }
1930        @Override
1931        public void onPermissionRemoved() {
1932            synchronized (mPackages) {
1933                mSettings.writeLPr();
1934            }
1935        }
1936    };
1937
1938    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1939            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1940            boolean launchedForRestore, String installerPackage,
1941            IPackageInstallObserver2 installObserver) {
1942        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1943            // Send the removed broadcasts
1944            if (res.removedInfo != null) {
1945                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1946            }
1947
1948            // Now that we successfully installed the package, grant runtime
1949            // permissions if requested before broadcasting the install. Also
1950            // for legacy apps in permission review mode we clear the permission
1951            // review flag which is used to emulate runtime permissions for
1952            // legacy apps.
1953            if (grantPermissions) {
1954                final int callingUid = Binder.getCallingUid();
1955                mPermissionManager.grantRequestedRuntimePermissions(
1956                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1957                        mPermissionCallback);
1958            }
1959
1960            final boolean update = res.removedInfo != null
1961                    && res.removedInfo.removedPackage != null;
1962            final String installerPackageName =
1963                    res.installerPackageName != null
1964                            ? res.installerPackageName
1965                            : res.removedInfo != null
1966                                    ? res.removedInfo.installerPackageName
1967                                    : null;
1968
1969            // If this is the first time we have child packages for a disabled privileged
1970            // app that had no children, we grant requested runtime permissions to the new
1971            // children if the parent on the system image had them already granted.
1972            if (res.pkg.parentPackage != null) {
1973                final int callingUid = Binder.getCallingUid();
1974                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1975                        res.pkg, callingUid, mPermissionCallback);
1976            }
1977
1978            synchronized (mPackages) {
1979                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1980            }
1981
1982            final String packageName = res.pkg.applicationInfo.packageName;
1983
1984            // Determine the set of users who are adding this package for
1985            // the first time vs. those who are seeing an update.
1986            int[] firstUserIds = EMPTY_INT_ARRAY;
1987            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1988            int[] updateUserIds = EMPTY_INT_ARRAY;
1989            int[] instantUserIds = EMPTY_INT_ARRAY;
1990            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1991            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1992            for (int newUser : res.newUsers) {
1993                final boolean isInstantApp = ps.getInstantApp(newUser);
1994                if (allNewUsers) {
1995                    if (isInstantApp) {
1996                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1997                    } else {
1998                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1999                    }
2000                    continue;
2001                }
2002                boolean isNew = true;
2003                for (int origUser : res.origUsers) {
2004                    if (origUser == newUser) {
2005                        isNew = false;
2006                        break;
2007                    }
2008                }
2009                if (isNew) {
2010                    if (isInstantApp) {
2011                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2012                    } else {
2013                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2014                    }
2015                } else {
2016                    if (isInstantApp) {
2017                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2018                    } else {
2019                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2020                    }
2021                }
2022            }
2023
2024            // Send installed broadcasts if the package is not a static shared lib.
2025            if (res.pkg.staticSharedLibName == null) {
2026                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2027
2028                // Send added for users that see the package for the first time
2029                // sendPackageAddedForNewUsers also deals with system apps
2030                int appId = UserHandle.getAppId(res.uid);
2031                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2032                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2033                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2034
2035                // Send added for users that don't see the package for the first time
2036                Bundle extras = new Bundle(1);
2037                extras.putInt(Intent.EXTRA_UID, res.uid);
2038                if (update) {
2039                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2040                }
2041                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2042                        extras, 0 /*flags*/,
2043                        null /*targetPackage*/, null /*finishedReceiver*/,
2044                        updateUserIds, instantUserIds);
2045                if (installerPackageName != null) {
2046                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2047                            extras, 0 /*flags*/,
2048                            installerPackageName, null /*finishedReceiver*/,
2049                            updateUserIds, instantUserIds);
2050                }
2051
2052                // Send replaced for users that don't see the package for the first time
2053                if (update) {
2054                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2055                            packageName, extras, 0 /*flags*/,
2056                            null /*targetPackage*/, null /*finishedReceiver*/,
2057                            updateUserIds, instantUserIds);
2058                    if (installerPackageName != null) {
2059                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2060                                extras, 0 /*flags*/,
2061                                installerPackageName, null /*finishedReceiver*/,
2062                                updateUserIds, instantUserIds);
2063                    }
2064                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2065                            null /*package*/, null /*extras*/, 0 /*flags*/,
2066                            packageName /*targetPackage*/,
2067                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2068                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2069                    // First-install and we did a restore, so we're responsible for the
2070                    // first-launch broadcast.
2071                    if (DEBUG_BACKUP) {
2072                        Slog.i(TAG, "Post-restore of " + packageName
2073                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2074                    }
2075                    sendFirstLaunchBroadcast(packageName, installerPackage,
2076                            firstUserIds, firstInstantUserIds);
2077                }
2078
2079                // Send broadcast package appeared if forward locked/external for all users
2080                // treat asec-hosted packages like removable media on upgrade
2081                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2082                    if (DEBUG_INSTALL) {
2083                        Slog.i(TAG, "upgrading pkg " + res.pkg
2084                                + " is ASEC-hosted -> AVAILABLE");
2085                    }
2086                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2087                    ArrayList<String> pkgList = new ArrayList<>(1);
2088                    pkgList.add(packageName);
2089                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2090                }
2091            }
2092
2093            // Work that needs to happen on first install within each user
2094            if (firstUserIds != null && firstUserIds.length > 0) {
2095                synchronized (mPackages) {
2096                    for (int userId : firstUserIds) {
2097                        // If this app is a browser and it's newly-installed for some
2098                        // users, clear any default-browser state in those users. The
2099                        // app's nature doesn't depend on the user, so we can just check
2100                        // its browser nature in any user and generalize.
2101                        if (packageIsBrowser(packageName, userId)) {
2102                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2103                        }
2104
2105                        // We may also need to apply pending (restored) runtime
2106                        // permission grants within these users.
2107                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2108                    }
2109                }
2110            }
2111
2112            if (allNewUsers && !update) {
2113                notifyPackageAdded(packageName);
2114            }
2115
2116            // Log current value of "unknown sources" setting
2117            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2118                    getUnknownSourcesSettings());
2119
2120            // Remove the replaced package's older resources safely now
2121            // We delete after a gc for applications  on sdcard.
2122            if (res.removedInfo != null && res.removedInfo.args != null) {
2123                Runtime.getRuntime().gc();
2124                synchronized (mInstallLock) {
2125                    res.removedInfo.args.doPostDeleteLI(true);
2126                }
2127            } else {
2128                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2129                // and not block here.
2130                VMRuntime.getRuntime().requestConcurrentGC();
2131            }
2132
2133            // Notify DexManager that the package was installed for new users.
2134            // The updated users should already be indexed and the package code paths
2135            // should not change.
2136            // Don't notify the manager for ephemeral apps as they are not expected to
2137            // survive long enough to benefit of background optimizations.
2138            for (int userId : firstUserIds) {
2139                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2140                // There's a race currently where some install events may interleave with an uninstall.
2141                // This can lead to package info being null (b/36642664).
2142                if (info != null) {
2143                    mDexManager.notifyPackageInstalled(info, userId);
2144                }
2145            }
2146        }
2147
2148        // If someone is watching installs - notify them
2149        if (installObserver != null) {
2150            try {
2151                Bundle extras = extrasForInstallResult(res);
2152                installObserver.onPackageInstalled(res.name, res.returnCode,
2153                        res.returnMsg, extras);
2154            } catch (RemoteException e) {
2155                Slog.i(TAG, "Observer no longer exists.");
2156            }
2157        }
2158    }
2159
2160    private StorageEventListener mStorageListener = new StorageEventListener() {
2161        @Override
2162        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2163            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2164                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2165                    final String volumeUuid = vol.getFsUuid();
2166
2167                    // Clean up any users or apps that were removed or recreated
2168                    // while this volume was missing
2169                    sUserManager.reconcileUsers(volumeUuid);
2170                    reconcileApps(volumeUuid);
2171
2172                    // Clean up any install sessions that expired or were
2173                    // cancelled while this volume was missing
2174                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2175
2176                    loadPrivatePackages(vol);
2177
2178                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2179                    unloadPrivatePackages(vol);
2180                }
2181            }
2182        }
2183
2184        @Override
2185        public void onVolumeForgotten(String fsUuid) {
2186            if (TextUtils.isEmpty(fsUuid)) {
2187                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2188                return;
2189            }
2190
2191            // Remove any apps installed on the forgotten volume
2192            synchronized (mPackages) {
2193                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2194                for (PackageSetting ps : packages) {
2195                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2196                    deletePackageVersioned(new VersionedPackage(ps.name,
2197                            PackageManager.VERSION_CODE_HIGHEST),
2198                            new LegacyPackageDeleteObserver(null).getBinder(),
2199                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2200                    // Try very hard to release any references to this package
2201                    // so we don't risk the system server being killed due to
2202                    // open FDs
2203                    AttributeCache.instance().removePackage(ps.name);
2204                }
2205
2206                mSettings.onVolumeForgotten(fsUuid);
2207                mSettings.writeLPr();
2208            }
2209        }
2210    };
2211
2212    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2213        Bundle extras = null;
2214        switch (res.returnCode) {
2215            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2216                extras = new Bundle();
2217                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2218                        res.origPermission);
2219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2220                        res.origPackage);
2221                break;
2222            }
2223            case PackageManager.INSTALL_SUCCEEDED: {
2224                extras = new Bundle();
2225                extras.putBoolean(Intent.EXTRA_REPLACING,
2226                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2227                break;
2228            }
2229        }
2230        return extras;
2231    }
2232
2233    void scheduleWriteSettingsLocked() {
2234        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2235            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2236        }
2237    }
2238
2239    void scheduleWritePackageListLocked(int userId) {
2240        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2241            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2242            msg.arg1 = userId;
2243            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2244        }
2245    }
2246
2247    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2248        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2249        scheduleWritePackageRestrictionsLocked(userId);
2250    }
2251
2252    void scheduleWritePackageRestrictionsLocked(int userId) {
2253        final int[] userIds = (userId == UserHandle.USER_ALL)
2254                ? sUserManager.getUserIds() : new int[]{userId};
2255        for (int nextUserId : userIds) {
2256            if (!sUserManager.exists(nextUserId)) return;
2257            mDirtyUsers.add(nextUserId);
2258            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2259                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2260            }
2261        }
2262    }
2263
2264    public static PackageManagerService main(Context context, Installer installer,
2265            boolean factoryTest, boolean onlyCore) {
2266        // Self-check for initial settings.
2267        PackageManagerServiceCompilerMapping.checkProperties();
2268
2269        PackageManagerService m = new PackageManagerService(context, installer,
2270                factoryTest, onlyCore);
2271        m.enableSystemUserPackages();
2272        ServiceManager.addService("package", m);
2273        final PackageManagerNative pmn = m.new PackageManagerNative();
2274        ServiceManager.addService("package_native", pmn);
2275        return m;
2276    }
2277
2278    private void enableSystemUserPackages() {
2279        if (!UserManager.isSplitSystemUser()) {
2280            return;
2281        }
2282        // For system user, enable apps based on the following conditions:
2283        // - app is whitelisted or belong to one of these groups:
2284        //   -- system app which has no launcher icons
2285        //   -- system app which has INTERACT_ACROSS_USERS permission
2286        //   -- system IME app
2287        // - app is not in the blacklist
2288        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2289        Set<String> enableApps = new ArraySet<>();
2290        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2291                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2292                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2293        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2294        enableApps.addAll(wlApps);
2295        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2296                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2297        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2298        enableApps.removeAll(blApps);
2299        Log.i(TAG, "Applications installed for system user: " + enableApps);
2300        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2301                UserHandle.SYSTEM);
2302        final int allAppsSize = allAps.size();
2303        synchronized (mPackages) {
2304            for (int i = 0; i < allAppsSize; i++) {
2305                String pName = allAps.get(i);
2306                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2307                // Should not happen, but we shouldn't be failing if it does
2308                if (pkgSetting == null) {
2309                    continue;
2310                }
2311                boolean install = enableApps.contains(pName);
2312                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2313                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2314                            + " for system user");
2315                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2316                }
2317            }
2318            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2319        }
2320    }
2321
2322    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2323        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2324                Context.DISPLAY_SERVICE);
2325        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2326    }
2327
2328    /**
2329     * Requests that files preopted on a secondary system partition be copied to the data partition
2330     * if possible.  Note that the actual copying of the files is accomplished by init for security
2331     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2332     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2333     */
2334    private static void requestCopyPreoptedFiles() {
2335        final int WAIT_TIME_MS = 100;
2336        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2337        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2338            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2339            // We will wait for up to 100 seconds.
2340            final long timeStart = SystemClock.uptimeMillis();
2341            final long timeEnd = timeStart + 100 * 1000;
2342            long timeNow = timeStart;
2343            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2344                try {
2345                    Thread.sleep(WAIT_TIME_MS);
2346                } catch (InterruptedException e) {
2347                    // Do nothing
2348                }
2349                timeNow = SystemClock.uptimeMillis();
2350                if (timeNow > timeEnd) {
2351                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2352                    Slog.wtf(TAG, "cppreopt did not finish!");
2353                    break;
2354                }
2355            }
2356
2357            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2358        }
2359    }
2360
2361    public PackageManagerService(Context context, Installer installer,
2362            boolean factoryTest, boolean onlyCore) {
2363        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2365        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2366                SystemClock.uptimeMillis());
2367
2368        if (mSdkVersion <= 0) {
2369            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2370        }
2371
2372        mContext = context;
2373
2374        mFactoryTest = factoryTest;
2375        mOnlyCore = onlyCore;
2376        mMetrics = new DisplayMetrics();
2377        mInstaller = installer;
2378
2379        // Create sub-components that provide services / data. Order here is important.
2380        synchronized (mInstallLock) {
2381        synchronized (mPackages) {
2382            // Expose private service for system components to use.
2383            LocalServices.addService(
2384                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2385            sUserManager = new UserManagerService(context, this,
2386                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2387            mPermissionManager = PermissionManagerService.create(context,
2388                    new DefaultPermissionGrantedCallback() {
2389                        @Override
2390                        public void onDefaultRuntimePermissionsGranted(int userId) {
2391                            synchronized(mPackages) {
2392                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2393                            }
2394                        }
2395                    }, mPackages /*externalLock*/);
2396            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2397            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2398        }
2399        }
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414
2415        String separateProcesses = SystemProperties.get("debug.separate_processes");
2416        if (separateProcesses != null && separateProcesses.length() > 0) {
2417            if ("*".equals(separateProcesses)) {
2418                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2419                mSeparateProcesses = null;
2420                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2421            } else {
2422                mDefParseFlags = 0;
2423                mSeparateProcesses = separateProcesses.split(",");
2424                Slog.w(TAG, "Running with debug.separate_processes: "
2425                        + separateProcesses);
2426            }
2427        } else {
2428            mDefParseFlags = 0;
2429            mSeparateProcesses = null;
2430        }
2431
2432        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2433                "*dexopt*");
2434        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2435                installer, mInstallLock);
2436        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2437                dexManagerListener);
2438        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2439        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2440
2441        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2442                FgThread.get().getLooper());
2443
2444        getDefaultDisplayMetrics(context, mMetrics);
2445
2446        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2447        SystemConfig systemConfig = SystemConfig.getInstance();
2448        mAvailableFeatures = systemConfig.getAvailableFeatures();
2449        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2450
2451        mProtectedPackages = new ProtectedPackages(mContext);
2452
2453        synchronized (mInstallLock) {
2454        // writer
2455        synchronized (mPackages) {
2456            mHandlerThread = new ServiceThread(TAG,
2457                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2458            mHandlerThread.start();
2459            mHandler = new PackageHandler(mHandlerThread.getLooper());
2460            mProcessLoggingHandler = new ProcessLoggingHandler();
2461            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2462            mInstantAppRegistry = new InstantAppRegistry(this);
2463
2464            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2465            final int builtInLibCount = libConfig.size();
2466            for (int i = 0; i < builtInLibCount; i++) {
2467                String name = libConfig.keyAt(i);
2468                String path = libConfig.valueAt(i);
2469                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2470                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2471            }
2472
2473            SELinuxMMAC.readInstallPolicy();
2474
2475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2476            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2477            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2478
2479            // Clean up orphaned packages for which the code path doesn't exist
2480            // and they are an update to a system app - caused by bug/32321269
2481            final int packageSettingCount = mSettings.mPackages.size();
2482            for (int i = packageSettingCount - 1; i >= 0; i--) {
2483                PackageSetting ps = mSettings.mPackages.valueAt(i);
2484                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2485                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2486                    mSettings.mPackages.removeAt(i);
2487                    mSettings.enableSystemPackageLPw(ps.name);
2488                }
2489            }
2490
2491            if (mFirstBoot) {
2492                requestCopyPreoptedFiles();
2493            }
2494
2495            String customResolverActivity = Resources.getSystem().getString(
2496                    R.string.config_customResolverActivity);
2497            if (TextUtils.isEmpty(customResolverActivity)) {
2498                customResolverActivity = null;
2499            } else {
2500                mCustomResolverComponentName = ComponentName.unflattenFromString(
2501                        customResolverActivity);
2502            }
2503
2504            long startTime = SystemClock.uptimeMillis();
2505
2506            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2507                    startTime);
2508
2509            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2510            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2511
2512            if (bootClassPath == null) {
2513                Slog.w(TAG, "No BOOTCLASSPATH found!");
2514            }
2515
2516            if (systemServerClassPath == null) {
2517                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2518            }
2519
2520            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2521
2522            final VersionInfo ver = mSettings.getInternalVersion();
2523            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2524            if (mIsUpgrade) {
2525                logCriticalInfo(Log.INFO,
2526                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2527            }
2528
2529            // when upgrading from pre-M, promote system app permissions from install to runtime
2530            mPromoteSystemApps =
2531                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2532
2533            // When upgrading from pre-N, we need to handle package extraction like first boot,
2534            // as there is no profiling data available.
2535            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2536
2537            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2538
2539            // save off the names of pre-existing system packages prior to scanning; we don't
2540            // want to automatically grant runtime permissions for new system apps
2541            if (mPromoteSystemApps) {
2542                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2543                while (pkgSettingIter.hasNext()) {
2544                    PackageSetting ps = pkgSettingIter.next();
2545                    if (isSystemApp(ps)) {
2546                        mExistingSystemPackages.add(ps.name);
2547                    }
2548                }
2549            }
2550
2551            mCacheDir = preparePackageParserCache(mIsUpgrade);
2552
2553            // Set flag to monitor and not change apk file paths when
2554            // scanning install directories.
2555            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2556
2557            if (mIsUpgrade || mFirstBoot) {
2558                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2559            }
2560
2561            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2562            // For security and version matching reason, only consider
2563            // overlay packages if they reside in the right directory.
2564            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2565                    mDefParseFlags
2566                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2567                    scanFlags
2568                    | SCAN_AS_SYSTEM
2569                    | SCAN_AS_VENDOR,
2570                    0);
2571            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2572                    mDefParseFlags
2573                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2574                    scanFlags
2575                    | SCAN_AS_SYSTEM
2576                    | SCAN_AS_PRODUCT,
2577                    0);
2578
2579            mParallelPackageParserCallback.findStaticOverlayPackages();
2580
2581            // Find base frameworks (resource packages without code).
2582            scanDirTracedLI(frameworkDir,
2583                    mDefParseFlags
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2585                    scanFlags
2586                    | SCAN_NO_DEX
2587                    | SCAN_AS_SYSTEM
2588                    | SCAN_AS_PRIVILEGED,
2589                    0);
2590
2591            // Collected privileged system packages.
2592            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2593            scanDirTracedLI(privilegedAppDir,
2594                    mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2596                    scanFlags
2597                    | SCAN_AS_SYSTEM
2598                    | SCAN_AS_PRIVILEGED,
2599                    0);
2600
2601            // Collect ordinary system packages.
2602            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2603            scanDirTracedLI(systemAppDir,
2604                    mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2606                    scanFlags
2607                    | SCAN_AS_SYSTEM,
2608                    0);
2609
2610            // Collected privileged vendor packages.
2611            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2612            try {
2613                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2614            } catch (IOException e) {
2615                // failed to look up canonical path, continue with original one
2616            }
2617            scanDirTracedLI(privilegedVendorAppDir,
2618                    mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2620                    scanFlags
2621                    | SCAN_AS_SYSTEM
2622                    | SCAN_AS_VENDOR
2623                    | SCAN_AS_PRIVILEGED,
2624                    0);
2625
2626            // Collect ordinary vendor packages.
2627            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2628            try {
2629                vendorAppDir = vendorAppDir.getCanonicalFile();
2630            } catch (IOException e) {
2631                // failed to look up canonical path, continue with original one
2632            }
2633            scanDirTracedLI(vendorAppDir,
2634                    mDefParseFlags
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2636                    scanFlags
2637                    | SCAN_AS_SYSTEM
2638                    | SCAN_AS_VENDOR,
2639                    0);
2640
2641            // Collect all OEM packages.
2642            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2643            scanDirTracedLI(oemAppDir,
2644                    mDefParseFlags
2645                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2646                    scanFlags
2647                    | SCAN_AS_SYSTEM
2648                    | SCAN_AS_OEM,
2649                    0);
2650
2651            // Collected privileged product packages.
2652            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2653            try {
2654                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2655            } catch (IOException e) {
2656                // failed to look up canonical path, continue with original one
2657            }
2658            scanDirTracedLI(privilegedProductAppDir,
2659                    mDefParseFlags
2660                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2661                    scanFlags
2662                    | SCAN_AS_SYSTEM
2663                    | SCAN_AS_PRODUCT
2664                    | SCAN_AS_PRIVILEGED,
2665                    0);
2666
2667            // Collect ordinary product packages.
2668            File productAppDir = new File(Environment.getProductDirectory(), "app");
2669            try {
2670                productAppDir = productAppDir.getCanonicalFile();
2671            } catch (IOException e) {
2672                // failed to look up canonical path, continue with original one
2673            }
2674            scanDirTracedLI(productAppDir,
2675                    mDefParseFlags
2676                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2677                    scanFlags
2678                    | SCAN_AS_SYSTEM
2679                    | SCAN_AS_PRODUCT,
2680                    0);
2681
2682            // Prune any system packages that no longer exist.
2683            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2684            // Stub packages must either be replaced with full versions in the /data
2685            // partition or be disabled.
2686            final List<String> stubSystemApps = new ArrayList<>();
2687            if (!mOnlyCore) {
2688                // do this first before mucking with mPackages for the "expecting better" case
2689                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2690                while (pkgIterator.hasNext()) {
2691                    final PackageParser.Package pkg = pkgIterator.next();
2692                    if (pkg.isStub) {
2693                        stubSystemApps.add(pkg.packageName);
2694                    }
2695                }
2696
2697                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2698                while (psit.hasNext()) {
2699                    PackageSetting ps = psit.next();
2700
2701                    /*
2702                     * If this is not a system app, it can't be a
2703                     * disable system app.
2704                     */
2705                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2706                        continue;
2707                    }
2708
2709                    /*
2710                     * If the package is scanned, it's not erased.
2711                     */
2712                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2713                    if (scannedPkg != null) {
2714                        /*
2715                         * If the system app is both scanned and in the
2716                         * disabled packages list, then it must have been
2717                         * added via OTA. Remove it from the currently
2718                         * scanned package so the previously user-installed
2719                         * application can be scanned.
2720                         */
2721                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2722                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2723                                    + ps.name + "; removing system app.  Last known codePath="
2724                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2725                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2726                                    + scannedPkg.getLongVersionCode());
2727                            removePackageLI(scannedPkg, true);
2728                            mExpectingBetter.put(ps.name, ps.codePath);
2729                        }
2730
2731                        continue;
2732                    }
2733
2734                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2735                        psit.remove();
2736                        logCriticalInfo(Log.WARN, "System package " + ps.name
2737                                + " no longer exists; it's data will be wiped");
2738                        // Actual deletion of code and data will be handled by later
2739                        // reconciliation step
2740                    } else {
2741                        // we still have a disabled system package, but, it still might have
2742                        // been removed. check the code path still exists and check there's
2743                        // still a package. the latter can happen if an OTA keeps the same
2744                        // code path, but, changes the package name.
2745                        final PackageSetting disabledPs =
2746                                mSettings.getDisabledSystemPkgLPr(ps.name);
2747                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2748                                || disabledPs.pkg == null) {
2749if (REFACTOR_DEBUG) {
2750Slog.e("TODD",
2751        "Possibly deleted app: " + ps.dumpState_temp()
2752        + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath)
2753        + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString()));
2754}
2755                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2756                        }
2757                    }
2758                }
2759            }
2760
2761            //look for any incomplete package installations
2762            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2763            for (int i = 0; i < deletePkgsList.size(); i++) {
2764                // Actual deletion of code and data will be handled by later
2765                // reconciliation step
2766                final String packageName = deletePkgsList.get(i).name;
2767                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2768                synchronized (mPackages) {
2769                    mSettings.removePackageLPw(packageName);
2770                }
2771            }
2772
2773            //delete tmp files
2774            deleteTempPackageFiles();
2775
2776            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2777
2778            // Remove any shared userIDs that have no associated packages
2779            mSettings.pruneSharedUsersLPw();
2780            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2781            final int systemPackagesCount = mPackages.size();
2782            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2783                    + " ms, packageCount: " + systemPackagesCount
2784                    + " , timePerPackage: "
2785                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2786                    + " , cached: " + cachedSystemApps);
2787            if (mIsUpgrade && systemPackagesCount > 0) {
2788                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2789                        ((int) systemScanTime) / systemPackagesCount);
2790            }
2791            if (!mOnlyCore) {
2792                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2793                        SystemClock.uptimeMillis());
2794                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2795
2796                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2797                        | PackageParser.PARSE_FORWARD_LOCK,
2798                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2799
2800                // Remove disable package settings for updated system apps that were
2801                // removed via an OTA. If the update is no longer present, remove the
2802                // app completely. Otherwise, revoke their system privileges.
2803                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2804                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2805                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2806if (REFACTOR_DEBUG) {
2807Slog.e("TODD",
2808        "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null));
2809}
2810                    final String msg;
2811                    if (deletedPkg == null) {
2812                        // should have found an update, but, we didn't; remove everything
2813                        msg = "Updated system package " + deletedAppName
2814                                + " no longer exists; removing its data";
2815                        // Actual deletion of code and data will be handled by later
2816                        // reconciliation step
2817                    } else {
2818                        // found an update; revoke system privileges
2819                        msg = "Updated system package + " + deletedAppName
2820                                + " no longer exists; revoking system privileges";
2821
2822                        // Don't do anything if a stub is removed from the system image. If
2823                        // we were to remove the uncompressed version from the /data partition,
2824                        // this is where it'd be done.
2825
2826                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2827                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2828                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2829                    }
2830                    logCriticalInfo(Log.WARN, msg);
2831                }
2832
2833                /*
2834                 * Make sure all system apps that we expected to appear on
2835                 * the userdata partition actually showed up. If they never
2836                 * appeared, crawl back and revive the system version.
2837                 */
2838                for (int i = 0; i < mExpectingBetter.size(); i++) {
2839                    final String packageName = mExpectingBetter.keyAt(i);
2840                    if (!mPackages.containsKey(packageName)) {
2841                        final File scanFile = mExpectingBetter.valueAt(i);
2842
2843                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2844                                + " but never showed up; reverting to system");
2845
2846                        final @ParseFlags int reparseFlags;
2847                        final @ScanFlags int rescanFlags;
2848                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2849                            reparseFlags =
2850                                    mDefParseFlags |
2851                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2852                            rescanFlags =
2853                                    scanFlags
2854                                    | SCAN_AS_SYSTEM
2855                                    | SCAN_AS_PRIVILEGED;
2856                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2857                            reparseFlags =
2858                                    mDefParseFlags |
2859                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2860                            rescanFlags =
2861                                    scanFlags
2862                                    | SCAN_AS_SYSTEM;
2863                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2864                            reparseFlags =
2865                                    mDefParseFlags |
2866                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2867                            rescanFlags =
2868                                    scanFlags
2869                                    | SCAN_AS_SYSTEM
2870                                    | SCAN_AS_VENDOR
2871                                    | SCAN_AS_PRIVILEGED;
2872                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2873                            reparseFlags =
2874                                    mDefParseFlags |
2875                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2876                            rescanFlags =
2877                                    scanFlags
2878                                    | SCAN_AS_SYSTEM
2879                                    | SCAN_AS_VENDOR;
2880                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2881                            reparseFlags =
2882                                    mDefParseFlags |
2883                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2884                            rescanFlags =
2885                                    scanFlags
2886                                    | SCAN_AS_SYSTEM
2887                                    | SCAN_AS_OEM;
2888                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2889                            reparseFlags =
2890                                    mDefParseFlags |
2891                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2892                            rescanFlags =
2893                                    scanFlags
2894                                    | SCAN_AS_SYSTEM
2895                                    | SCAN_AS_PRODUCT
2896                                    | SCAN_AS_PRIVILEGED;
2897                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2898                            reparseFlags =
2899                                    mDefParseFlags |
2900                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2901                            rescanFlags =
2902                                    scanFlags
2903                                    | SCAN_AS_SYSTEM
2904                                    | SCAN_AS_PRODUCT;
2905                        } else {
2906                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2907                            continue;
2908                        }
2909
2910                        mSettings.enableSystemPackageLPw(packageName);
2911
2912                        try {
2913                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2914                        } catch (PackageManagerException e) {
2915                            Slog.e(TAG, "Failed to parse original system package: "
2916                                    + e.getMessage());
2917                        }
2918                    }
2919                }
2920
2921                // Uncompress and install any stubbed system applications.
2922                // This must be done last to ensure all stubs are replaced or disabled.
2923                decompressSystemApplications(stubSystemApps, scanFlags);
2924
2925                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2926                                - cachedSystemApps;
2927
2928                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2929                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2930                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2931                        + " ms, packageCount: " + dataPackagesCount
2932                        + " , timePerPackage: "
2933                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2934                        + " , cached: " + cachedNonSystemApps);
2935                if (mIsUpgrade && dataPackagesCount > 0) {
2936                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2937                            ((int) dataScanTime) / dataPackagesCount);
2938                }
2939            }
2940            mExpectingBetter.clear();
2941
2942            // Resolve the storage manager.
2943            mStorageManagerPackage = getStorageManagerPackageName();
2944
2945            // Resolve protected action filters. Only the setup wizard is allowed to
2946            // have a high priority filter for these actions.
2947            mSetupWizardPackage = getSetupWizardPackageName();
2948            if (mProtectedFilters.size() > 0) {
2949                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2950                    Slog.i(TAG, "No setup wizard;"
2951                        + " All protected intents capped to priority 0");
2952                }
2953                for (ActivityIntentInfo filter : mProtectedFilters) {
2954                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2955                        if (DEBUG_FILTERS) {
2956                            Slog.i(TAG, "Found setup wizard;"
2957                                + " allow priority " + filter.getPriority() + ";"
2958                                + " package: " + filter.activity.info.packageName
2959                                + " activity: " + filter.activity.className
2960                                + " priority: " + filter.getPriority());
2961                        }
2962                        // skip setup wizard; allow it to keep the high priority filter
2963                        continue;
2964                    }
2965                    if (DEBUG_FILTERS) {
2966                        Slog.i(TAG, "Protected action; cap priority to 0;"
2967                                + " package: " + filter.activity.info.packageName
2968                                + " activity: " + filter.activity.className
2969                                + " origPrio: " + filter.getPriority());
2970                    }
2971                    filter.setPriority(0);
2972                }
2973            }
2974            mDeferProtectedFilters = false;
2975            mProtectedFilters.clear();
2976
2977            // Now that we know all of the shared libraries, update all clients to have
2978            // the correct library paths.
2979            updateAllSharedLibrariesLPw(null);
2980
2981            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2982                // NOTE: We ignore potential failures here during a system scan (like
2983                // the rest of the commands above) because there's precious little we
2984                // can do about it. A settings error is reported, though.
2985                final List<String> changedAbiCodePath =
2986                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2987                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2988                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2989                        final String codePathString = changedAbiCodePath.get(i);
2990                        try {
2991                            mInstaller.rmdex(codePathString,
2992                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2993                        } catch (InstallerException ignored) {
2994                        }
2995                    }
2996                }
2997            }
2998
2999            // Now that we know all the packages we are keeping,
3000            // read and update their last usage times.
3001            mPackageUsage.read(mPackages);
3002            mCompilerStats.read();
3003
3004            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3005                    SystemClock.uptimeMillis());
3006            Slog.i(TAG, "Time to scan packages: "
3007                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3008                    + " seconds");
3009
3010            // If the platform SDK has changed since the last time we booted,
3011            // we need to re-grant app permission to catch any new ones that
3012            // appear.  This is really a hack, and means that apps can in some
3013            // cases get permissions that the user didn't initially explicitly
3014            // allow...  it would be nice to have some better way to handle
3015            // this situation.
3016            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3017            if (sdkUpdated) {
3018                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3019                        + mSdkVersion + "; regranting permissions for internal storage");
3020            }
3021            mPermissionManager.updateAllPermissions(
3022                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3023                    mPermissionCallback);
3024            ver.sdkVersion = mSdkVersion;
3025
3026            // If this is the first boot or an update from pre-M, and it is a normal
3027            // boot, then we need to initialize the default preferred apps across
3028            // all defined users.
3029            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3030                for (UserInfo user : sUserManager.getUsers(true)) {
3031                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3032                    applyFactoryDefaultBrowserLPw(user.id);
3033                    primeDomainVerificationsLPw(user.id);
3034                }
3035            }
3036
3037            // Prepare storage for system user really early during boot,
3038            // since core system apps like SettingsProvider and SystemUI
3039            // can't wait for user to start
3040            final int storageFlags;
3041            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3042                storageFlags = StorageManager.FLAG_STORAGE_DE;
3043            } else {
3044                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3045            }
3046            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3047                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3048                    true /* onlyCoreApps */);
3049            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3050                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3051                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3052                traceLog.traceBegin("AppDataFixup");
3053                try {
3054                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3055                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3056                } catch (InstallerException e) {
3057                    Slog.w(TAG, "Trouble fixing GIDs", e);
3058                }
3059                traceLog.traceEnd();
3060
3061                traceLog.traceBegin("AppDataPrepare");
3062                if (deferPackages == null || deferPackages.isEmpty()) {
3063                    return;
3064                }
3065                int count = 0;
3066                for (String pkgName : deferPackages) {
3067                    PackageParser.Package pkg = null;
3068                    synchronized (mPackages) {
3069                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3070                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3071                            pkg = ps.pkg;
3072                        }
3073                    }
3074                    if (pkg != null) {
3075                        synchronized (mInstallLock) {
3076                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3077                                    true /* maybeMigrateAppData */);
3078                        }
3079                        count++;
3080                    }
3081                }
3082                traceLog.traceEnd();
3083                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3084            }, "prepareAppData");
3085
3086            // If this is first boot after an OTA, and a normal boot, then
3087            // we need to clear code cache directories.
3088            // Note that we do *not* clear the application profiles. These remain valid
3089            // across OTAs and are used to drive profile verification (post OTA) and
3090            // profile compilation (without waiting to collect a fresh set of profiles).
3091            if (mIsUpgrade && !onlyCore) {
3092                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3093                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3094                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3095                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3096                        // No apps are running this early, so no need to freeze
3097                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3098                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3099                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3100                    }
3101                }
3102                ver.fingerprint = Build.FINGERPRINT;
3103            }
3104
3105            checkDefaultBrowser();
3106
3107            // clear only after permissions and other defaults have been updated
3108            mExistingSystemPackages.clear();
3109            mPromoteSystemApps = false;
3110
3111            // All the changes are done during package scanning.
3112            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3113
3114            // can downgrade to reader
3115            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3116            mSettings.writeLPr();
3117            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3118            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3119                    SystemClock.uptimeMillis());
3120
3121            if (!mOnlyCore) {
3122                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3123                mRequiredInstallerPackage = getRequiredInstallerLPr();
3124                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3125                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3126                if (mIntentFilterVerifierComponent != null) {
3127                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3128                            mIntentFilterVerifierComponent);
3129                } else {
3130                    mIntentFilterVerifier = null;
3131                }
3132                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3133                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3134                        SharedLibraryInfo.VERSION_UNDEFINED);
3135                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3136                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3137                        SharedLibraryInfo.VERSION_UNDEFINED);
3138            } else {
3139                mRequiredVerifierPackage = null;
3140                mRequiredInstallerPackage = null;
3141                mRequiredUninstallerPackage = null;
3142                mIntentFilterVerifierComponent = null;
3143                mIntentFilterVerifier = null;
3144                mServicesSystemSharedLibraryPackageName = null;
3145                mSharedSystemSharedLibraryPackageName = null;
3146            }
3147
3148            mInstallerService = new PackageInstallerService(context, this);
3149            final Pair<ComponentName, String> instantAppResolverComponent =
3150                    getInstantAppResolverLPr();
3151            if (instantAppResolverComponent != null) {
3152                if (DEBUG_INSTANT) {
3153                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3154                }
3155                mInstantAppResolverConnection = new InstantAppResolverConnection(
3156                        mContext, instantAppResolverComponent.first,
3157                        instantAppResolverComponent.second);
3158                mInstantAppResolverSettingsComponent =
3159                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3160            } else {
3161                mInstantAppResolverConnection = null;
3162                mInstantAppResolverSettingsComponent = null;
3163            }
3164            updateInstantAppInstallerLocked(null);
3165
3166            // Read and update the usage of dex files.
3167            // Do this at the end of PM init so that all the packages have their
3168            // data directory reconciled.
3169            // At this point we know the code paths of the packages, so we can validate
3170            // the disk file and build the internal cache.
3171            // The usage file is expected to be small so loading and verifying it
3172            // should take a fairly small time compare to the other activities (e.g. package
3173            // scanning).
3174            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3175            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3176            for (int userId : currentUserIds) {
3177                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3178            }
3179            mDexManager.load(userPackages);
3180            if (mIsUpgrade) {
3181                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3182                        (int) (SystemClock.uptimeMillis() - startTime));
3183            }
3184        } // synchronized (mPackages)
3185        } // synchronized (mInstallLock)
3186
3187        // Now after opening every single application zip, make sure they
3188        // are all flushed.  Not really needed, but keeps things nice and
3189        // tidy.
3190        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3191        Runtime.getRuntime().gc();
3192        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3193
3194        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3195        FallbackCategoryProvider.loadFallbacks();
3196        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3197
3198        // The initial scanning above does many calls into installd while
3199        // holding the mPackages lock, but we're mostly interested in yelling
3200        // once we have a booted system.
3201        mInstaller.setWarnIfHeld(mPackages);
3202
3203        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3204    }
3205
3206    /**
3207     * Uncompress and install stub applications.
3208     * <p>In order to save space on the system partition, some applications are shipped in a
3209     * compressed form. In addition the compressed bits for the full application, the
3210     * system image contains a tiny stub comprised of only the Android manifest.
3211     * <p>During the first boot, attempt to uncompress and install the full application. If
3212     * the application can't be installed for any reason, disable the stub and prevent
3213     * uncompressing the full application during future boots.
3214     * <p>In order to forcefully attempt an installation of a full application, go to app
3215     * settings and enable the application.
3216     */
3217    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3218        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3219            final String pkgName = stubSystemApps.get(i);
3220            // skip if the system package is already disabled
3221            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3222                stubSystemApps.remove(i);
3223                continue;
3224            }
3225            // skip if the package isn't installed (?!); this should never happen
3226            final PackageParser.Package pkg = mPackages.get(pkgName);
3227            if (pkg == null) {
3228                stubSystemApps.remove(i);
3229                continue;
3230            }
3231            // skip if the package has been disabled by the user
3232            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3233            if (ps != null) {
3234                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3235                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3236                    stubSystemApps.remove(i);
3237                    continue;
3238                }
3239            }
3240
3241            if (DEBUG_COMPRESSION) {
3242                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3243            }
3244
3245            // uncompress the binary to its eventual destination on /data
3246            final File scanFile = decompressPackage(pkg);
3247            if (scanFile == null) {
3248                continue;
3249            }
3250
3251            // install the package to replace the stub on /system
3252            try {
3253                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3254                removePackageLI(pkg, true /*chatty*/);
3255                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3256                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3257                        UserHandle.USER_SYSTEM, "android");
3258                stubSystemApps.remove(i);
3259                continue;
3260            } catch (PackageManagerException e) {
3261                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3262            }
3263
3264            // any failed attempt to install the package will be cleaned up later
3265        }
3266
3267        // disable any stub still left; these failed to install the full application
3268        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3269            final String pkgName = stubSystemApps.get(i);
3270            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3271            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3272                    UserHandle.USER_SYSTEM, "android");
3273            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3274        }
3275    }
3276
3277    /**
3278     * Decompresses the given package on the system image onto
3279     * the /data partition.
3280     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3281     */
3282    private File decompressPackage(PackageParser.Package pkg) {
3283        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3284        if (compressedFiles == null || compressedFiles.length == 0) {
3285            if (DEBUG_COMPRESSION) {
3286                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3287            }
3288            return null;
3289        }
3290        final File dstCodePath =
3291                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3292        int ret = PackageManager.INSTALL_SUCCEEDED;
3293        try {
3294            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3295            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3296            for (File srcFile : compressedFiles) {
3297                final String srcFileName = srcFile.getName();
3298                final String dstFileName = srcFileName.substring(
3299                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3300                final File dstFile = new File(dstCodePath, dstFileName);
3301                ret = decompressFile(srcFile, dstFile);
3302                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3303                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3304                            + "; pkg: " + pkg.packageName
3305                            + ", file: " + dstFileName);
3306                    break;
3307                }
3308            }
3309        } catch (ErrnoException e) {
3310            logCriticalInfo(Log.ERROR, "Failed to decompress"
3311                    + "; pkg: " + pkg.packageName
3312                    + ", err: " + e.errno);
3313        }
3314        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3315            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3316            NativeLibraryHelper.Handle handle = null;
3317            try {
3318                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3319                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3320                        null /*abiOverride*/);
3321            } catch (IOException e) {
3322                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3323                        + "; pkg: " + pkg.packageName);
3324                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3325            } finally {
3326                IoUtils.closeQuietly(handle);
3327            }
3328        }
3329        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3330            if (dstCodePath == null || !dstCodePath.exists()) {
3331                return null;
3332            }
3333            removeCodePathLI(dstCodePath);
3334            return null;
3335        }
3336
3337        return dstCodePath;
3338    }
3339
3340    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3341        // we're only interested in updating the installer appliction when 1) it's not
3342        // already set or 2) the modified package is the installer
3343        if (mInstantAppInstallerActivity != null
3344                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3345                        .equals(modifiedPackage)) {
3346            return;
3347        }
3348        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3349    }
3350
3351    private static File preparePackageParserCache(boolean isUpgrade) {
3352        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3353            return null;
3354        }
3355
3356        // Disable package parsing on eng builds to allow for faster incremental development.
3357        if (Build.IS_ENG) {
3358            return null;
3359        }
3360
3361        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3362            Slog.i(TAG, "Disabling package parser cache due to system property.");
3363            return null;
3364        }
3365
3366        // The base directory for the package parser cache lives under /data/system/.
3367        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3368                "package_cache");
3369        if (cacheBaseDir == null) {
3370            return null;
3371        }
3372
3373        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3374        // This also serves to "GC" unused entries when the package cache version changes (which
3375        // can only happen during upgrades).
3376        if (isUpgrade) {
3377            FileUtils.deleteContents(cacheBaseDir);
3378        }
3379
3380
3381        // Return the versioned package cache directory. This is something like
3382        // "/data/system/package_cache/1"
3383        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3384
3385        // The following is a workaround to aid development on non-numbered userdebug
3386        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3387        // the system partition is newer.
3388        //
3389        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3390        // that starts with "eng." to signify that this is an engineering build and not
3391        // destined for release.
3392        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3393            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3394
3395            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3396            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3397            // in general and should not be used for production changes. In this specific case,
3398            // we know that they will work.
3399            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3400            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3401                FileUtils.deleteContents(cacheBaseDir);
3402                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3403            }
3404        }
3405
3406        return cacheDir;
3407    }
3408
3409    @Override
3410    public boolean isFirstBoot() {
3411        // allow instant applications
3412        return mFirstBoot;
3413    }
3414
3415    @Override
3416    public boolean isOnlyCoreApps() {
3417        // allow instant applications
3418        return mOnlyCore;
3419    }
3420
3421    @Override
3422    public boolean isUpgrade() {
3423        // allow instant applications
3424        // The system property allows testing ota flow when upgraded to the same image.
3425        return mIsUpgrade || SystemProperties.getBoolean(
3426                "persist.pm.mock-upgrade", false /* default */);
3427    }
3428
3429    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3430        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3431
3432        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3433                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3434                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3435        if (matches.size() == 1) {
3436            return matches.get(0).getComponentInfo().packageName;
3437        } else if (matches.size() == 0) {
3438            Log.e(TAG, "There should probably be a verifier, but, none were found");
3439            return null;
3440        }
3441        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3442    }
3443
3444    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3445        synchronized (mPackages) {
3446            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3447            if (libraryEntry == null) {
3448                throw new IllegalStateException("Missing required shared library:" + name);
3449            }
3450            return libraryEntry.apk;
3451        }
3452    }
3453
3454    private @NonNull String getRequiredInstallerLPr() {
3455        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3456        intent.addCategory(Intent.CATEGORY_DEFAULT);
3457        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3458
3459        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3460                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3461                UserHandle.USER_SYSTEM);
3462        if (matches.size() == 1) {
3463            ResolveInfo resolveInfo = matches.get(0);
3464            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3465                throw new RuntimeException("The installer must be a privileged app");
3466            }
3467            return matches.get(0).getComponentInfo().packageName;
3468        } else {
3469            throw new RuntimeException("There must be exactly one installer; found " + matches);
3470        }
3471    }
3472
3473    private @NonNull String getRequiredUninstallerLPr() {
3474        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3475        intent.addCategory(Intent.CATEGORY_DEFAULT);
3476        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3477
3478        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3479                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3480                UserHandle.USER_SYSTEM);
3481        if (resolveInfo == null ||
3482                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3483            throw new RuntimeException("There must be exactly one uninstaller; found "
3484                    + resolveInfo);
3485        }
3486        return resolveInfo.getComponentInfo().packageName;
3487    }
3488
3489    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3490        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3491
3492        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3493                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3494                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3495        ResolveInfo best = null;
3496        final int N = matches.size();
3497        for (int i = 0; i < N; i++) {
3498            final ResolveInfo cur = matches.get(i);
3499            final String packageName = cur.getComponentInfo().packageName;
3500            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3501                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3502                continue;
3503            }
3504
3505            if (best == null || cur.priority > best.priority) {
3506                best = cur;
3507            }
3508        }
3509
3510        if (best != null) {
3511            return best.getComponentInfo().getComponentName();
3512        }
3513        Slog.w(TAG, "Intent filter verifier not found");
3514        return null;
3515    }
3516
3517    @Override
3518    public @Nullable ComponentName getInstantAppResolverComponent() {
3519        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3520            return null;
3521        }
3522        synchronized (mPackages) {
3523            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3524            if (instantAppResolver == null) {
3525                return null;
3526            }
3527            return instantAppResolver.first;
3528        }
3529    }
3530
3531    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3532        final String[] packageArray =
3533                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3534        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3535            if (DEBUG_INSTANT) {
3536                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3537            }
3538            return null;
3539        }
3540
3541        final int callingUid = Binder.getCallingUid();
3542        final int resolveFlags =
3543                MATCH_DIRECT_BOOT_AWARE
3544                | MATCH_DIRECT_BOOT_UNAWARE
3545                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3546        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3547        final Intent resolverIntent = new Intent(actionName);
3548        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3549                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3550        final int N = resolvers.size();
3551        if (N == 0) {
3552            if (DEBUG_INSTANT) {
3553                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3554            }
3555            return null;
3556        }
3557
3558        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3559        for (int i = 0; i < N; i++) {
3560            final ResolveInfo info = resolvers.get(i);
3561
3562            if (info.serviceInfo == null) {
3563                continue;
3564            }
3565
3566            final String packageName = info.serviceInfo.packageName;
3567            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3568                if (DEBUG_INSTANT) {
3569                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3570                            + " pkg: " + packageName + ", info:" + info);
3571                }
3572                continue;
3573            }
3574
3575            if (DEBUG_INSTANT) {
3576                Slog.v(TAG, "Ephemeral resolver found;"
3577                        + " pkg: " + packageName + ", info:" + info);
3578            }
3579            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3580        }
3581        if (DEBUG_INSTANT) {
3582            Slog.v(TAG, "Ephemeral resolver NOT found");
3583        }
3584        return null;
3585    }
3586
3587    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3588        String[] orderedActions = Build.IS_ENG
3589                ? new String[]{
3590                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3591                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3592                : new String[]{
3593                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3594
3595        final int resolveFlags =
3596                MATCH_DIRECT_BOOT_AWARE
3597                        | MATCH_DIRECT_BOOT_UNAWARE
3598                        | Intent.FLAG_IGNORE_EPHEMERAL
3599                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3600        final Intent intent = new Intent();
3601        intent.addCategory(Intent.CATEGORY_DEFAULT);
3602        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3603        List<ResolveInfo> matches = null;
3604        for (String action : orderedActions) {
3605            intent.setAction(action);
3606            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3607                    resolveFlags, UserHandle.USER_SYSTEM);
3608            if (matches.isEmpty()) {
3609                if (DEBUG_INSTANT) {
3610                    Slog.d(TAG, "Instant App installer not found with " + action);
3611                }
3612            } else {
3613                break;
3614            }
3615        }
3616        Iterator<ResolveInfo> iter = matches.iterator();
3617        while (iter.hasNext()) {
3618            final ResolveInfo rInfo = iter.next();
3619            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3620            if (ps != null) {
3621                final PermissionsState permissionsState = ps.getPermissionsState();
3622                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3623                        || Build.IS_ENG) {
3624                    continue;
3625                }
3626            }
3627            iter.remove();
3628        }
3629        if (matches.size() == 0) {
3630            return null;
3631        } else if (matches.size() == 1) {
3632            return (ActivityInfo) matches.get(0).getComponentInfo();
3633        } else {
3634            throw new RuntimeException(
3635                    "There must be at most one ephemeral installer; found " + matches);
3636        }
3637    }
3638
3639    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3640            @NonNull ComponentName resolver) {
3641        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3642                .addCategory(Intent.CATEGORY_DEFAULT)
3643                .setPackage(resolver.getPackageName());
3644        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3645        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3646                UserHandle.USER_SYSTEM);
3647        if (matches.isEmpty()) {
3648            return null;
3649        }
3650        return matches.get(0).getComponentInfo().getComponentName();
3651    }
3652
3653    private void primeDomainVerificationsLPw(int userId) {
3654        if (DEBUG_DOMAIN_VERIFICATION) {
3655            Slog.d(TAG, "Priming domain verifications in user " + userId);
3656        }
3657
3658        SystemConfig systemConfig = SystemConfig.getInstance();
3659        ArraySet<String> packages = systemConfig.getLinkedApps();
3660
3661        for (String packageName : packages) {
3662            PackageParser.Package pkg = mPackages.get(packageName);
3663            if (pkg != null) {
3664                if (!pkg.isSystem()) {
3665                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3666                    continue;
3667                }
3668
3669                ArraySet<String> domains = null;
3670                for (PackageParser.Activity a : pkg.activities) {
3671                    for (ActivityIntentInfo filter : a.intents) {
3672                        if (hasValidDomains(filter)) {
3673                            if (domains == null) {
3674                                domains = new ArraySet<String>();
3675                            }
3676                            domains.addAll(filter.getHostsList());
3677                        }
3678                    }
3679                }
3680
3681                if (domains != null && domains.size() > 0) {
3682                    if (DEBUG_DOMAIN_VERIFICATION) {
3683                        Slog.v(TAG, "      + " + packageName);
3684                    }
3685                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3686                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3687                    // and then 'always' in the per-user state actually used for intent resolution.
3688                    final IntentFilterVerificationInfo ivi;
3689                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3690                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3691                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3692                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3693                } else {
3694                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3695                            + "' does not handle web links");
3696                }
3697            } else {
3698                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3699            }
3700        }
3701
3702        scheduleWritePackageRestrictionsLocked(userId);
3703        scheduleWriteSettingsLocked();
3704    }
3705
3706    private void applyFactoryDefaultBrowserLPw(int userId) {
3707        // The default browser app's package name is stored in a string resource,
3708        // with a product-specific overlay used for vendor customization.
3709        String browserPkg = mContext.getResources().getString(
3710                com.android.internal.R.string.default_browser);
3711        if (!TextUtils.isEmpty(browserPkg)) {
3712            // non-empty string => required to be a known package
3713            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3714            if (ps == null) {
3715                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3716                browserPkg = null;
3717            } else {
3718                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3719            }
3720        }
3721
3722        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3723        // default.  If there's more than one, just leave everything alone.
3724        if (browserPkg == null) {
3725            calculateDefaultBrowserLPw(userId);
3726        }
3727    }
3728
3729    private void calculateDefaultBrowserLPw(int userId) {
3730        List<String> allBrowsers = resolveAllBrowserApps(userId);
3731        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3732        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3733    }
3734
3735    private List<String> resolveAllBrowserApps(int userId) {
3736        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3737        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3738                PackageManager.MATCH_ALL, userId);
3739
3740        final int count = list.size();
3741        List<String> result = new ArrayList<String>(count);
3742        for (int i=0; i<count; i++) {
3743            ResolveInfo info = list.get(i);
3744            if (info.activityInfo == null
3745                    || !info.handleAllWebDataURI
3746                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3747                    || result.contains(info.activityInfo.packageName)) {
3748                continue;
3749            }
3750            result.add(info.activityInfo.packageName);
3751        }
3752
3753        return result;
3754    }
3755
3756    private boolean packageIsBrowser(String packageName, int userId) {
3757        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3758                PackageManager.MATCH_ALL, userId);
3759        final int N = list.size();
3760        for (int i = 0; i < N; i++) {
3761            ResolveInfo info = list.get(i);
3762            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3763                return true;
3764            }
3765        }
3766        return false;
3767    }
3768
3769    private void checkDefaultBrowser() {
3770        final int myUserId = UserHandle.myUserId();
3771        final String packageName = getDefaultBrowserPackageName(myUserId);
3772        if (packageName != null) {
3773            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3774            if (info == null) {
3775                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3776                synchronized (mPackages) {
3777                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3778                }
3779            }
3780        }
3781    }
3782
3783    @Override
3784    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3785            throws RemoteException {
3786        try {
3787            return super.onTransact(code, data, reply, flags);
3788        } catch (RuntimeException e) {
3789            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3790                Slog.wtf(TAG, "Package Manager Crash", e);
3791            }
3792            throw e;
3793        }
3794    }
3795
3796    static int[] appendInts(int[] cur, int[] add) {
3797        if (add == null) return cur;
3798        if (cur == null) return add;
3799        final int N = add.length;
3800        for (int i=0; i<N; i++) {
3801            cur = appendInt(cur, add[i]);
3802        }
3803        return cur;
3804    }
3805
3806    /**
3807     * Returns whether or not a full application can see an instant application.
3808     * <p>
3809     * Currently, there are three cases in which this can occur:
3810     * <ol>
3811     * <li>The calling application is a "special" process. Special processes
3812     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3813     * <li>The calling application has the permission
3814     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3815     * <li>The calling application is the default launcher on the
3816     *     system partition.</li>
3817     * </ol>
3818     */
3819    private boolean canViewInstantApps(int callingUid, int userId) {
3820        if (callingUid < Process.FIRST_APPLICATION_UID) {
3821            return true;
3822        }
3823        if (mContext.checkCallingOrSelfPermission(
3824                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3825            return true;
3826        }
3827        if (mContext.checkCallingOrSelfPermission(
3828                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3829            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3830            if (homeComponent != null
3831                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3832                return true;
3833            }
3834        }
3835        return false;
3836    }
3837
3838    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3839        if (!sUserManager.exists(userId)) return null;
3840        if (ps == null) {
3841            return null;
3842        }
3843        final int callingUid = Binder.getCallingUid();
3844        // Filter out ephemeral app metadata:
3845        //   * The system/shell/root can see metadata for any app
3846        //   * An installed app can see metadata for 1) other installed apps
3847        //     and 2) ephemeral apps that have explicitly interacted with it
3848        //   * Ephemeral apps can only see their own data and exposed installed apps
3849        //   * Holding a signature permission allows seeing instant apps
3850        if (filterAppAccessLPr(ps, callingUid, userId)) {
3851            return null;
3852        }
3853
3854        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3855                && ps.isSystem()) {
3856            flags |= MATCH_ANY_USER;
3857        }
3858
3859        final PackageUserState state = ps.readUserState(userId);
3860        PackageParser.Package p = ps.pkg;
3861        if (p != null) {
3862            final PermissionsState permissionsState = ps.getPermissionsState();
3863
3864            // Compute GIDs only if requested
3865            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3866                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3867            // Compute granted permissions only if package has requested permissions
3868            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3869                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3870
3871            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3872                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3873
3874            if (packageInfo == null) {
3875                return null;
3876            }
3877
3878            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3879                    resolveExternalPackageNameLPr(p);
3880
3881            return packageInfo;
3882        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3883            PackageInfo pi = new PackageInfo();
3884            pi.packageName = ps.name;
3885            pi.setLongVersionCode(ps.versionCode);
3886            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3887            pi.firstInstallTime = ps.firstInstallTime;
3888            pi.lastUpdateTime = ps.lastUpdateTime;
3889
3890            ApplicationInfo ai = new ApplicationInfo();
3891            ai.packageName = ps.name;
3892            ai.uid = UserHandle.getUid(userId, ps.appId);
3893            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3894            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3895            ai.versionCode = ps.versionCode;
3896            ai.flags = ps.pkgFlags;
3897            ai.privateFlags = ps.pkgPrivateFlags;
3898            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3899
3900            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3901                    + ps.name + "]. Provides a minimum info.");
3902            return pi;
3903        } else {
3904            return null;
3905        }
3906    }
3907
3908    @Override
3909    public void checkPackageStartable(String packageName, int userId) {
3910        final int callingUid = Binder.getCallingUid();
3911        if (getInstantAppPackageName(callingUid) != null) {
3912            throw new SecurityException("Instant applications don't have access to this method");
3913        }
3914        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3915        synchronized (mPackages) {
3916            final PackageSetting ps = mSettings.mPackages.get(packageName);
3917            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3918                throw new SecurityException("Package " + packageName + " was not found!");
3919            }
3920
3921            if (!ps.getInstalled(userId)) {
3922                throw new SecurityException(
3923                        "Package " + packageName + " was not installed for user " + userId + "!");
3924            }
3925
3926            if (mSafeMode && !ps.isSystem()) {
3927                throw new SecurityException("Package " + packageName + " not a system app!");
3928            }
3929
3930            if (mFrozenPackages.contains(packageName)) {
3931                throw new SecurityException("Package " + packageName + " is currently frozen!");
3932            }
3933
3934            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3935                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3936            }
3937        }
3938    }
3939
3940    @Override
3941    public boolean isPackageAvailable(String packageName, int userId) {
3942        if (!sUserManager.exists(userId)) return false;
3943        final int callingUid = Binder.getCallingUid();
3944        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3945                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3946        synchronized (mPackages) {
3947            PackageParser.Package p = mPackages.get(packageName);
3948            if (p != null) {
3949                final PackageSetting ps = (PackageSetting) p.mExtras;
3950                if (filterAppAccessLPr(ps, callingUid, userId)) {
3951                    return false;
3952                }
3953                if (ps != null) {
3954                    final PackageUserState state = ps.readUserState(userId);
3955                    if (state != null) {
3956                        return PackageParser.isAvailable(state);
3957                    }
3958                }
3959            }
3960        }
3961        return false;
3962    }
3963
3964    @Override
3965    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3966        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3967                flags, Binder.getCallingUid(), userId);
3968    }
3969
3970    @Override
3971    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3972            int flags, int userId) {
3973        return getPackageInfoInternal(versionedPackage.getPackageName(),
3974                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3975    }
3976
3977    /**
3978     * Important: The provided filterCallingUid is used exclusively to filter out packages
3979     * that can be seen based on user state. It's typically the original caller uid prior
3980     * to clearing. Because it can only be provided by trusted code, it's value can be
3981     * trusted and will be used as-is; unlike userId which will be validated by this method.
3982     */
3983    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3984            int flags, int filterCallingUid, int userId) {
3985        if (!sUserManager.exists(userId)) return null;
3986        flags = updateFlagsForPackage(flags, userId, packageName);
3987        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3988                false /* requireFullPermission */, false /* checkShell */, "get package info");
3989
3990        // reader
3991        synchronized (mPackages) {
3992            // Normalize package name to handle renamed packages and static libs
3993            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3994
3995            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3996            if (matchFactoryOnly) {
3997                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3998                if (ps != null) {
3999                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4000                        return null;
4001                    }
4002                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4003                        return null;
4004                    }
4005                    return generatePackageInfo(ps, flags, userId);
4006                }
4007            }
4008
4009            PackageParser.Package p = mPackages.get(packageName);
4010            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4011                return null;
4012            }
4013            if (DEBUG_PACKAGE_INFO)
4014                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4015            if (p != null) {
4016                final PackageSetting ps = (PackageSetting) p.mExtras;
4017                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4018                    return null;
4019                }
4020                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4021                    return null;
4022                }
4023                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4024            }
4025            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4026                final PackageSetting ps = mSettings.mPackages.get(packageName);
4027                if (ps == null) return null;
4028                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4029                    return null;
4030                }
4031                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4032                    return null;
4033                }
4034                return generatePackageInfo(ps, flags, userId);
4035            }
4036        }
4037        return null;
4038    }
4039
4040    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4041        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4042            return true;
4043        }
4044        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4045            return true;
4046        }
4047        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4048            return true;
4049        }
4050        return false;
4051    }
4052
4053    private boolean isComponentVisibleToInstantApp(
4054            @Nullable ComponentName component, @ComponentType int type) {
4055        if (type == TYPE_ACTIVITY) {
4056            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4057            return activity != null
4058                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4059                    : false;
4060        } else if (type == TYPE_RECEIVER) {
4061            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4062            return activity != null
4063                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4064                    : false;
4065        } else if (type == TYPE_SERVICE) {
4066            final PackageParser.Service service = mServices.mServices.get(component);
4067            return service != null
4068                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4069                    : false;
4070        } else if (type == TYPE_PROVIDER) {
4071            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4072            return provider != null
4073                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4074                    : false;
4075        } else if (type == TYPE_UNKNOWN) {
4076            return isComponentVisibleToInstantApp(component);
4077        }
4078        return false;
4079    }
4080
4081    /**
4082     * Returns whether or not access to the application should be filtered.
4083     * <p>
4084     * Access may be limited based upon whether the calling or target applications
4085     * are instant applications.
4086     *
4087     * @see #canAccessInstantApps(int)
4088     */
4089    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4090            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4091        // if we're in an isolated process, get the real calling UID
4092        if (Process.isIsolated(callingUid)) {
4093            callingUid = mIsolatedOwners.get(callingUid);
4094        }
4095        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4096        final boolean callerIsInstantApp = instantAppPkgName != null;
4097        if (ps == null) {
4098            if (callerIsInstantApp) {
4099                // pretend the application exists, but, needs to be filtered
4100                return true;
4101            }
4102            return false;
4103        }
4104        // if the target and caller are the same application, don't filter
4105        if (isCallerSameApp(ps.name, callingUid)) {
4106            return false;
4107        }
4108        if (callerIsInstantApp) {
4109            // request for a specific component; if it hasn't been explicitly exposed, filter
4110            if (component != null) {
4111                return !isComponentVisibleToInstantApp(component, componentType);
4112            }
4113            // request for application; if no components have been explicitly exposed, filter
4114            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4115        }
4116        if (ps.getInstantApp(userId)) {
4117            // caller can see all components of all instant applications, don't filter
4118            if (canViewInstantApps(callingUid, userId)) {
4119                return false;
4120            }
4121            // request for a specific instant application component, filter
4122            if (component != null) {
4123                return true;
4124            }
4125            // request for an instant application; if the caller hasn't been granted access, filter
4126            return !mInstantAppRegistry.isInstantAccessGranted(
4127                    userId, UserHandle.getAppId(callingUid), ps.appId);
4128        }
4129        return false;
4130    }
4131
4132    /**
4133     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4134     */
4135    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4136        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4137    }
4138
4139    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4140            int flags) {
4141        // Callers can access only the libs they depend on, otherwise they need to explicitly
4142        // ask for the shared libraries given the caller is allowed to access all static libs.
4143        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4144            // System/shell/root get to see all static libs
4145            final int appId = UserHandle.getAppId(uid);
4146            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4147                    || appId == Process.ROOT_UID) {
4148                return false;
4149            }
4150        }
4151
4152        // No package means no static lib as it is always on internal storage
4153        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4154            return false;
4155        }
4156
4157        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4158                ps.pkg.staticSharedLibVersion);
4159        if (libEntry == null) {
4160            return false;
4161        }
4162
4163        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4164        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4165        if (uidPackageNames == null) {
4166            return true;
4167        }
4168
4169        for (String uidPackageName : uidPackageNames) {
4170            if (ps.name.equals(uidPackageName)) {
4171                return false;
4172            }
4173            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4174            if (uidPs != null) {
4175                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4176                        libEntry.info.getName());
4177                if (index < 0) {
4178                    continue;
4179                }
4180                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4181                    return false;
4182                }
4183            }
4184        }
4185        return true;
4186    }
4187
4188    @Override
4189    public String[] currentToCanonicalPackageNames(String[] names) {
4190        final int callingUid = Binder.getCallingUid();
4191        if (getInstantAppPackageName(callingUid) != null) {
4192            return names;
4193        }
4194        final String[] out = new String[names.length];
4195        // reader
4196        synchronized (mPackages) {
4197            final int callingUserId = UserHandle.getUserId(callingUid);
4198            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4199            for (int i=names.length-1; i>=0; i--) {
4200                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4201                boolean translateName = false;
4202                if (ps != null && ps.realName != null) {
4203                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4204                    translateName = !targetIsInstantApp
4205                            || canViewInstantApps
4206                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4207                                    UserHandle.getAppId(callingUid), ps.appId);
4208                }
4209                out[i] = translateName ? ps.realName : names[i];
4210            }
4211        }
4212        return out;
4213    }
4214
4215    @Override
4216    public String[] canonicalToCurrentPackageNames(String[] names) {
4217        final int callingUid = Binder.getCallingUid();
4218        if (getInstantAppPackageName(callingUid) != null) {
4219            return names;
4220        }
4221        final String[] out = new String[names.length];
4222        // reader
4223        synchronized (mPackages) {
4224            final int callingUserId = UserHandle.getUserId(callingUid);
4225            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4226            for (int i=names.length-1; i>=0; i--) {
4227                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4228                boolean translateName = false;
4229                if (cur != null) {
4230                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4231                    final boolean targetIsInstantApp =
4232                            ps != null && ps.getInstantApp(callingUserId);
4233                    translateName = !targetIsInstantApp
4234                            || canViewInstantApps
4235                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4236                                    UserHandle.getAppId(callingUid), ps.appId);
4237                }
4238                out[i] = translateName ? cur : names[i];
4239            }
4240        }
4241        return out;
4242    }
4243
4244    @Override
4245    public int getPackageUid(String packageName, int flags, int userId) {
4246        if (!sUserManager.exists(userId)) return -1;
4247        final int callingUid = Binder.getCallingUid();
4248        flags = updateFlagsForPackage(flags, userId, packageName);
4249        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4250                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4251
4252        // reader
4253        synchronized (mPackages) {
4254            final PackageParser.Package p = mPackages.get(packageName);
4255            if (p != null && p.isMatch(flags)) {
4256                PackageSetting ps = (PackageSetting) p.mExtras;
4257                if (filterAppAccessLPr(ps, callingUid, userId)) {
4258                    return -1;
4259                }
4260                return UserHandle.getUid(userId, p.applicationInfo.uid);
4261            }
4262            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4263                final PackageSetting ps = mSettings.mPackages.get(packageName);
4264                if (ps != null && ps.isMatch(flags)
4265                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4266                    return UserHandle.getUid(userId, ps.appId);
4267                }
4268            }
4269        }
4270
4271        return -1;
4272    }
4273
4274    @Override
4275    public int[] getPackageGids(String packageName, int flags, int userId) {
4276        if (!sUserManager.exists(userId)) return null;
4277        final int callingUid = Binder.getCallingUid();
4278        flags = updateFlagsForPackage(flags, userId, packageName);
4279        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4280                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4281
4282        // reader
4283        synchronized (mPackages) {
4284            final PackageParser.Package p = mPackages.get(packageName);
4285            if (p != null && p.isMatch(flags)) {
4286                PackageSetting ps = (PackageSetting) p.mExtras;
4287                if (filterAppAccessLPr(ps, callingUid, userId)) {
4288                    return null;
4289                }
4290                // TODO: Shouldn't this be checking for package installed state for userId and
4291                // return null?
4292                return ps.getPermissionsState().computeGids(userId);
4293            }
4294            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4295                final PackageSetting ps = mSettings.mPackages.get(packageName);
4296                if (ps != null && ps.isMatch(flags)
4297                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4298                    return ps.getPermissionsState().computeGids(userId);
4299                }
4300            }
4301        }
4302
4303        return null;
4304    }
4305
4306    @Override
4307    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4308        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4309    }
4310
4311    @Override
4312    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4313            int flags) {
4314        final List<PermissionInfo> permissionList =
4315                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4316        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4317    }
4318
4319    @Override
4320    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4321        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4322    }
4323
4324    @Override
4325    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4326        final List<PermissionGroupInfo> permissionList =
4327                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4328        return (permissionList == null)
4329                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4330    }
4331
4332    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4333            int filterCallingUid, int userId) {
4334        if (!sUserManager.exists(userId)) return null;
4335        PackageSetting ps = mSettings.mPackages.get(packageName);
4336        if (ps != null) {
4337            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4338                return null;
4339            }
4340            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4341                return null;
4342            }
4343            if (ps.pkg == null) {
4344                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4345                if (pInfo != null) {
4346                    return pInfo.applicationInfo;
4347                }
4348                return null;
4349            }
4350            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4351                    ps.readUserState(userId), userId);
4352            if (ai != null) {
4353                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4354            }
4355            return ai;
4356        }
4357        return null;
4358    }
4359
4360    @Override
4361    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4362        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4363    }
4364
4365    /**
4366     * Important: The provided filterCallingUid is used exclusively to filter out applications
4367     * that can be seen based on user state. It's typically the original caller uid prior
4368     * to clearing. Because it can only be provided by trusted code, it's value can be
4369     * trusted and will be used as-is; unlike userId which will be validated by this method.
4370     */
4371    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4372            int filterCallingUid, int userId) {
4373        if (!sUserManager.exists(userId)) return null;
4374        flags = updateFlagsForApplication(flags, userId, packageName);
4375        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4376                false /* requireFullPermission */, false /* checkShell */, "get application info");
4377
4378        // writer
4379        synchronized (mPackages) {
4380            // Normalize package name to handle renamed packages and static libs
4381            packageName = resolveInternalPackageNameLPr(packageName,
4382                    PackageManager.VERSION_CODE_HIGHEST);
4383
4384            PackageParser.Package p = mPackages.get(packageName);
4385            if (DEBUG_PACKAGE_INFO) Log.v(
4386                    TAG, "getApplicationInfo " + packageName
4387                    + ": " + p);
4388            if (p != null) {
4389                PackageSetting ps = mSettings.mPackages.get(packageName);
4390                if (ps == null) return null;
4391                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4392                    return null;
4393                }
4394                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4395                    return null;
4396                }
4397                // Note: isEnabledLP() does not apply here - always return info
4398                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4399                        p, flags, ps.readUserState(userId), userId);
4400                if (ai != null) {
4401                    ai.packageName = resolveExternalPackageNameLPr(p);
4402                }
4403                return ai;
4404            }
4405            if ("android".equals(packageName)||"system".equals(packageName)) {
4406                return mAndroidApplication;
4407            }
4408            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4409                // Already generates the external package name
4410                return generateApplicationInfoFromSettingsLPw(packageName,
4411                        flags, filterCallingUid, userId);
4412            }
4413        }
4414        return null;
4415    }
4416
4417    private String normalizePackageNameLPr(String packageName) {
4418        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4419        return normalizedPackageName != null ? normalizedPackageName : packageName;
4420    }
4421
4422    @Override
4423    public void deletePreloadsFileCache() {
4424        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4425            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4426        }
4427        File dir = Environment.getDataPreloadsFileCacheDirectory();
4428        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4429        FileUtils.deleteContents(dir);
4430    }
4431
4432    @Override
4433    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4434            final int storageFlags, final IPackageDataObserver observer) {
4435        mContext.enforceCallingOrSelfPermission(
4436                android.Manifest.permission.CLEAR_APP_CACHE, null);
4437        mHandler.post(() -> {
4438            boolean success = false;
4439            try {
4440                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4441                success = true;
4442            } catch (IOException e) {
4443                Slog.w(TAG, e);
4444            }
4445            if (observer != null) {
4446                try {
4447                    observer.onRemoveCompleted(null, success);
4448                } catch (RemoteException e) {
4449                    Slog.w(TAG, e);
4450                }
4451            }
4452        });
4453    }
4454
4455    @Override
4456    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4457            final int storageFlags, final IntentSender pi) {
4458        mContext.enforceCallingOrSelfPermission(
4459                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4460        mHandler.post(() -> {
4461            boolean success = false;
4462            try {
4463                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4464                success = true;
4465            } catch (IOException e) {
4466                Slog.w(TAG, e);
4467            }
4468            if (pi != null) {
4469                try {
4470                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4471                } catch (SendIntentException e) {
4472                    Slog.w(TAG, e);
4473                }
4474            }
4475        });
4476    }
4477
4478    /**
4479     * Blocking call to clear various types of cached data across the system
4480     * until the requested bytes are available.
4481     */
4482    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4483        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4484        final File file = storage.findPathForUuid(volumeUuid);
4485        if (file.getUsableSpace() >= bytes) return;
4486
4487        if (ENABLE_FREE_CACHE_V2) {
4488            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4489                    volumeUuid);
4490            final boolean aggressive = (storageFlags
4491                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4492            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4493
4494            // 1. Pre-flight to determine if we have any chance to succeed
4495            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4496            if (internalVolume && (aggressive || SystemProperties
4497                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4498                deletePreloadsFileCache();
4499                if (file.getUsableSpace() >= bytes) return;
4500            }
4501
4502            // 3. Consider parsed APK data (aggressive only)
4503            if (internalVolume && aggressive) {
4504                FileUtils.deleteContents(mCacheDir);
4505                if (file.getUsableSpace() >= bytes) return;
4506            }
4507
4508            // 4. Consider cached app data (above quotas)
4509            try {
4510                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4511                        Installer.FLAG_FREE_CACHE_V2);
4512            } catch (InstallerException ignored) {
4513            }
4514            if (file.getUsableSpace() >= bytes) return;
4515
4516            // 5. Consider shared libraries with refcount=0 and age>min cache period
4517            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4518                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4519                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4520                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4521                return;
4522            }
4523
4524            // 6. Consider dexopt output (aggressive only)
4525            // TODO: Implement
4526
4527            // 7. Consider installed instant apps unused longer than min cache period
4528            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4529                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4530                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4531                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4532                return;
4533            }
4534
4535            // 8. Consider cached app data (below quotas)
4536            try {
4537                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4538                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4539            } catch (InstallerException ignored) {
4540            }
4541            if (file.getUsableSpace() >= bytes) return;
4542
4543            // 9. Consider DropBox entries
4544            // TODO: Implement
4545
4546            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4547            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4548                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4549                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4550                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4551                return;
4552            }
4553        } else {
4554            try {
4555                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4556            } catch (InstallerException ignored) {
4557            }
4558            if (file.getUsableSpace() >= bytes) return;
4559        }
4560
4561        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4562    }
4563
4564    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4565            throws IOException {
4566        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4567        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4568
4569        List<VersionedPackage> packagesToDelete = null;
4570        final long now = System.currentTimeMillis();
4571
4572        synchronized (mPackages) {
4573            final int[] allUsers = sUserManager.getUserIds();
4574            final int libCount = mSharedLibraries.size();
4575            for (int i = 0; i < libCount; i++) {
4576                final LongSparseArray<SharedLibraryEntry> versionedLib
4577                        = mSharedLibraries.valueAt(i);
4578                if (versionedLib == null) {
4579                    continue;
4580                }
4581                final int versionCount = versionedLib.size();
4582                for (int j = 0; j < versionCount; j++) {
4583                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4584                    // Skip packages that are not static shared libs.
4585                    if (!libInfo.isStatic()) {
4586                        break;
4587                    }
4588                    // Important: We skip static shared libs used for some user since
4589                    // in such a case we need to keep the APK on the device. The check for
4590                    // a lib being used for any user is performed by the uninstall call.
4591                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4592                    // Resolve the package name - we use synthetic package names internally
4593                    final String internalPackageName = resolveInternalPackageNameLPr(
4594                            declaringPackage.getPackageName(),
4595                            declaringPackage.getLongVersionCode());
4596                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4597                    // Skip unused static shared libs cached less than the min period
4598                    // to prevent pruning a lib needed by a subsequently installed package.
4599                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4600                        continue;
4601                    }
4602                    if (packagesToDelete == null) {
4603                        packagesToDelete = new ArrayList<>();
4604                    }
4605                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4606                            declaringPackage.getLongVersionCode()));
4607                }
4608            }
4609        }
4610
4611        if (packagesToDelete != null) {
4612            final int packageCount = packagesToDelete.size();
4613            for (int i = 0; i < packageCount; i++) {
4614                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4615                // Delete the package synchronously (will fail of the lib used for any user).
4616                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4617                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4618                                == PackageManager.DELETE_SUCCEEDED) {
4619                    if (volume.getUsableSpace() >= neededSpace) {
4620                        return true;
4621                    }
4622                }
4623            }
4624        }
4625
4626        return false;
4627    }
4628
4629    /**
4630     * Update given flags based on encryption status of current user.
4631     */
4632    private int updateFlags(int flags, int userId) {
4633        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4634                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4635            // Caller expressed an explicit opinion about what encryption
4636            // aware/unaware components they want to see, so fall through and
4637            // give them what they want
4638        } else {
4639            // Caller expressed no opinion, so match based on user state
4640            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4641                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4642            } else {
4643                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4644            }
4645        }
4646        return flags;
4647    }
4648
4649    private UserManagerInternal getUserManagerInternal() {
4650        if (mUserManagerInternal == null) {
4651            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4652        }
4653        return mUserManagerInternal;
4654    }
4655
4656    private ActivityManagerInternal getActivityManagerInternal() {
4657        if (mActivityManagerInternal == null) {
4658            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4659        }
4660        return mActivityManagerInternal;
4661    }
4662
4663
4664    private DeviceIdleController.LocalService getDeviceIdleController() {
4665        if (mDeviceIdleController == null) {
4666            mDeviceIdleController =
4667                    LocalServices.getService(DeviceIdleController.LocalService.class);
4668        }
4669        return mDeviceIdleController;
4670    }
4671
4672    /**
4673     * Update given flags when being used to request {@link PackageInfo}.
4674     */
4675    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4676        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4677        boolean triaged = true;
4678        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4679                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4680            // Caller is asking for component details, so they'd better be
4681            // asking for specific encryption matching behavior, or be triaged
4682            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4683                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4684                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4685                triaged = false;
4686            }
4687        }
4688        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4689                | PackageManager.MATCH_SYSTEM_ONLY
4690                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4691            triaged = false;
4692        }
4693        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4694            mPermissionManager.enforceCrossUserPermission(
4695                    Binder.getCallingUid(), userId, false, false,
4696                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4697                    + Debug.getCallers(5));
4698        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4699                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4700            // If the caller wants all packages and has a restricted profile associated with it,
4701            // then match all users. This is to make sure that launchers that need to access work
4702            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4703            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4704            flags |= PackageManager.MATCH_ANY_USER;
4705        }
4706        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4707            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4708                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4709        }
4710        return updateFlags(flags, userId);
4711    }
4712
4713    /**
4714     * Update given flags when being used to request {@link ApplicationInfo}.
4715     */
4716    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4717        return updateFlagsForPackage(flags, userId, cookie);
4718    }
4719
4720    /**
4721     * Update given flags when being used to request {@link ComponentInfo}.
4722     */
4723    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4724        if (cookie instanceof Intent) {
4725            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4726                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4727            }
4728        }
4729
4730        boolean triaged = true;
4731        // Caller is asking for component details, so they'd better be
4732        // asking for specific encryption matching behavior, or be triaged
4733        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4734                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4735                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4736            triaged = false;
4737        }
4738        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4739            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4740                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4741        }
4742
4743        return updateFlags(flags, userId);
4744    }
4745
4746    /**
4747     * Update given intent when being used to request {@link ResolveInfo}.
4748     */
4749    private Intent updateIntentForResolve(Intent intent) {
4750        if (intent.getSelector() != null) {
4751            intent = intent.getSelector();
4752        }
4753        if (DEBUG_PREFERRED) {
4754            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4755        }
4756        return intent;
4757    }
4758
4759    /**
4760     * Update given flags when being used to request {@link ResolveInfo}.
4761     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4762     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4763     * flag set. However, this flag is only honoured in three circumstances:
4764     * <ul>
4765     * <li>when called from a system process</li>
4766     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4767     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4768     * action and a {@code android.intent.category.BROWSABLE} category</li>
4769     * </ul>
4770     */
4771    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4772        return updateFlagsForResolve(flags, userId, intent, callingUid,
4773                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4774    }
4775    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4776            boolean wantInstantApps) {
4777        return updateFlagsForResolve(flags, userId, intent, callingUid,
4778                wantInstantApps, false /*onlyExposedExplicitly*/);
4779    }
4780    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4781            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4782        // Safe mode means we shouldn't match any third-party components
4783        if (mSafeMode) {
4784            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4785        }
4786        if (getInstantAppPackageName(callingUid) != null) {
4787            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4788            if (onlyExposedExplicitly) {
4789                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4790            }
4791            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4792            flags |= PackageManager.MATCH_INSTANT;
4793        } else {
4794            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4795            final boolean allowMatchInstant = wantInstantApps
4796                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4797            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4798                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4799            if (!allowMatchInstant) {
4800                flags &= ~PackageManager.MATCH_INSTANT;
4801            }
4802        }
4803        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4804    }
4805
4806    @Override
4807    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4808        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4809    }
4810
4811    /**
4812     * Important: The provided filterCallingUid is used exclusively to filter out activities
4813     * that can be seen based on user state. It's typically the original caller uid prior
4814     * to clearing. Because it can only be provided by trusted code, it's value can be
4815     * trusted and will be used as-is; unlike userId which will be validated by this method.
4816     */
4817    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4818            int filterCallingUid, int userId) {
4819        if (!sUserManager.exists(userId)) return null;
4820        flags = updateFlagsForComponent(flags, userId, component);
4821
4822        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4823            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4824                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4825        }
4826
4827        synchronized (mPackages) {
4828            PackageParser.Activity a = mActivities.mActivities.get(component);
4829
4830            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4831            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4832                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4833                if (ps == null) return null;
4834                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4835                    return null;
4836                }
4837                return PackageParser.generateActivityInfo(
4838                        a, flags, ps.readUserState(userId), userId);
4839            }
4840            if (mResolveComponentName.equals(component)) {
4841                return PackageParser.generateActivityInfo(
4842                        mResolveActivity, flags, new PackageUserState(), userId);
4843            }
4844        }
4845        return null;
4846    }
4847
4848    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4849        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4850            return false;
4851        }
4852        final long token = Binder.clearCallingIdentity();
4853        try {
4854            final int callingUserId = UserHandle.getUserId(callingUid);
4855            if (ActivityManager.getCurrentUser() != callingUserId) {
4856                return false;
4857            }
4858            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4859        } finally {
4860            Binder.restoreCallingIdentity(token);
4861        }
4862    }
4863
4864    @Override
4865    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4866            String resolvedType) {
4867        synchronized (mPackages) {
4868            if (component.equals(mResolveComponentName)) {
4869                // The resolver supports EVERYTHING!
4870                return true;
4871            }
4872            final int callingUid = Binder.getCallingUid();
4873            final int callingUserId = UserHandle.getUserId(callingUid);
4874            PackageParser.Activity a = mActivities.mActivities.get(component);
4875            if (a == null) {
4876                return false;
4877            }
4878            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4879            if (ps == null) {
4880                return false;
4881            }
4882            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4883                return false;
4884            }
4885            for (int i=0; i<a.intents.size(); i++) {
4886                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4887                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4888                    return true;
4889                }
4890            }
4891            return false;
4892        }
4893    }
4894
4895    @Override
4896    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4897        if (!sUserManager.exists(userId)) return null;
4898        final int callingUid = Binder.getCallingUid();
4899        flags = updateFlagsForComponent(flags, userId, component);
4900        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4901                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4902        synchronized (mPackages) {
4903            PackageParser.Activity a = mReceivers.mActivities.get(component);
4904            if (DEBUG_PACKAGE_INFO) Log.v(
4905                TAG, "getReceiverInfo " + component + ": " + a);
4906            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4907                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4908                if (ps == null) return null;
4909                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4910                    return null;
4911                }
4912                return PackageParser.generateActivityInfo(
4913                        a, flags, ps.readUserState(userId), userId);
4914            }
4915        }
4916        return null;
4917    }
4918
4919    @Override
4920    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4921            int flags, int userId) {
4922        if (!sUserManager.exists(userId)) return null;
4923        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4924        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4925            return null;
4926        }
4927
4928        flags = updateFlagsForPackage(flags, userId, null);
4929
4930        final boolean canSeeStaticLibraries =
4931                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4932                        == PERMISSION_GRANTED
4933                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4934                        == PERMISSION_GRANTED
4935                || canRequestPackageInstallsInternal(packageName,
4936                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4937                        false  /* throwIfPermNotDeclared*/)
4938                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4939                        == PERMISSION_GRANTED;
4940
4941        synchronized (mPackages) {
4942            List<SharedLibraryInfo> result = null;
4943
4944            final int libCount = mSharedLibraries.size();
4945            for (int i = 0; i < libCount; i++) {
4946                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4947                if (versionedLib == null) {
4948                    continue;
4949                }
4950
4951                final int versionCount = versionedLib.size();
4952                for (int j = 0; j < versionCount; j++) {
4953                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4954                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4955                        break;
4956                    }
4957                    final long identity = Binder.clearCallingIdentity();
4958                    try {
4959                        PackageInfo packageInfo = getPackageInfoVersioned(
4960                                libInfo.getDeclaringPackage(), flags
4961                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4962                        if (packageInfo == null) {
4963                            continue;
4964                        }
4965                    } finally {
4966                        Binder.restoreCallingIdentity(identity);
4967                    }
4968
4969                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4970                            libInfo.getLongVersion(), libInfo.getType(),
4971                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4972                            flags, userId));
4973
4974                    if (result == null) {
4975                        result = new ArrayList<>();
4976                    }
4977                    result.add(resLibInfo);
4978                }
4979            }
4980
4981            return result != null ? new ParceledListSlice<>(result) : null;
4982        }
4983    }
4984
4985    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4986            SharedLibraryInfo libInfo, int flags, int userId) {
4987        List<VersionedPackage> versionedPackages = null;
4988        final int packageCount = mSettings.mPackages.size();
4989        for (int i = 0; i < packageCount; i++) {
4990            PackageSetting ps = mSettings.mPackages.valueAt(i);
4991
4992            if (ps == null) {
4993                continue;
4994            }
4995
4996            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4997                continue;
4998            }
4999
5000            final String libName = libInfo.getName();
5001            if (libInfo.isStatic()) {
5002                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5003                if (libIdx < 0) {
5004                    continue;
5005                }
5006                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5007                    continue;
5008                }
5009                if (versionedPackages == null) {
5010                    versionedPackages = new ArrayList<>();
5011                }
5012                // If the dependent is a static shared lib, use the public package name
5013                String dependentPackageName = ps.name;
5014                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5015                    dependentPackageName = ps.pkg.manifestPackageName;
5016                }
5017                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5018            } else if (ps.pkg != null) {
5019                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5020                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5021                    if (versionedPackages == null) {
5022                        versionedPackages = new ArrayList<>();
5023                    }
5024                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5025                }
5026            }
5027        }
5028
5029        return versionedPackages;
5030    }
5031
5032    @Override
5033    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5034        if (!sUserManager.exists(userId)) return null;
5035        final int callingUid = Binder.getCallingUid();
5036        flags = updateFlagsForComponent(flags, userId, component);
5037        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5038                false /* requireFullPermission */, false /* checkShell */, "get service info");
5039        synchronized (mPackages) {
5040            PackageParser.Service s = mServices.mServices.get(component);
5041            if (DEBUG_PACKAGE_INFO) Log.v(
5042                TAG, "getServiceInfo " + component + ": " + s);
5043            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5044                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5045                if (ps == null) return null;
5046                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5047                    return null;
5048                }
5049                return PackageParser.generateServiceInfo(
5050                        s, flags, ps.readUserState(userId), userId);
5051            }
5052        }
5053        return null;
5054    }
5055
5056    @Override
5057    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5058        if (!sUserManager.exists(userId)) return null;
5059        final int callingUid = Binder.getCallingUid();
5060        flags = updateFlagsForComponent(flags, userId, component);
5061        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5062                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5063        synchronized (mPackages) {
5064            PackageParser.Provider p = mProviders.mProviders.get(component);
5065            if (DEBUG_PACKAGE_INFO) Log.v(
5066                TAG, "getProviderInfo " + component + ": " + p);
5067            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5068                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5069                if (ps == null) return null;
5070                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5071                    return null;
5072                }
5073                return PackageParser.generateProviderInfo(
5074                        p, flags, ps.readUserState(userId), userId);
5075            }
5076        }
5077        return null;
5078    }
5079
5080    @Override
5081    public String[] getSystemSharedLibraryNames() {
5082        // allow instant applications
5083        synchronized (mPackages) {
5084            Set<String> libs = null;
5085            final int libCount = mSharedLibraries.size();
5086            for (int i = 0; i < libCount; i++) {
5087                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5088                if (versionedLib == null) {
5089                    continue;
5090                }
5091                final int versionCount = versionedLib.size();
5092                for (int j = 0; j < versionCount; j++) {
5093                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5094                    if (!libEntry.info.isStatic()) {
5095                        if (libs == null) {
5096                            libs = new ArraySet<>();
5097                        }
5098                        libs.add(libEntry.info.getName());
5099                        break;
5100                    }
5101                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5102                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5103                            UserHandle.getUserId(Binder.getCallingUid()),
5104                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5105                        if (libs == null) {
5106                            libs = new ArraySet<>();
5107                        }
5108                        libs.add(libEntry.info.getName());
5109                        break;
5110                    }
5111                }
5112            }
5113
5114            if (libs != null) {
5115                String[] libsArray = new String[libs.size()];
5116                libs.toArray(libsArray);
5117                return libsArray;
5118            }
5119
5120            return null;
5121        }
5122    }
5123
5124    @Override
5125    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5126        // allow instant applications
5127        synchronized (mPackages) {
5128            return mServicesSystemSharedLibraryPackageName;
5129        }
5130    }
5131
5132    @Override
5133    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5134        // allow instant applications
5135        synchronized (mPackages) {
5136            return mSharedSystemSharedLibraryPackageName;
5137        }
5138    }
5139
5140    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5141        for (int i = userList.length - 1; i >= 0; --i) {
5142            final int userId = userList[i];
5143            // don't add instant app to the list of updates
5144            if (pkgSetting.getInstantApp(userId)) {
5145                continue;
5146            }
5147            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5148            if (changedPackages == null) {
5149                changedPackages = new SparseArray<>();
5150                mChangedPackages.put(userId, changedPackages);
5151            }
5152            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5153            if (sequenceNumbers == null) {
5154                sequenceNumbers = new HashMap<>();
5155                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5156            }
5157            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5158            if (sequenceNumber != null) {
5159                changedPackages.remove(sequenceNumber);
5160            }
5161            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5162            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5163        }
5164        mChangedPackagesSequenceNumber++;
5165    }
5166
5167    @Override
5168    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5169        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5170            return null;
5171        }
5172        synchronized (mPackages) {
5173            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5174                return null;
5175            }
5176            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5177            if (changedPackages == null) {
5178                return null;
5179            }
5180            final List<String> packageNames =
5181                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5182            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5183                final String packageName = changedPackages.get(i);
5184                if (packageName != null) {
5185                    packageNames.add(packageName);
5186                }
5187            }
5188            return packageNames.isEmpty()
5189                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5190        }
5191    }
5192
5193    @Override
5194    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5195        // allow instant applications
5196        ArrayList<FeatureInfo> res;
5197        synchronized (mAvailableFeatures) {
5198            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5199            res.addAll(mAvailableFeatures.values());
5200        }
5201        final FeatureInfo fi = new FeatureInfo();
5202        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5203                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5204        res.add(fi);
5205
5206        return new ParceledListSlice<>(res);
5207    }
5208
5209    @Override
5210    public boolean hasSystemFeature(String name, int version) {
5211        // allow instant applications
5212        synchronized (mAvailableFeatures) {
5213            final FeatureInfo feat = mAvailableFeatures.get(name);
5214            if (feat == null) {
5215                return false;
5216            } else {
5217                return feat.version >= version;
5218            }
5219        }
5220    }
5221
5222    @Override
5223    public int checkPermission(String permName, String pkgName, int userId) {
5224        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5225    }
5226
5227    @Override
5228    public int checkUidPermission(String permName, int uid) {
5229        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5230    }
5231
5232    @Override
5233    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5234        if (UserHandle.getCallingUserId() != userId) {
5235            mContext.enforceCallingPermission(
5236                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5237                    "isPermissionRevokedByPolicy for user " + userId);
5238        }
5239
5240        if (checkPermission(permission, packageName, userId)
5241                == PackageManager.PERMISSION_GRANTED) {
5242            return false;
5243        }
5244
5245        final int callingUid = Binder.getCallingUid();
5246        if (getInstantAppPackageName(callingUid) != null) {
5247            if (!isCallerSameApp(packageName, callingUid)) {
5248                return false;
5249            }
5250        } else {
5251            if (isInstantApp(packageName, userId)) {
5252                return false;
5253            }
5254        }
5255
5256        final long identity = Binder.clearCallingIdentity();
5257        try {
5258            final int flags = getPermissionFlags(permission, packageName, userId);
5259            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5260        } finally {
5261            Binder.restoreCallingIdentity(identity);
5262        }
5263    }
5264
5265    @Override
5266    public String getPermissionControllerPackageName() {
5267        synchronized (mPackages) {
5268            return mRequiredInstallerPackage;
5269        }
5270    }
5271
5272    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5273        return mPermissionManager.addDynamicPermission(
5274                info, async, getCallingUid(), new PermissionCallback() {
5275                    @Override
5276                    public void onPermissionChanged() {
5277                        if (!async) {
5278                            mSettings.writeLPr();
5279                        } else {
5280                            scheduleWriteSettingsLocked();
5281                        }
5282                    }
5283                });
5284    }
5285
5286    @Override
5287    public boolean addPermission(PermissionInfo info) {
5288        synchronized (mPackages) {
5289            return addDynamicPermission(info, false);
5290        }
5291    }
5292
5293    @Override
5294    public boolean addPermissionAsync(PermissionInfo info) {
5295        synchronized (mPackages) {
5296            return addDynamicPermission(info, true);
5297        }
5298    }
5299
5300    @Override
5301    public void removePermission(String permName) {
5302        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5303    }
5304
5305    @Override
5306    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5307        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5308                getCallingUid(), userId, mPermissionCallback);
5309    }
5310
5311    @Override
5312    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5313        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5314                getCallingUid(), userId, mPermissionCallback);
5315    }
5316
5317    @Override
5318    public void resetRuntimePermissions() {
5319        mContext.enforceCallingOrSelfPermission(
5320                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5321                "revokeRuntimePermission");
5322
5323        int callingUid = Binder.getCallingUid();
5324        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5325            mContext.enforceCallingOrSelfPermission(
5326                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5327                    "resetRuntimePermissions");
5328        }
5329
5330        synchronized (mPackages) {
5331            mPermissionManager.updateAllPermissions(
5332                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5333                    mPermissionCallback);
5334            for (int userId : UserManagerService.getInstance().getUserIds()) {
5335                final int packageCount = mPackages.size();
5336                for (int i = 0; i < packageCount; i++) {
5337                    PackageParser.Package pkg = mPackages.valueAt(i);
5338                    if (!(pkg.mExtras instanceof PackageSetting)) {
5339                        continue;
5340                    }
5341                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5342                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5343                }
5344            }
5345        }
5346    }
5347
5348    @Override
5349    public int getPermissionFlags(String permName, String packageName, int userId) {
5350        return mPermissionManager.getPermissionFlags(
5351                permName, packageName, getCallingUid(), userId);
5352    }
5353
5354    @Override
5355    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5356            int flagValues, int userId) {
5357        mPermissionManager.updatePermissionFlags(
5358                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5359                mPermissionCallback);
5360    }
5361
5362    /**
5363     * Update the permission flags for all packages and runtime permissions of a user in order
5364     * to allow device or profile owner to remove POLICY_FIXED.
5365     */
5366    @Override
5367    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5368        synchronized (mPackages) {
5369            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5370                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5371                    mPermissionCallback);
5372            if (changed) {
5373                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5374            }
5375        }
5376    }
5377
5378    @Override
5379    public boolean shouldShowRequestPermissionRationale(String permissionName,
5380            String packageName, int userId) {
5381        if (UserHandle.getCallingUserId() != userId) {
5382            mContext.enforceCallingPermission(
5383                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5384                    "canShowRequestPermissionRationale for user " + userId);
5385        }
5386
5387        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5388        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5389            return false;
5390        }
5391
5392        if (checkPermission(permissionName, packageName, userId)
5393                == PackageManager.PERMISSION_GRANTED) {
5394            return false;
5395        }
5396
5397        final int flags;
5398
5399        final long identity = Binder.clearCallingIdentity();
5400        try {
5401            flags = getPermissionFlags(permissionName,
5402                    packageName, userId);
5403        } finally {
5404            Binder.restoreCallingIdentity(identity);
5405        }
5406
5407        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5408                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5409                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5410
5411        if ((flags & fixedFlags) != 0) {
5412            return false;
5413        }
5414
5415        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5416    }
5417
5418    @Override
5419    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5420        mContext.enforceCallingOrSelfPermission(
5421                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5422                "addOnPermissionsChangeListener");
5423
5424        synchronized (mPackages) {
5425            mOnPermissionChangeListeners.addListenerLocked(listener);
5426        }
5427    }
5428
5429    @Override
5430    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5431        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5432            throw new SecurityException("Instant applications don't have access to this method");
5433        }
5434        synchronized (mPackages) {
5435            mOnPermissionChangeListeners.removeListenerLocked(listener);
5436        }
5437    }
5438
5439    @Override
5440    public boolean isProtectedBroadcast(String actionName) {
5441        // allow instant applications
5442        synchronized (mProtectedBroadcasts) {
5443            if (mProtectedBroadcasts.contains(actionName)) {
5444                return true;
5445            } else if (actionName != null) {
5446                // TODO: remove these terrible hacks
5447                if (actionName.startsWith("android.net.netmon.lingerExpired")
5448                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5449                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5450                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5451                    return true;
5452                }
5453            }
5454        }
5455        return false;
5456    }
5457
5458    @Override
5459    public int checkSignatures(String pkg1, String pkg2) {
5460        synchronized (mPackages) {
5461            final PackageParser.Package p1 = mPackages.get(pkg1);
5462            final PackageParser.Package p2 = mPackages.get(pkg2);
5463            if (p1 == null || p1.mExtras == null
5464                    || p2 == null || p2.mExtras == null) {
5465                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5466            }
5467            final int callingUid = Binder.getCallingUid();
5468            final int callingUserId = UserHandle.getUserId(callingUid);
5469            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5470            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5471            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5472                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5473                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5474            }
5475            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5476        }
5477    }
5478
5479    @Override
5480    public int checkUidSignatures(int uid1, int uid2) {
5481        final int callingUid = Binder.getCallingUid();
5482        final int callingUserId = UserHandle.getUserId(callingUid);
5483        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5484        // Map to base uids.
5485        uid1 = UserHandle.getAppId(uid1);
5486        uid2 = UserHandle.getAppId(uid2);
5487        // reader
5488        synchronized (mPackages) {
5489            Signature[] s1;
5490            Signature[] s2;
5491            Object obj = mSettings.getUserIdLPr(uid1);
5492            if (obj != null) {
5493                if (obj instanceof SharedUserSetting) {
5494                    if (isCallerInstantApp) {
5495                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5496                    }
5497                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5498                } else if (obj instanceof PackageSetting) {
5499                    final PackageSetting ps = (PackageSetting) obj;
5500                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5501                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5502                    }
5503                    s1 = ps.signatures.mSigningDetails.signatures;
5504                } else {
5505                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5506                }
5507            } else {
5508                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5509            }
5510            obj = mSettings.getUserIdLPr(uid2);
5511            if (obj != null) {
5512                if (obj instanceof SharedUserSetting) {
5513                    if (isCallerInstantApp) {
5514                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5515                    }
5516                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5517                } else if (obj instanceof PackageSetting) {
5518                    final PackageSetting ps = (PackageSetting) obj;
5519                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5520                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5521                    }
5522                    s2 = ps.signatures.mSigningDetails.signatures;
5523                } else {
5524                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5525                }
5526            } else {
5527                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5528            }
5529            return compareSignatures(s1, s2);
5530        }
5531    }
5532
5533    @Override
5534    public boolean hasSigningCertificate(
5535            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5536
5537        synchronized (mPackages) {
5538            final PackageParser.Package p = mPackages.get(packageName);
5539            if (p == null || p.mExtras == null) {
5540                return false;
5541            }
5542            final int callingUid = Binder.getCallingUid();
5543            final int callingUserId = UserHandle.getUserId(callingUid);
5544            final PackageSetting ps = (PackageSetting) p.mExtras;
5545            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5546                return false;
5547            }
5548            switch (type) {
5549                case CERT_INPUT_RAW_X509:
5550                    return p.mSigningDetails.hasCertificate(certificate);
5551                case CERT_INPUT_SHA256:
5552                    return p.mSigningDetails.hasSha256Certificate(certificate);
5553                default:
5554                    return false;
5555            }
5556        }
5557    }
5558
5559    @Override
5560    public boolean hasUidSigningCertificate(
5561            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5562        final int callingUid = Binder.getCallingUid();
5563        final int callingUserId = UserHandle.getUserId(callingUid);
5564        // Map to base uids.
5565        uid = UserHandle.getAppId(uid);
5566        // reader
5567        synchronized (mPackages) {
5568            final PackageParser.SigningDetails signingDetails;
5569            final Object obj = mSettings.getUserIdLPr(uid);
5570            if (obj != null) {
5571                if (obj instanceof SharedUserSetting) {
5572                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5573                    if (isCallerInstantApp) {
5574                        return false;
5575                    }
5576                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5577                } else if (obj instanceof PackageSetting) {
5578                    final PackageSetting ps = (PackageSetting) obj;
5579                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5580                        return false;
5581                    }
5582                    signingDetails = ps.signatures.mSigningDetails;
5583                } else {
5584                    return false;
5585                }
5586            } else {
5587                return false;
5588            }
5589            switch (type) {
5590                case CERT_INPUT_RAW_X509:
5591                    return signingDetails.hasCertificate(certificate);
5592                case CERT_INPUT_SHA256:
5593                    return signingDetails.hasSha256Certificate(certificate);
5594                default:
5595                    return false;
5596            }
5597        }
5598    }
5599
5600    /**
5601     * This method should typically only be used when granting or revoking
5602     * permissions, since the app may immediately restart after this call.
5603     * <p>
5604     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5605     * guard your work against the app being relaunched.
5606     */
5607    private void killUid(int appId, int userId, String reason) {
5608        final long identity = Binder.clearCallingIdentity();
5609        try {
5610            IActivityManager am = ActivityManager.getService();
5611            if (am != null) {
5612                try {
5613                    am.killUid(appId, userId, reason);
5614                } catch (RemoteException e) {
5615                    /* ignore - same process */
5616                }
5617            }
5618        } finally {
5619            Binder.restoreCallingIdentity(identity);
5620        }
5621    }
5622
5623    /**
5624     * If the database version for this type of package (internal storage or
5625     * external storage) is less than the version where package signatures
5626     * were updated, return true.
5627     */
5628    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5629        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5630        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5631    }
5632
5633    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5634        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5635        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5636    }
5637
5638    @Override
5639    public List<String> getAllPackages() {
5640        final int callingUid = Binder.getCallingUid();
5641        final int callingUserId = UserHandle.getUserId(callingUid);
5642        synchronized (mPackages) {
5643            if (canViewInstantApps(callingUid, callingUserId)) {
5644                return new ArrayList<String>(mPackages.keySet());
5645            }
5646            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5647            final List<String> result = new ArrayList<>();
5648            if (instantAppPkgName != null) {
5649                // caller is an instant application; filter unexposed applications
5650                for (PackageParser.Package pkg : mPackages.values()) {
5651                    if (!pkg.visibleToInstantApps) {
5652                        continue;
5653                    }
5654                    result.add(pkg.packageName);
5655                }
5656            } else {
5657                // caller is a normal application; filter instant applications
5658                for (PackageParser.Package pkg : mPackages.values()) {
5659                    final PackageSetting ps =
5660                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5661                    if (ps != null
5662                            && ps.getInstantApp(callingUserId)
5663                            && !mInstantAppRegistry.isInstantAccessGranted(
5664                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5665                        continue;
5666                    }
5667                    result.add(pkg.packageName);
5668                }
5669            }
5670            return result;
5671        }
5672    }
5673
5674    @Override
5675    public String[] getPackagesForUid(int uid) {
5676        final int callingUid = Binder.getCallingUid();
5677        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5678        final int userId = UserHandle.getUserId(uid);
5679        uid = UserHandle.getAppId(uid);
5680        // reader
5681        synchronized (mPackages) {
5682            Object obj = mSettings.getUserIdLPr(uid);
5683            if (obj instanceof SharedUserSetting) {
5684                if (isCallerInstantApp) {
5685                    return null;
5686                }
5687                final SharedUserSetting sus = (SharedUserSetting) obj;
5688                final int N = sus.packages.size();
5689                String[] res = new String[N];
5690                final Iterator<PackageSetting> it = sus.packages.iterator();
5691                int i = 0;
5692                while (it.hasNext()) {
5693                    PackageSetting ps = it.next();
5694                    if (ps.getInstalled(userId)) {
5695                        res[i++] = ps.name;
5696                    } else {
5697                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5698                    }
5699                }
5700                return res;
5701            } else if (obj instanceof PackageSetting) {
5702                final PackageSetting ps = (PackageSetting) obj;
5703                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5704                    return new String[]{ps.name};
5705                }
5706            }
5707        }
5708        return null;
5709    }
5710
5711    @Override
5712    public String getNameForUid(int uid) {
5713        final int callingUid = Binder.getCallingUid();
5714        if (getInstantAppPackageName(callingUid) != null) {
5715            return null;
5716        }
5717        synchronized (mPackages) {
5718            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5719            if (obj instanceof SharedUserSetting) {
5720                final SharedUserSetting sus = (SharedUserSetting) obj;
5721                return sus.name + ":" + sus.userId;
5722            } else if (obj instanceof PackageSetting) {
5723                final PackageSetting ps = (PackageSetting) obj;
5724                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5725                    return null;
5726                }
5727                return ps.name;
5728            }
5729            return null;
5730        }
5731    }
5732
5733    @Override
5734    public String[] getNamesForUids(int[] uids) {
5735        if (uids == null || uids.length == 0) {
5736            return null;
5737        }
5738        final int callingUid = Binder.getCallingUid();
5739        if (getInstantAppPackageName(callingUid) != null) {
5740            return null;
5741        }
5742        final String[] names = new String[uids.length];
5743        synchronized (mPackages) {
5744            for (int i = uids.length - 1; i >= 0; i--) {
5745                final int uid = uids[i];
5746                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5747                if (obj instanceof SharedUserSetting) {
5748                    final SharedUserSetting sus = (SharedUserSetting) obj;
5749                    names[i] = "shared:" + sus.name;
5750                } else if (obj instanceof PackageSetting) {
5751                    final PackageSetting ps = (PackageSetting) obj;
5752                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5753                        names[i] = null;
5754                    } else {
5755                        names[i] = ps.name;
5756                    }
5757                } else {
5758                    names[i] = null;
5759                }
5760            }
5761        }
5762        return names;
5763    }
5764
5765    @Override
5766    public int getUidForSharedUser(String sharedUserName) {
5767        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5768            return -1;
5769        }
5770        if (sharedUserName == null) {
5771            return -1;
5772        }
5773        // reader
5774        synchronized (mPackages) {
5775            SharedUserSetting suid;
5776            try {
5777                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5778                if (suid != null) {
5779                    return suid.userId;
5780                }
5781            } catch (PackageManagerException ignore) {
5782                // can't happen, but, still need to catch it
5783            }
5784            return -1;
5785        }
5786    }
5787
5788    @Override
5789    public int getFlagsForUid(int uid) {
5790        final int callingUid = Binder.getCallingUid();
5791        if (getInstantAppPackageName(callingUid) != null) {
5792            return 0;
5793        }
5794        synchronized (mPackages) {
5795            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5796            if (obj instanceof SharedUserSetting) {
5797                final SharedUserSetting sus = (SharedUserSetting) obj;
5798                return sus.pkgFlags;
5799            } else if (obj instanceof PackageSetting) {
5800                final PackageSetting ps = (PackageSetting) obj;
5801                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5802                    return 0;
5803                }
5804                return ps.pkgFlags;
5805            }
5806        }
5807        return 0;
5808    }
5809
5810    @Override
5811    public int getPrivateFlagsForUid(int uid) {
5812        final int callingUid = Binder.getCallingUid();
5813        if (getInstantAppPackageName(callingUid) != null) {
5814            return 0;
5815        }
5816        synchronized (mPackages) {
5817            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5818            if (obj instanceof SharedUserSetting) {
5819                final SharedUserSetting sus = (SharedUserSetting) obj;
5820                return sus.pkgPrivateFlags;
5821            } else if (obj instanceof PackageSetting) {
5822                final PackageSetting ps = (PackageSetting) obj;
5823                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5824                    return 0;
5825                }
5826                return ps.pkgPrivateFlags;
5827            }
5828        }
5829        return 0;
5830    }
5831
5832    @Override
5833    public boolean isUidPrivileged(int uid) {
5834        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5835            return false;
5836        }
5837        uid = UserHandle.getAppId(uid);
5838        // reader
5839        synchronized (mPackages) {
5840            Object obj = mSettings.getUserIdLPr(uid);
5841            if (obj instanceof SharedUserSetting) {
5842                final SharedUserSetting sus = (SharedUserSetting) obj;
5843                final Iterator<PackageSetting> it = sus.packages.iterator();
5844                while (it.hasNext()) {
5845                    if (it.next().isPrivileged()) {
5846                        return true;
5847                    }
5848                }
5849            } else if (obj instanceof PackageSetting) {
5850                final PackageSetting ps = (PackageSetting) obj;
5851                return ps.isPrivileged();
5852            }
5853        }
5854        return false;
5855    }
5856
5857    @Override
5858    public String[] getAppOpPermissionPackages(String permName) {
5859        return mPermissionManager.getAppOpPermissionPackages(permName);
5860    }
5861
5862    @Override
5863    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5864            int flags, int userId) {
5865        return resolveIntentInternal(
5866                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5867    }
5868
5869    /**
5870     * Normally instant apps can only be resolved when they're visible to the caller.
5871     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5872     * since we need to allow the system to start any installed application.
5873     */
5874    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5875            int flags, int userId, boolean resolveForStart) {
5876        try {
5877            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5878
5879            if (!sUserManager.exists(userId)) return null;
5880            final int callingUid = Binder.getCallingUid();
5881            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5882            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5883                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5884
5885            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5886            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5887                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5888            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5889
5890            final ResolveInfo bestChoice =
5891                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5892            return bestChoice;
5893        } finally {
5894            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5895        }
5896    }
5897
5898    @Override
5899    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5900        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5901            throw new SecurityException(
5902                    "findPersistentPreferredActivity can only be run by the system");
5903        }
5904        if (!sUserManager.exists(userId)) {
5905            return null;
5906        }
5907        final int callingUid = Binder.getCallingUid();
5908        intent = updateIntentForResolve(intent);
5909        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5910        final int flags = updateFlagsForResolve(
5911                0, userId, intent, callingUid, false /*includeInstantApps*/);
5912        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5913                userId);
5914        synchronized (mPackages) {
5915            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5916                    userId);
5917        }
5918    }
5919
5920    @Override
5921    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5922            IntentFilter filter, int match, ComponentName activity) {
5923        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5924            return;
5925        }
5926        final int userId = UserHandle.getCallingUserId();
5927        if (DEBUG_PREFERRED) {
5928            Log.v(TAG, "setLastChosenActivity intent=" + intent
5929                + " resolvedType=" + resolvedType
5930                + " flags=" + flags
5931                + " filter=" + filter
5932                + " match=" + match
5933                + " activity=" + activity);
5934            filter.dump(new PrintStreamPrinter(System.out), "    ");
5935        }
5936        intent.setComponent(null);
5937        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5938                userId);
5939        // Find any earlier preferred or last chosen entries and nuke them
5940        findPreferredActivity(intent, resolvedType,
5941                flags, query, 0, false, true, false, userId);
5942        // Add the new activity as the last chosen for this filter
5943        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5944                "Setting last chosen");
5945    }
5946
5947    @Override
5948    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5949        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5950            return null;
5951        }
5952        final int userId = UserHandle.getCallingUserId();
5953        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5954        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5955                userId);
5956        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5957                false, false, false, userId);
5958    }
5959
5960    /**
5961     * Returns whether or not instant apps have been disabled remotely.
5962     */
5963    private boolean isEphemeralDisabled() {
5964        return mEphemeralAppsDisabled;
5965    }
5966
5967    private boolean isInstantAppAllowed(
5968            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5969            boolean skipPackageCheck) {
5970        if (mInstantAppResolverConnection == null) {
5971            return false;
5972        }
5973        if (mInstantAppInstallerActivity == null) {
5974            return false;
5975        }
5976        if (intent.getComponent() != null) {
5977            return false;
5978        }
5979        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5980            return false;
5981        }
5982        if (!skipPackageCheck && intent.getPackage() != null) {
5983            return false;
5984        }
5985        if (!intent.isBrowsableWebIntent()) {
5986            // for non web intents, we should not resolve externally if an app already exists to
5987            // handle it or if the caller didn't explicitly request it.
5988            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5989                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5990                return false;
5991            }
5992        } else if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5993            return false;
5994        }
5995        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5996        // Or if there's already an ephemeral app installed that handles the action
5997        synchronized (mPackages) {
5998            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5999            for (int n = 0; n < count; n++) {
6000                final ResolveInfo info = resolvedActivities.get(n);
6001                final String packageName = info.activityInfo.packageName;
6002                final PackageSetting ps = mSettings.mPackages.get(packageName);
6003                if (ps != null) {
6004                    // only check domain verification status if the app is not a browser
6005                    if (!info.handleAllWebDataURI) {
6006                        // Try to get the status from User settings first
6007                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6008                        final int status = (int) (packedStatus >> 32);
6009                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6010                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6011                            if (DEBUG_INSTANT) {
6012                                Slog.v(TAG, "DENY instant app;"
6013                                    + " pkg: " + packageName + ", status: " + status);
6014                            }
6015                            return false;
6016                        }
6017                    }
6018                    if (ps.getInstantApp(userId)) {
6019                        if (DEBUG_INSTANT) {
6020                            Slog.v(TAG, "DENY instant app installed;"
6021                                    + " pkg: " + packageName);
6022                        }
6023                        return false;
6024                    }
6025                }
6026            }
6027        }
6028        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6029        return true;
6030    }
6031
6032    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6033            Intent origIntent, String resolvedType, String callingPackage,
6034            Bundle verificationBundle, int userId) {
6035        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6036                new InstantAppRequest(responseObj, origIntent, resolvedType,
6037                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6038        mHandler.sendMessage(msg);
6039    }
6040
6041    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6042            int flags, List<ResolveInfo> query, int userId) {
6043        if (query != null) {
6044            final int N = query.size();
6045            if (N == 1) {
6046                return query.get(0);
6047            } else if (N > 1) {
6048                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6049                // If there is more than one activity with the same priority,
6050                // then let the user decide between them.
6051                ResolveInfo r0 = query.get(0);
6052                ResolveInfo r1 = query.get(1);
6053                if (DEBUG_INTENT_MATCHING || debug) {
6054                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6055                            + r1.activityInfo.name + "=" + r1.priority);
6056                }
6057                // If the first activity has a higher priority, or a different
6058                // default, then it is always desirable to pick it.
6059                if (r0.priority != r1.priority
6060                        || r0.preferredOrder != r1.preferredOrder
6061                        || r0.isDefault != r1.isDefault) {
6062                    return query.get(0);
6063                }
6064                // If we have saved a preference for a preferred activity for
6065                // this Intent, use that.
6066                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6067                        flags, query, r0.priority, true, false, debug, userId);
6068                if (ri != null) {
6069                    return ri;
6070                }
6071                // If we have an ephemeral app, use it
6072                for (int i = 0; i < N; i++) {
6073                    ri = query.get(i);
6074                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6075                        final String packageName = ri.activityInfo.packageName;
6076                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6077                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6078                        final int status = (int)(packedStatus >> 32);
6079                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6080                            return ri;
6081                        }
6082                    }
6083                }
6084                ri = new ResolveInfo(mResolveInfo);
6085                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6086                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6087                // If all of the options come from the same package, show the application's
6088                // label and icon instead of the generic resolver's.
6089                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6090                // and then throw away the ResolveInfo itself, meaning that the caller loses
6091                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6092                // a fallback for this case; we only set the target package's resources on
6093                // the ResolveInfo, not the ActivityInfo.
6094                final String intentPackage = intent.getPackage();
6095                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6096                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6097                    ri.resolvePackageName = intentPackage;
6098                    if (userNeedsBadging(userId)) {
6099                        ri.noResourceId = true;
6100                    } else {
6101                        ri.icon = appi.icon;
6102                    }
6103                    ri.iconResourceId = appi.icon;
6104                    ri.labelRes = appi.labelRes;
6105                }
6106                ri.activityInfo.applicationInfo = new ApplicationInfo(
6107                        ri.activityInfo.applicationInfo);
6108                if (userId != 0) {
6109                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6110                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6111                }
6112                // Make sure that the resolver is displayable in car mode
6113                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6114                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6115                return ri;
6116            }
6117        }
6118        return null;
6119    }
6120
6121    /**
6122     * Return true if the given list is not empty and all of its contents have
6123     * an activityInfo with the given package name.
6124     */
6125    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6126        if (ArrayUtils.isEmpty(list)) {
6127            return false;
6128        }
6129        for (int i = 0, N = list.size(); i < N; i++) {
6130            final ResolveInfo ri = list.get(i);
6131            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6132            if (ai == null || !packageName.equals(ai.packageName)) {
6133                return false;
6134            }
6135        }
6136        return true;
6137    }
6138
6139    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6140            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6141        final int N = query.size();
6142        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6143                .get(userId);
6144        // Get the list of persistent preferred activities that handle the intent
6145        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6146        List<PersistentPreferredActivity> pprefs = ppir != null
6147                ? ppir.queryIntent(intent, resolvedType,
6148                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6149                        userId)
6150                : null;
6151        if (pprefs != null && pprefs.size() > 0) {
6152            final int M = pprefs.size();
6153            for (int i=0; i<M; i++) {
6154                final PersistentPreferredActivity ppa = pprefs.get(i);
6155                if (DEBUG_PREFERRED || debug) {
6156                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6157                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6158                            + "\n  component=" + ppa.mComponent);
6159                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6160                }
6161                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6162                        flags | MATCH_DISABLED_COMPONENTS, userId);
6163                if (DEBUG_PREFERRED || debug) {
6164                    Slog.v(TAG, "Found persistent preferred activity:");
6165                    if (ai != null) {
6166                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6167                    } else {
6168                        Slog.v(TAG, "  null");
6169                    }
6170                }
6171                if (ai == null) {
6172                    // This previously registered persistent preferred activity
6173                    // component is no longer known. Ignore it and do NOT remove it.
6174                    continue;
6175                }
6176                for (int j=0; j<N; j++) {
6177                    final ResolveInfo ri = query.get(j);
6178                    if (!ri.activityInfo.applicationInfo.packageName
6179                            .equals(ai.applicationInfo.packageName)) {
6180                        continue;
6181                    }
6182                    if (!ri.activityInfo.name.equals(ai.name)) {
6183                        continue;
6184                    }
6185                    //  Found a persistent preference that can handle the intent.
6186                    if (DEBUG_PREFERRED || debug) {
6187                        Slog.v(TAG, "Returning persistent preferred activity: " +
6188                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6189                    }
6190                    return ri;
6191                }
6192            }
6193        }
6194        return null;
6195    }
6196
6197    // TODO: handle preferred activities missing while user has amnesia
6198    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6199            List<ResolveInfo> query, int priority, boolean always,
6200            boolean removeMatches, boolean debug, int userId) {
6201        if (!sUserManager.exists(userId)) return null;
6202        final int callingUid = Binder.getCallingUid();
6203        flags = updateFlagsForResolve(
6204                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6205        intent = updateIntentForResolve(intent);
6206        // writer
6207        synchronized (mPackages) {
6208            // Try to find a matching persistent preferred activity.
6209            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6210                    debug, userId);
6211
6212            // If a persistent preferred activity matched, use it.
6213            if (pri != null) {
6214                return pri;
6215            }
6216
6217            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6218            // Get the list of preferred activities that handle the intent
6219            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6220            List<PreferredActivity> prefs = pir != null
6221                    ? pir.queryIntent(intent, resolvedType,
6222                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6223                            userId)
6224                    : null;
6225            if (prefs != null && prefs.size() > 0) {
6226                boolean changed = false;
6227                try {
6228                    // First figure out how good the original match set is.
6229                    // We will only allow preferred activities that came
6230                    // from the same match quality.
6231                    int match = 0;
6232
6233                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6234
6235                    final int N = query.size();
6236                    for (int j=0; j<N; j++) {
6237                        final ResolveInfo ri = query.get(j);
6238                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6239                                + ": 0x" + Integer.toHexString(match));
6240                        if (ri.match > match) {
6241                            match = ri.match;
6242                        }
6243                    }
6244
6245                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6246                            + Integer.toHexString(match));
6247
6248                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6249                    final int M = prefs.size();
6250                    for (int i=0; i<M; i++) {
6251                        final PreferredActivity pa = prefs.get(i);
6252                        if (DEBUG_PREFERRED || debug) {
6253                            Slog.v(TAG, "Checking PreferredActivity ds="
6254                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6255                                    + "\n  component=" + pa.mPref.mComponent);
6256                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6257                        }
6258                        if (pa.mPref.mMatch != match) {
6259                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6260                                    + Integer.toHexString(pa.mPref.mMatch));
6261                            continue;
6262                        }
6263                        // If it's not an "always" type preferred activity and that's what we're
6264                        // looking for, skip it.
6265                        if (always && !pa.mPref.mAlways) {
6266                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6267                            continue;
6268                        }
6269                        final ActivityInfo ai = getActivityInfo(
6270                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6271                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6272                                userId);
6273                        if (DEBUG_PREFERRED || debug) {
6274                            Slog.v(TAG, "Found preferred activity:");
6275                            if (ai != null) {
6276                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6277                            } else {
6278                                Slog.v(TAG, "  null");
6279                            }
6280                        }
6281                        if (ai == null) {
6282                            // This previously registered preferred activity
6283                            // component is no longer known.  Most likely an update
6284                            // to the app was installed and in the new version this
6285                            // component no longer exists.  Clean it up by removing
6286                            // it from the preferred activities list, and skip it.
6287                            Slog.w(TAG, "Removing dangling preferred activity: "
6288                                    + pa.mPref.mComponent);
6289                            pir.removeFilter(pa);
6290                            changed = true;
6291                            continue;
6292                        }
6293                        for (int j=0; j<N; j++) {
6294                            final ResolveInfo ri = query.get(j);
6295                            if (!ri.activityInfo.applicationInfo.packageName
6296                                    .equals(ai.applicationInfo.packageName)) {
6297                                continue;
6298                            }
6299                            if (!ri.activityInfo.name.equals(ai.name)) {
6300                                continue;
6301                            }
6302
6303                            if (removeMatches) {
6304                                pir.removeFilter(pa);
6305                                changed = true;
6306                                if (DEBUG_PREFERRED) {
6307                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6308                                }
6309                                break;
6310                            }
6311
6312                            // Okay we found a previously set preferred or last chosen app.
6313                            // If the result set is different from when this
6314                            // was created, and is not a subset of the preferred set, we need to
6315                            // clear it and re-ask the user their preference, if we're looking for
6316                            // an "always" type entry.
6317                            if (always && !pa.mPref.sameSet(query)) {
6318                                if (pa.mPref.isSuperset(query)) {
6319                                    // some components of the set are no longer present in
6320                                    // the query, but the preferred activity can still be reused
6321                                    if (DEBUG_PREFERRED) {
6322                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6323                                                + " still valid as only non-preferred components"
6324                                                + " were removed for " + intent + " type "
6325                                                + resolvedType);
6326                                    }
6327                                    // remove obsolete components and re-add the up-to-date filter
6328                                    PreferredActivity freshPa = new PreferredActivity(pa,
6329                                            pa.mPref.mMatch,
6330                                            pa.mPref.discardObsoleteComponents(query),
6331                                            pa.mPref.mComponent,
6332                                            pa.mPref.mAlways);
6333                                    pir.removeFilter(pa);
6334                                    pir.addFilter(freshPa);
6335                                    changed = true;
6336                                } else {
6337                                    Slog.i(TAG,
6338                                            "Result set changed, dropping preferred activity for "
6339                                                    + intent + " type " + resolvedType);
6340                                    if (DEBUG_PREFERRED) {
6341                                        Slog.v(TAG, "Removing preferred activity since set changed "
6342                                                + pa.mPref.mComponent);
6343                                    }
6344                                    pir.removeFilter(pa);
6345                                    // Re-add the filter as a "last chosen" entry (!always)
6346                                    PreferredActivity lastChosen = new PreferredActivity(
6347                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6348                                    pir.addFilter(lastChosen);
6349                                    changed = true;
6350                                    return null;
6351                                }
6352                            }
6353
6354                            // Yay! Either the set matched or we're looking for the last chosen
6355                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6356                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6357                            return ri;
6358                        }
6359                    }
6360                } finally {
6361                    if (changed) {
6362                        if (DEBUG_PREFERRED) {
6363                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6364                        }
6365                        scheduleWritePackageRestrictionsLocked(userId);
6366                    }
6367                }
6368            }
6369        }
6370        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6371        return null;
6372    }
6373
6374    /*
6375     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6376     */
6377    @Override
6378    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6379            int targetUserId) {
6380        mContext.enforceCallingOrSelfPermission(
6381                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6382        List<CrossProfileIntentFilter> matches =
6383                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6384        if (matches != null) {
6385            int size = matches.size();
6386            for (int i = 0; i < size; i++) {
6387                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6388            }
6389        }
6390        if (intent.hasWebURI()) {
6391            // cross-profile app linking works only towards the parent.
6392            final int callingUid = Binder.getCallingUid();
6393            final UserInfo parent = getProfileParent(sourceUserId);
6394            synchronized(mPackages) {
6395                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6396                        false /*includeInstantApps*/);
6397                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6398                        intent, resolvedType, flags, sourceUserId, parent.id);
6399                return xpDomainInfo != null;
6400            }
6401        }
6402        return false;
6403    }
6404
6405    private UserInfo getProfileParent(int userId) {
6406        final long identity = Binder.clearCallingIdentity();
6407        try {
6408            return sUserManager.getProfileParent(userId);
6409        } finally {
6410            Binder.restoreCallingIdentity(identity);
6411        }
6412    }
6413
6414    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6415            String resolvedType, int userId) {
6416        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6417        if (resolver != null) {
6418            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6419        }
6420        return null;
6421    }
6422
6423    @Override
6424    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6425            String resolvedType, int flags, int userId) {
6426        try {
6427            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6428
6429            return new ParceledListSlice<>(
6430                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6431        } finally {
6432            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6433        }
6434    }
6435
6436    /**
6437     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6438     * instant, returns {@code null}.
6439     */
6440    private String getInstantAppPackageName(int callingUid) {
6441        synchronized (mPackages) {
6442            // If the caller is an isolated app use the owner's uid for the lookup.
6443            if (Process.isIsolated(callingUid)) {
6444                callingUid = mIsolatedOwners.get(callingUid);
6445            }
6446            final int appId = UserHandle.getAppId(callingUid);
6447            final Object obj = mSettings.getUserIdLPr(appId);
6448            if (obj instanceof PackageSetting) {
6449                final PackageSetting ps = (PackageSetting) obj;
6450                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6451                return isInstantApp ? ps.pkg.packageName : null;
6452            }
6453        }
6454        return null;
6455    }
6456
6457    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6458            String resolvedType, int flags, int userId) {
6459        return queryIntentActivitiesInternal(
6460                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6461                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6462    }
6463
6464    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6465            String resolvedType, int flags, int filterCallingUid, int userId,
6466            boolean resolveForStart, boolean allowDynamicSplits) {
6467        if (!sUserManager.exists(userId)) return Collections.emptyList();
6468        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6469        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6470                false /* requireFullPermission */, false /* checkShell */,
6471                "query intent activities");
6472        final String pkgName = intent.getPackage();
6473        ComponentName comp = intent.getComponent();
6474        if (comp == null) {
6475            if (intent.getSelector() != null) {
6476                intent = intent.getSelector();
6477                comp = intent.getComponent();
6478            }
6479        }
6480
6481        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6482                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6483        if (comp != null) {
6484            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6485            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6486            if (ai != null) {
6487                // When specifying an explicit component, we prevent the activity from being
6488                // used when either 1) the calling package is normal and the activity is within
6489                // an ephemeral application or 2) the calling package is ephemeral and the
6490                // activity is not visible to ephemeral applications.
6491                final boolean matchInstantApp =
6492                        (flags & PackageManager.MATCH_INSTANT) != 0;
6493                final boolean matchVisibleToInstantAppOnly =
6494                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6495                final boolean matchExplicitlyVisibleOnly =
6496                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6497                final boolean isCallerInstantApp =
6498                        instantAppPkgName != null;
6499                final boolean isTargetSameInstantApp =
6500                        comp.getPackageName().equals(instantAppPkgName);
6501                final boolean isTargetInstantApp =
6502                        (ai.applicationInfo.privateFlags
6503                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6504                final boolean isTargetVisibleToInstantApp =
6505                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6506                final boolean isTargetExplicitlyVisibleToInstantApp =
6507                        isTargetVisibleToInstantApp
6508                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6509                final boolean isTargetHiddenFromInstantApp =
6510                        !isTargetVisibleToInstantApp
6511                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6512                final boolean blockResolution =
6513                        !isTargetSameInstantApp
6514                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6515                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6516                                        && isTargetHiddenFromInstantApp));
6517                if (!blockResolution) {
6518                    final ResolveInfo ri = new ResolveInfo();
6519                    ri.activityInfo = ai;
6520                    list.add(ri);
6521                }
6522            }
6523            return applyPostResolutionFilter(
6524                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6525        }
6526
6527        // reader
6528        boolean sortResult = false;
6529        boolean addEphemeral = false;
6530        List<ResolveInfo> result;
6531        final boolean ephemeralDisabled = isEphemeralDisabled();
6532        synchronized (mPackages) {
6533            if (pkgName == null) {
6534                List<CrossProfileIntentFilter> matchingFilters =
6535                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6536                // Check for results that need to skip the current profile.
6537                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6538                        resolvedType, flags, userId);
6539                if (xpResolveInfo != null) {
6540                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6541                    xpResult.add(xpResolveInfo);
6542                    return applyPostResolutionFilter(
6543                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6544                            allowDynamicSplits, filterCallingUid, userId);
6545                }
6546
6547                // Check for results in the current profile.
6548                result = filterIfNotSystemUser(mActivities.queryIntent(
6549                        intent, resolvedType, flags, userId), userId);
6550                addEphemeral = !ephemeralDisabled
6551                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6552                // Check for cross profile results.
6553                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6554                xpResolveInfo = queryCrossProfileIntents(
6555                        matchingFilters, intent, resolvedType, flags, userId,
6556                        hasNonNegativePriorityResult);
6557                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6558                    boolean isVisibleToUser = filterIfNotSystemUser(
6559                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6560                    if (isVisibleToUser) {
6561                        result.add(xpResolveInfo);
6562                        sortResult = true;
6563                    }
6564                }
6565                if (intent.hasWebURI()) {
6566                    CrossProfileDomainInfo xpDomainInfo = null;
6567                    final UserInfo parent = getProfileParent(userId);
6568                    if (parent != null) {
6569                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6570                                flags, userId, parent.id);
6571                    }
6572                    if (xpDomainInfo != null) {
6573                        if (xpResolveInfo != null) {
6574                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6575                            // in the result.
6576                            result.remove(xpResolveInfo);
6577                        }
6578                        if (result.size() == 0 && !addEphemeral) {
6579                            // No result in current profile, but found candidate in parent user.
6580                            // And we are not going to add emphemeral app, so we can return the
6581                            // result straight away.
6582                            result.add(xpDomainInfo.resolveInfo);
6583                            return applyPostResolutionFilter(result, instantAppPkgName,
6584                                    allowDynamicSplits, filterCallingUid, userId);
6585                        }
6586                    } else if (result.size() <= 1 && !addEphemeral) {
6587                        // No result in parent user and <= 1 result in current profile, and we
6588                        // are not going to add emphemeral app, so we can return the result without
6589                        // further processing.
6590                        return applyPostResolutionFilter(result, instantAppPkgName,
6591                                allowDynamicSplits, filterCallingUid, userId);
6592                    }
6593                    // We have more than one candidate (combining results from current and parent
6594                    // profile), so we need filtering and sorting.
6595                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6596                            intent, flags, result, xpDomainInfo, userId);
6597                    sortResult = true;
6598                }
6599            } else {
6600                final PackageParser.Package pkg = mPackages.get(pkgName);
6601                result = null;
6602                if (pkg != null) {
6603                    result = filterIfNotSystemUser(
6604                            mActivities.queryIntentForPackage(
6605                                    intent, resolvedType, flags, pkg.activities, userId),
6606                            userId);
6607                }
6608                if (result == null || result.size() == 0) {
6609                    // the caller wants to resolve for a particular package; however, there
6610                    // were no installed results, so, try to find an ephemeral result
6611                    addEphemeral = !ephemeralDisabled
6612                            && isInstantAppAllowed(
6613                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6614                    if (result == null) {
6615                        result = new ArrayList<>();
6616                    }
6617                }
6618            }
6619        }
6620        if (addEphemeral) {
6621            result = maybeAddInstantAppInstaller(
6622                    result, intent, resolvedType, flags, userId, resolveForStart);
6623        }
6624        if (sortResult) {
6625            Collections.sort(result, mResolvePrioritySorter);
6626        }
6627        return applyPostResolutionFilter(
6628                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6629    }
6630
6631    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6632            String resolvedType, int flags, int userId, boolean resolveForStart) {
6633        // first, check to see if we've got an instant app already installed
6634        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6635        ResolveInfo localInstantApp = null;
6636        boolean blockResolution = false;
6637        if (!alreadyResolvedLocally) {
6638            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6639                    flags
6640                        | PackageManager.GET_RESOLVED_FILTER
6641                        | PackageManager.MATCH_INSTANT
6642                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6643                    userId);
6644            for (int i = instantApps.size() - 1; i >= 0; --i) {
6645                final ResolveInfo info = instantApps.get(i);
6646                final String packageName = info.activityInfo.packageName;
6647                final PackageSetting ps = mSettings.mPackages.get(packageName);
6648                if (ps.getInstantApp(userId)) {
6649                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6650                    final int status = (int)(packedStatus >> 32);
6651                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6652                        // there's a local instant application installed, but, the user has
6653                        // chosen to never use it; skip resolution and don't acknowledge
6654                        // an instant application is even available
6655                        if (DEBUG_INSTANT) {
6656                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6657                        }
6658                        blockResolution = true;
6659                        break;
6660                    } else {
6661                        // we have a locally installed instant application; skip resolution
6662                        // but acknowledge there's an instant application available
6663                        if (DEBUG_INSTANT) {
6664                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6665                        }
6666                        localInstantApp = info;
6667                        break;
6668                    }
6669                }
6670            }
6671        }
6672        // no app installed, let's see if one's available
6673        AuxiliaryResolveInfo auxiliaryResponse = null;
6674        if (!blockResolution) {
6675            if (localInstantApp == null) {
6676                // we don't have an instant app locally, resolve externally
6677                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6678                final InstantAppRequest requestObject = new InstantAppRequest(
6679                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6680                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6681                        resolveForStart);
6682                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6683                        mInstantAppResolverConnection, requestObject);
6684                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6685            } else {
6686                // we have an instant application locally, but, we can't admit that since
6687                // callers shouldn't be able to determine prior browsing. create a dummy
6688                // auxiliary response so the downstream code behaves as if there's an
6689                // instant application available externally. when it comes time to start
6690                // the instant application, we'll do the right thing.
6691                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6692                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6693                                        ai.packageName, ai.versionCode, null /* splitName */);
6694            }
6695        }
6696        if (intent.isBrowsableWebIntent() && auxiliaryResponse == null) {
6697            return result;
6698        }
6699        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6700        if (ps == null) {
6701            return result;
6702        }
6703        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6704        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6705                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6706        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6707                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6708        // add a non-generic filter
6709        ephemeralInstaller.filter = new IntentFilter();
6710        if (intent.getAction() != null) {
6711            ephemeralInstaller.filter.addAction(intent.getAction());
6712        }
6713        if (intent.getData() != null && intent.getData().getPath() != null) {
6714            ephemeralInstaller.filter.addDataPath(
6715                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6716        }
6717        ephemeralInstaller.isInstantAppAvailable = true;
6718        // make sure this resolver is the default
6719        ephemeralInstaller.isDefault = true;
6720        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6721        if (DEBUG_INSTANT) {
6722            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6723        }
6724
6725        result.add(ephemeralInstaller);
6726        return result;
6727    }
6728
6729    private static class CrossProfileDomainInfo {
6730        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6731        ResolveInfo resolveInfo;
6732        /* Best domain verification status of the activities found in the other profile */
6733        int bestDomainVerificationStatus;
6734    }
6735
6736    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6737            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6738        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6739                sourceUserId)) {
6740            return null;
6741        }
6742        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6743                resolvedType, flags, parentUserId);
6744
6745        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6746            return null;
6747        }
6748        CrossProfileDomainInfo result = null;
6749        int size = resultTargetUser.size();
6750        for (int i = 0; i < size; i++) {
6751            ResolveInfo riTargetUser = resultTargetUser.get(i);
6752            // Intent filter verification is only for filters that specify a host. So don't return
6753            // those that handle all web uris.
6754            if (riTargetUser.handleAllWebDataURI) {
6755                continue;
6756            }
6757            String packageName = riTargetUser.activityInfo.packageName;
6758            PackageSetting ps = mSettings.mPackages.get(packageName);
6759            if (ps == null) {
6760                continue;
6761            }
6762            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6763            int status = (int)(verificationState >> 32);
6764            if (result == null) {
6765                result = new CrossProfileDomainInfo();
6766                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6767                        sourceUserId, parentUserId);
6768                result.bestDomainVerificationStatus = status;
6769            } else {
6770                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6771                        result.bestDomainVerificationStatus);
6772            }
6773        }
6774        // Don't consider matches with status NEVER across profiles.
6775        if (result != null && result.bestDomainVerificationStatus
6776                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6777            return null;
6778        }
6779        return result;
6780    }
6781
6782    /**
6783     * Verification statuses are ordered from the worse to the best, except for
6784     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6785     */
6786    private int bestDomainVerificationStatus(int status1, int status2) {
6787        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6788            return status2;
6789        }
6790        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6791            return status1;
6792        }
6793        return (int) MathUtils.max(status1, status2);
6794    }
6795
6796    private boolean isUserEnabled(int userId) {
6797        long callingId = Binder.clearCallingIdentity();
6798        try {
6799            UserInfo userInfo = sUserManager.getUserInfo(userId);
6800            return userInfo != null && userInfo.isEnabled();
6801        } finally {
6802            Binder.restoreCallingIdentity(callingId);
6803        }
6804    }
6805
6806    /**
6807     * Filter out activities with systemUserOnly flag set, when current user is not System.
6808     *
6809     * @return filtered list
6810     */
6811    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6812        if (userId == UserHandle.USER_SYSTEM) {
6813            return resolveInfos;
6814        }
6815        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6816            ResolveInfo info = resolveInfos.get(i);
6817            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6818                resolveInfos.remove(i);
6819            }
6820        }
6821        return resolveInfos;
6822    }
6823
6824    /**
6825     * Filters out ephemeral activities.
6826     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6827     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6828     *
6829     * @param resolveInfos The pre-filtered list of resolved activities
6830     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6831     *          is performed.
6832     * @return A filtered list of resolved activities.
6833     */
6834    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6835            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6836        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6837            final ResolveInfo info = resolveInfos.get(i);
6838            // allow activities that are defined in the provided package
6839            if (allowDynamicSplits
6840                    && info.activityInfo != null
6841                    && info.activityInfo.splitName != null
6842                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6843                            info.activityInfo.splitName)) {
6844                if (mInstantAppInstallerActivity == null) {
6845                    if (DEBUG_INSTALL) {
6846                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6847                    }
6848                    resolveInfos.remove(i);
6849                    continue;
6850                }
6851                // requested activity is defined in a split that hasn't been installed yet.
6852                // add the installer to the resolve list
6853                if (DEBUG_INSTALL) {
6854                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6855                }
6856                final ResolveInfo installerInfo = new ResolveInfo(
6857                        mInstantAppInstallerInfo);
6858                final ComponentName installFailureActivity = findInstallFailureActivity(
6859                        info.activityInfo.packageName,  filterCallingUid, userId);
6860                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6861                        installFailureActivity,
6862                        info.activityInfo.packageName,
6863                        info.activityInfo.applicationInfo.versionCode,
6864                        info.activityInfo.splitName);
6865                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6866                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6867                // add a non-generic filter
6868                installerInfo.filter = new IntentFilter();
6869
6870                // This resolve info may appear in the chooser UI, so let us make it
6871                // look as the one it replaces as far as the user is concerned which
6872                // requires loading the correct label and icon for the resolve info.
6873                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6874                installerInfo.labelRes = info.resolveLabelResId();
6875                installerInfo.icon = info.resolveIconResId();
6876
6877                // propagate priority/preferred order/default
6878                installerInfo.priority = info.priority;
6879                installerInfo.preferredOrder = info.preferredOrder;
6880                installerInfo.isDefault = info.isDefault;
6881                installerInfo.isInstantAppAvailable = true;
6882                resolveInfos.set(i, installerInfo);
6883                continue;
6884            }
6885            // caller is a full app, don't need to apply any other filtering
6886            if (ephemeralPkgName == null) {
6887                continue;
6888            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6889                // caller is same app; don't need to apply any other filtering
6890                continue;
6891            }
6892            // allow activities that have been explicitly exposed to ephemeral apps
6893            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6894            if (!isEphemeralApp
6895                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6896                continue;
6897            }
6898            resolveInfos.remove(i);
6899        }
6900        return resolveInfos;
6901    }
6902
6903    /**
6904     * Returns the activity component that can handle install failures.
6905     * <p>By default, the instant application installer handles failures. However, an
6906     * application may want to handle failures on its own. Applications do this by
6907     * creating an activity with an intent filter that handles the action
6908     * {@link Intent#ACTION_INSTALL_FAILURE}.
6909     */
6910    private @Nullable ComponentName findInstallFailureActivity(
6911            String packageName, int filterCallingUid, int userId) {
6912        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6913        failureActivityIntent.setPackage(packageName);
6914        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6915        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6916                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6917                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6918        final int NR = result.size();
6919        if (NR > 0) {
6920            for (int i = 0; i < NR; i++) {
6921                final ResolveInfo info = result.get(i);
6922                if (info.activityInfo.splitName != null) {
6923                    continue;
6924                }
6925                return new ComponentName(packageName, info.activityInfo.name);
6926            }
6927        }
6928        return null;
6929    }
6930
6931    /**
6932     * @param resolveInfos list of resolve infos in descending priority order
6933     * @return if the list contains a resolve info with non-negative priority
6934     */
6935    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6936        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6937    }
6938
6939    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6940            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6941            int userId) {
6942        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6943
6944        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6945            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6946                    candidates.size());
6947        }
6948
6949        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6950        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6951        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6952        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6953        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6954        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6955
6956        synchronized (mPackages) {
6957            final int count = candidates.size();
6958            // First, try to use linked apps. Partition the candidates into four lists:
6959            // one for the final results, one for the "do not use ever", one for "undefined status"
6960            // and finally one for "browser app type".
6961            for (int n=0; n<count; n++) {
6962                ResolveInfo info = candidates.get(n);
6963                String packageName = info.activityInfo.packageName;
6964                PackageSetting ps = mSettings.mPackages.get(packageName);
6965                if (ps != null) {
6966                    // Add to the special match all list (Browser use case)
6967                    if (info.handleAllWebDataURI) {
6968                        matchAllList.add(info);
6969                        continue;
6970                    }
6971                    // Try to get the status from User settings first
6972                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6973                    int status = (int)(packedStatus >> 32);
6974                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6975                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6976                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6977                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6978                                    + " : linkgen=" + linkGeneration);
6979                        }
6980                        // Use link-enabled generation as preferredOrder, i.e.
6981                        // prefer newly-enabled over earlier-enabled.
6982                        info.preferredOrder = linkGeneration;
6983                        alwaysList.add(info);
6984                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6985                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6986                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6987                        }
6988                        neverList.add(info);
6989                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6990                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6991                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6992                        }
6993                        alwaysAskList.add(info);
6994                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6995                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6996                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6997                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6998                        }
6999                        undefinedList.add(info);
7000                    }
7001                }
7002            }
7003
7004            // We'll want to include browser possibilities in a few cases
7005            boolean includeBrowser = false;
7006
7007            // First try to add the "always" resolution(s) for the current user, if any
7008            if (alwaysList.size() > 0) {
7009                result.addAll(alwaysList);
7010            } else {
7011                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7012                result.addAll(undefinedList);
7013                // Maybe add one for the other profile.
7014                if (xpDomainInfo != null && (
7015                        xpDomainInfo.bestDomainVerificationStatus
7016                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7017                    result.add(xpDomainInfo.resolveInfo);
7018                }
7019                includeBrowser = true;
7020            }
7021
7022            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7023            // If there were 'always' entries their preferred order has been set, so we also
7024            // back that off to make the alternatives equivalent
7025            if (alwaysAskList.size() > 0) {
7026                for (ResolveInfo i : result) {
7027                    i.preferredOrder = 0;
7028                }
7029                result.addAll(alwaysAskList);
7030                includeBrowser = true;
7031            }
7032
7033            if (includeBrowser) {
7034                // Also add browsers (all of them or only the default one)
7035                if (DEBUG_DOMAIN_VERIFICATION) {
7036                    Slog.v(TAG, "   ...including browsers in candidate set");
7037                }
7038                if ((matchFlags & MATCH_ALL) != 0) {
7039                    result.addAll(matchAllList);
7040                } else {
7041                    // Browser/generic handling case.  If there's a default browser, go straight
7042                    // to that (but only if there is no other higher-priority match).
7043                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7044                    int maxMatchPrio = 0;
7045                    ResolveInfo defaultBrowserMatch = null;
7046                    final int numCandidates = matchAllList.size();
7047                    for (int n = 0; n < numCandidates; n++) {
7048                        ResolveInfo info = matchAllList.get(n);
7049                        // track the highest overall match priority...
7050                        if (info.priority > maxMatchPrio) {
7051                            maxMatchPrio = info.priority;
7052                        }
7053                        // ...and the highest-priority default browser match
7054                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7055                            if (defaultBrowserMatch == null
7056                                    || (defaultBrowserMatch.priority < info.priority)) {
7057                                if (debug) {
7058                                    Slog.v(TAG, "Considering default browser match " + info);
7059                                }
7060                                defaultBrowserMatch = info;
7061                            }
7062                        }
7063                    }
7064                    if (defaultBrowserMatch != null
7065                            && defaultBrowserMatch.priority >= maxMatchPrio
7066                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7067                    {
7068                        if (debug) {
7069                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7070                        }
7071                        result.add(defaultBrowserMatch);
7072                    } else {
7073                        result.addAll(matchAllList);
7074                    }
7075                }
7076
7077                // If there is nothing selected, add all candidates and remove the ones that the user
7078                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7079                if (result.size() == 0) {
7080                    result.addAll(candidates);
7081                    result.removeAll(neverList);
7082                }
7083            }
7084        }
7085        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7086            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7087                    result.size());
7088            for (ResolveInfo info : result) {
7089                Slog.v(TAG, "  + " + info.activityInfo);
7090            }
7091        }
7092        return result;
7093    }
7094
7095    // Returns a packed value as a long:
7096    //
7097    // high 'int'-sized word: link status: undefined/ask/never/always.
7098    // low 'int'-sized word: relative priority among 'always' results.
7099    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7100        long result = ps.getDomainVerificationStatusForUser(userId);
7101        // if none available, get the master status
7102        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7103            if (ps.getIntentFilterVerificationInfo() != null) {
7104                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7105            }
7106        }
7107        return result;
7108    }
7109
7110    private ResolveInfo querySkipCurrentProfileIntents(
7111            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7112            int flags, int sourceUserId) {
7113        if (matchingFilters != null) {
7114            int size = matchingFilters.size();
7115            for (int i = 0; i < size; i ++) {
7116                CrossProfileIntentFilter filter = matchingFilters.get(i);
7117                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7118                    // Checking if there are activities in the target user that can handle the
7119                    // intent.
7120                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7121                            resolvedType, flags, sourceUserId);
7122                    if (resolveInfo != null) {
7123                        return resolveInfo;
7124                    }
7125                }
7126            }
7127        }
7128        return null;
7129    }
7130
7131    // Return matching ResolveInfo in target user if any.
7132    private ResolveInfo queryCrossProfileIntents(
7133            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7134            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7135        if (matchingFilters != null) {
7136            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7137            // match the same intent. For performance reasons, it is better not to
7138            // run queryIntent twice for the same userId
7139            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7140            int size = matchingFilters.size();
7141            for (int i = 0; i < size; i++) {
7142                CrossProfileIntentFilter filter = matchingFilters.get(i);
7143                int targetUserId = filter.getTargetUserId();
7144                boolean skipCurrentProfile =
7145                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7146                boolean skipCurrentProfileIfNoMatchFound =
7147                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7148                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7149                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7150                    // Checking if there are activities in the target user that can handle the
7151                    // intent.
7152                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7153                            resolvedType, flags, sourceUserId);
7154                    if (resolveInfo != null) return resolveInfo;
7155                    alreadyTriedUserIds.put(targetUserId, true);
7156                }
7157            }
7158        }
7159        return null;
7160    }
7161
7162    /**
7163     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7164     * will forward the intent to the filter's target user.
7165     * Otherwise, returns null.
7166     */
7167    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7168            String resolvedType, int flags, int sourceUserId) {
7169        int targetUserId = filter.getTargetUserId();
7170        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7171                resolvedType, flags, targetUserId);
7172        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7173            // If all the matches in the target profile are suspended, return null.
7174            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7175                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7176                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7177                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7178                            targetUserId);
7179                }
7180            }
7181        }
7182        return null;
7183    }
7184
7185    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7186            int sourceUserId, int targetUserId) {
7187        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7188        long ident = Binder.clearCallingIdentity();
7189        boolean targetIsProfile;
7190        try {
7191            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7192        } finally {
7193            Binder.restoreCallingIdentity(ident);
7194        }
7195        String className;
7196        if (targetIsProfile) {
7197            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7198        } else {
7199            className = FORWARD_INTENT_TO_PARENT;
7200        }
7201        ComponentName forwardingActivityComponentName = new ComponentName(
7202                mAndroidApplication.packageName, className);
7203        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7204                sourceUserId);
7205        if (!targetIsProfile) {
7206            forwardingActivityInfo.showUserIcon = targetUserId;
7207            forwardingResolveInfo.noResourceId = true;
7208        }
7209        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7210        forwardingResolveInfo.priority = 0;
7211        forwardingResolveInfo.preferredOrder = 0;
7212        forwardingResolveInfo.match = 0;
7213        forwardingResolveInfo.isDefault = true;
7214        forwardingResolveInfo.filter = filter;
7215        forwardingResolveInfo.targetUserId = targetUserId;
7216        return forwardingResolveInfo;
7217    }
7218
7219    @Override
7220    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7221            Intent[] specifics, String[] specificTypes, Intent intent,
7222            String resolvedType, int flags, int userId) {
7223        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7224                specificTypes, intent, resolvedType, flags, userId));
7225    }
7226
7227    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7228            Intent[] specifics, String[] specificTypes, Intent intent,
7229            String resolvedType, int flags, int userId) {
7230        if (!sUserManager.exists(userId)) return Collections.emptyList();
7231        final int callingUid = Binder.getCallingUid();
7232        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7233                false /*includeInstantApps*/);
7234        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7235                false /*requireFullPermission*/, false /*checkShell*/,
7236                "query intent activity options");
7237        final String resultsAction = intent.getAction();
7238
7239        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7240                | PackageManager.GET_RESOLVED_FILTER, userId);
7241
7242        if (DEBUG_INTENT_MATCHING) {
7243            Log.v(TAG, "Query " + intent + ": " + results);
7244        }
7245
7246        int specificsPos = 0;
7247        int N;
7248
7249        // todo: note that the algorithm used here is O(N^2).  This
7250        // isn't a problem in our current environment, but if we start running
7251        // into situations where we have more than 5 or 10 matches then this
7252        // should probably be changed to something smarter...
7253
7254        // First we go through and resolve each of the specific items
7255        // that were supplied, taking care of removing any corresponding
7256        // duplicate items in the generic resolve list.
7257        if (specifics != null) {
7258            for (int i=0; i<specifics.length; i++) {
7259                final Intent sintent = specifics[i];
7260                if (sintent == null) {
7261                    continue;
7262                }
7263
7264                if (DEBUG_INTENT_MATCHING) {
7265                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7266                }
7267
7268                String action = sintent.getAction();
7269                if (resultsAction != null && resultsAction.equals(action)) {
7270                    // If this action was explicitly requested, then don't
7271                    // remove things that have it.
7272                    action = null;
7273                }
7274
7275                ResolveInfo ri = null;
7276                ActivityInfo ai = null;
7277
7278                ComponentName comp = sintent.getComponent();
7279                if (comp == null) {
7280                    ri = resolveIntent(
7281                        sintent,
7282                        specificTypes != null ? specificTypes[i] : null,
7283                            flags, userId);
7284                    if (ri == null) {
7285                        continue;
7286                    }
7287                    if (ri == mResolveInfo) {
7288                        // ACK!  Must do something better with this.
7289                    }
7290                    ai = ri.activityInfo;
7291                    comp = new ComponentName(ai.applicationInfo.packageName,
7292                            ai.name);
7293                } else {
7294                    ai = getActivityInfo(comp, flags, userId);
7295                    if (ai == null) {
7296                        continue;
7297                    }
7298                }
7299
7300                // Look for any generic query activities that are duplicates
7301                // of this specific one, and remove them from the results.
7302                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7303                N = results.size();
7304                int j;
7305                for (j=specificsPos; j<N; j++) {
7306                    ResolveInfo sri = results.get(j);
7307                    if ((sri.activityInfo.name.equals(comp.getClassName())
7308                            && sri.activityInfo.applicationInfo.packageName.equals(
7309                                    comp.getPackageName()))
7310                        || (action != null && sri.filter.matchAction(action))) {
7311                        results.remove(j);
7312                        if (DEBUG_INTENT_MATCHING) Log.v(
7313                            TAG, "Removing duplicate item from " + j
7314                            + " due to specific " + specificsPos);
7315                        if (ri == null) {
7316                            ri = sri;
7317                        }
7318                        j--;
7319                        N--;
7320                    }
7321                }
7322
7323                // Add this specific item to its proper place.
7324                if (ri == null) {
7325                    ri = new ResolveInfo();
7326                    ri.activityInfo = ai;
7327                }
7328                results.add(specificsPos, ri);
7329                ri.specificIndex = i;
7330                specificsPos++;
7331            }
7332        }
7333
7334        // Now we go through the remaining generic results and remove any
7335        // duplicate actions that are found here.
7336        N = results.size();
7337        for (int i=specificsPos; i<N-1; i++) {
7338            final ResolveInfo rii = results.get(i);
7339            if (rii.filter == null) {
7340                continue;
7341            }
7342
7343            // Iterate over all of the actions of this result's intent
7344            // filter...  typically this should be just one.
7345            final Iterator<String> it = rii.filter.actionsIterator();
7346            if (it == null) {
7347                continue;
7348            }
7349            while (it.hasNext()) {
7350                final String action = it.next();
7351                if (resultsAction != null && resultsAction.equals(action)) {
7352                    // If this action was explicitly requested, then don't
7353                    // remove things that have it.
7354                    continue;
7355                }
7356                for (int j=i+1; j<N; j++) {
7357                    final ResolveInfo rij = results.get(j);
7358                    if (rij.filter != null && rij.filter.hasAction(action)) {
7359                        results.remove(j);
7360                        if (DEBUG_INTENT_MATCHING) Log.v(
7361                            TAG, "Removing duplicate item from " + j
7362                            + " due to action " + action + " at " + i);
7363                        j--;
7364                        N--;
7365                    }
7366                }
7367            }
7368
7369            // If the caller didn't request filter information, drop it now
7370            // so we don't have to marshall/unmarshall it.
7371            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7372                rii.filter = null;
7373            }
7374        }
7375
7376        // Filter out the caller activity if so requested.
7377        if (caller != null) {
7378            N = results.size();
7379            for (int i=0; i<N; i++) {
7380                ActivityInfo ainfo = results.get(i).activityInfo;
7381                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7382                        && caller.getClassName().equals(ainfo.name)) {
7383                    results.remove(i);
7384                    break;
7385                }
7386            }
7387        }
7388
7389        // If the caller didn't request filter information,
7390        // drop them now so we don't have to
7391        // marshall/unmarshall it.
7392        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7393            N = results.size();
7394            for (int i=0; i<N; i++) {
7395                results.get(i).filter = null;
7396            }
7397        }
7398
7399        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7400        return results;
7401    }
7402
7403    @Override
7404    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7405            String resolvedType, int flags, int userId) {
7406        return new ParceledListSlice<>(
7407                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7408                        false /*allowDynamicSplits*/));
7409    }
7410
7411    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7412            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7413        if (!sUserManager.exists(userId)) return Collections.emptyList();
7414        final int callingUid = Binder.getCallingUid();
7415        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7416                false /*requireFullPermission*/, false /*checkShell*/,
7417                "query intent receivers");
7418        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7419        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7420                false /*includeInstantApps*/);
7421        ComponentName comp = intent.getComponent();
7422        if (comp == null) {
7423            if (intent.getSelector() != null) {
7424                intent = intent.getSelector();
7425                comp = intent.getComponent();
7426            }
7427        }
7428        if (comp != null) {
7429            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7430            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7431            if (ai != null) {
7432                // When specifying an explicit component, we prevent the activity from being
7433                // used when either 1) the calling package is normal and the activity is within
7434                // an instant application or 2) the calling package is ephemeral and the
7435                // activity is not visible to instant applications.
7436                final boolean matchInstantApp =
7437                        (flags & PackageManager.MATCH_INSTANT) != 0;
7438                final boolean matchVisibleToInstantAppOnly =
7439                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7440                final boolean matchExplicitlyVisibleOnly =
7441                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7442                final boolean isCallerInstantApp =
7443                        instantAppPkgName != null;
7444                final boolean isTargetSameInstantApp =
7445                        comp.getPackageName().equals(instantAppPkgName);
7446                final boolean isTargetInstantApp =
7447                        (ai.applicationInfo.privateFlags
7448                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7449                final boolean isTargetVisibleToInstantApp =
7450                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7451                final boolean isTargetExplicitlyVisibleToInstantApp =
7452                        isTargetVisibleToInstantApp
7453                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7454                final boolean isTargetHiddenFromInstantApp =
7455                        !isTargetVisibleToInstantApp
7456                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7457                final boolean blockResolution =
7458                        !isTargetSameInstantApp
7459                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7460                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7461                                        && isTargetHiddenFromInstantApp));
7462                if (!blockResolution) {
7463                    ResolveInfo ri = new ResolveInfo();
7464                    ri.activityInfo = ai;
7465                    list.add(ri);
7466                }
7467            }
7468            return applyPostResolutionFilter(
7469                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7470        }
7471
7472        // reader
7473        synchronized (mPackages) {
7474            String pkgName = intent.getPackage();
7475            if (pkgName == null) {
7476                final List<ResolveInfo> result =
7477                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7478                return applyPostResolutionFilter(
7479                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7480            }
7481            final PackageParser.Package pkg = mPackages.get(pkgName);
7482            if (pkg != null) {
7483                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7484                        intent, resolvedType, flags, pkg.receivers, userId);
7485                return applyPostResolutionFilter(
7486                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7487            }
7488            return Collections.emptyList();
7489        }
7490    }
7491
7492    @Override
7493    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7494        final int callingUid = Binder.getCallingUid();
7495        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7496    }
7497
7498    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7499            int userId, int callingUid) {
7500        if (!sUserManager.exists(userId)) return null;
7501        flags = updateFlagsForResolve(
7502                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7503        List<ResolveInfo> query = queryIntentServicesInternal(
7504                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7505        if (query != null) {
7506            if (query.size() >= 1) {
7507                // If there is more than one service with the same priority,
7508                // just arbitrarily pick the first one.
7509                return query.get(0);
7510            }
7511        }
7512        return null;
7513    }
7514
7515    @Override
7516    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7517            String resolvedType, int flags, int userId) {
7518        final int callingUid = Binder.getCallingUid();
7519        return new ParceledListSlice<>(queryIntentServicesInternal(
7520                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7521    }
7522
7523    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7524            String resolvedType, int flags, int userId, int callingUid,
7525            boolean includeInstantApps) {
7526        if (!sUserManager.exists(userId)) return Collections.emptyList();
7527        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7528                false /*requireFullPermission*/, false /*checkShell*/,
7529                "query intent receivers");
7530        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7531        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7532        ComponentName comp = intent.getComponent();
7533        if (comp == null) {
7534            if (intent.getSelector() != null) {
7535                intent = intent.getSelector();
7536                comp = intent.getComponent();
7537            }
7538        }
7539        if (comp != null) {
7540            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7541            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7542            if (si != null) {
7543                // When specifying an explicit component, we prevent the service from being
7544                // used when either 1) the service is in an instant application and the
7545                // caller is not the same instant application or 2) the calling package is
7546                // ephemeral and the activity is not visible to ephemeral applications.
7547                final boolean matchInstantApp =
7548                        (flags & PackageManager.MATCH_INSTANT) != 0;
7549                final boolean matchVisibleToInstantAppOnly =
7550                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7551                final boolean isCallerInstantApp =
7552                        instantAppPkgName != null;
7553                final boolean isTargetSameInstantApp =
7554                        comp.getPackageName().equals(instantAppPkgName);
7555                final boolean isTargetInstantApp =
7556                        (si.applicationInfo.privateFlags
7557                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7558                final boolean isTargetHiddenFromInstantApp =
7559                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7560                final boolean blockResolution =
7561                        !isTargetSameInstantApp
7562                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7563                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7564                                        && isTargetHiddenFromInstantApp));
7565                if (!blockResolution) {
7566                    final ResolveInfo ri = new ResolveInfo();
7567                    ri.serviceInfo = si;
7568                    list.add(ri);
7569                }
7570            }
7571            return list;
7572        }
7573
7574        // reader
7575        synchronized (mPackages) {
7576            String pkgName = intent.getPackage();
7577            if (pkgName == null) {
7578                return applyPostServiceResolutionFilter(
7579                        mServices.queryIntent(intent, resolvedType, flags, userId),
7580                        instantAppPkgName);
7581            }
7582            final PackageParser.Package pkg = mPackages.get(pkgName);
7583            if (pkg != null) {
7584                return applyPostServiceResolutionFilter(
7585                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7586                                userId),
7587                        instantAppPkgName);
7588            }
7589            return Collections.emptyList();
7590        }
7591    }
7592
7593    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7594            String instantAppPkgName) {
7595        if (instantAppPkgName == null) {
7596            return resolveInfos;
7597        }
7598        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7599            final ResolveInfo info = resolveInfos.get(i);
7600            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7601            // allow services that are defined in the provided package
7602            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7603                if (info.serviceInfo.splitName != null
7604                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7605                                info.serviceInfo.splitName)) {
7606                    // requested service is defined in a split that hasn't been installed yet.
7607                    // add the installer to the resolve list
7608                    if (DEBUG_INSTANT) {
7609                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7610                    }
7611                    final ResolveInfo installerInfo = new ResolveInfo(
7612                            mInstantAppInstallerInfo);
7613                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7614                            null /* installFailureActivity */,
7615                            info.serviceInfo.packageName,
7616                            info.serviceInfo.applicationInfo.versionCode,
7617                            info.serviceInfo.splitName);
7618                    // make sure this resolver is the default
7619                    installerInfo.isDefault = true;
7620                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7621                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7622                    // add a non-generic filter
7623                    installerInfo.filter = new IntentFilter();
7624                    // load resources from the correct package
7625                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7626                    resolveInfos.set(i, installerInfo);
7627                }
7628                continue;
7629            }
7630            // allow services that have been explicitly exposed to ephemeral apps
7631            if (!isEphemeralApp
7632                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7633                continue;
7634            }
7635            resolveInfos.remove(i);
7636        }
7637        return resolveInfos;
7638    }
7639
7640    @Override
7641    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7642            String resolvedType, int flags, int userId) {
7643        return new ParceledListSlice<>(
7644                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7645    }
7646
7647    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7648            Intent intent, String resolvedType, int flags, int userId) {
7649        if (!sUserManager.exists(userId)) return Collections.emptyList();
7650        final int callingUid = Binder.getCallingUid();
7651        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7652        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7653                false /*includeInstantApps*/);
7654        ComponentName comp = intent.getComponent();
7655        if (comp == null) {
7656            if (intent.getSelector() != null) {
7657                intent = intent.getSelector();
7658                comp = intent.getComponent();
7659            }
7660        }
7661        if (comp != null) {
7662            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7663            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7664            if (pi != null) {
7665                // When specifying an explicit component, we prevent the provider from being
7666                // used when either 1) the provider is in an instant application and the
7667                // caller is not the same instant application or 2) the calling package is an
7668                // instant application and the provider is not visible to instant applications.
7669                final boolean matchInstantApp =
7670                        (flags & PackageManager.MATCH_INSTANT) != 0;
7671                final boolean matchVisibleToInstantAppOnly =
7672                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7673                final boolean isCallerInstantApp =
7674                        instantAppPkgName != null;
7675                final boolean isTargetSameInstantApp =
7676                        comp.getPackageName().equals(instantAppPkgName);
7677                final boolean isTargetInstantApp =
7678                        (pi.applicationInfo.privateFlags
7679                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7680                final boolean isTargetHiddenFromInstantApp =
7681                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7682                final boolean blockResolution =
7683                        !isTargetSameInstantApp
7684                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7685                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7686                                        && isTargetHiddenFromInstantApp));
7687                if (!blockResolution) {
7688                    final ResolveInfo ri = new ResolveInfo();
7689                    ri.providerInfo = pi;
7690                    list.add(ri);
7691                }
7692            }
7693            return list;
7694        }
7695
7696        // reader
7697        synchronized (mPackages) {
7698            String pkgName = intent.getPackage();
7699            if (pkgName == null) {
7700                return applyPostContentProviderResolutionFilter(
7701                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7702                        instantAppPkgName);
7703            }
7704            final PackageParser.Package pkg = mPackages.get(pkgName);
7705            if (pkg != null) {
7706                return applyPostContentProviderResolutionFilter(
7707                        mProviders.queryIntentForPackage(
7708                        intent, resolvedType, flags, pkg.providers, userId),
7709                        instantAppPkgName);
7710            }
7711            return Collections.emptyList();
7712        }
7713    }
7714
7715    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7716            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7717        if (instantAppPkgName == null) {
7718            return resolveInfos;
7719        }
7720        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7721            final ResolveInfo info = resolveInfos.get(i);
7722            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7723            // allow providers that are defined in the provided package
7724            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7725                if (info.providerInfo.splitName != null
7726                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7727                                info.providerInfo.splitName)) {
7728                    // requested provider is defined in a split that hasn't been installed yet.
7729                    // add the installer to the resolve list
7730                    if (DEBUG_INSTANT) {
7731                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7732                    }
7733                    final ResolveInfo installerInfo = new ResolveInfo(
7734                            mInstantAppInstallerInfo);
7735                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7736                            null /*failureActivity*/,
7737                            info.providerInfo.packageName,
7738                            info.providerInfo.applicationInfo.versionCode,
7739                            info.providerInfo.splitName);
7740                    // make sure this resolver is the default
7741                    installerInfo.isDefault = true;
7742                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7743                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7744                    // add a non-generic filter
7745                    installerInfo.filter = new IntentFilter();
7746                    // load resources from the correct package
7747                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7748                    resolveInfos.set(i, installerInfo);
7749                }
7750                continue;
7751            }
7752            // allow providers that have been explicitly exposed to instant applications
7753            if (!isEphemeralApp
7754                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7755                continue;
7756            }
7757            resolveInfos.remove(i);
7758        }
7759        return resolveInfos;
7760    }
7761
7762    @Override
7763    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7764        final int callingUid = Binder.getCallingUid();
7765        if (getInstantAppPackageName(callingUid) != null) {
7766            return ParceledListSlice.emptyList();
7767        }
7768        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7769        flags = updateFlagsForPackage(flags, userId, null);
7770        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7771        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7772                true /* requireFullPermission */, false /* checkShell */,
7773                "get installed packages");
7774
7775        // writer
7776        synchronized (mPackages) {
7777            ArrayList<PackageInfo> list;
7778            if (listUninstalled) {
7779                list = new ArrayList<>(mSettings.mPackages.size());
7780                for (PackageSetting ps : mSettings.mPackages.values()) {
7781                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7782                        continue;
7783                    }
7784                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7785                        continue;
7786                    }
7787                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7788                    if (pi != null) {
7789                        list.add(pi);
7790                    }
7791                }
7792            } else {
7793                list = new ArrayList<>(mPackages.size());
7794                for (PackageParser.Package p : mPackages.values()) {
7795                    final PackageSetting ps = (PackageSetting) p.mExtras;
7796                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7797                        continue;
7798                    }
7799                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7800                        continue;
7801                    }
7802                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7803                            p.mExtras, flags, userId);
7804                    if (pi != null) {
7805                        list.add(pi);
7806                    }
7807                }
7808            }
7809
7810            return new ParceledListSlice<>(list);
7811        }
7812    }
7813
7814    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7815            String[] permissions, boolean[] tmp, int flags, int userId) {
7816        int numMatch = 0;
7817        final PermissionsState permissionsState = ps.getPermissionsState();
7818        for (int i=0; i<permissions.length; i++) {
7819            final String permission = permissions[i];
7820            if (permissionsState.hasPermission(permission, userId)) {
7821                tmp[i] = true;
7822                numMatch++;
7823            } else {
7824                tmp[i] = false;
7825            }
7826        }
7827        if (numMatch == 0) {
7828            return;
7829        }
7830        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7831
7832        // The above might return null in cases of uninstalled apps or install-state
7833        // skew across users/profiles.
7834        if (pi != null) {
7835            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7836                if (numMatch == permissions.length) {
7837                    pi.requestedPermissions = permissions;
7838                } else {
7839                    pi.requestedPermissions = new String[numMatch];
7840                    numMatch = 0;
7841                    for (int i=0; i<permissions.length; i++) {
7842                        if (tmp[i]) {
7843                            pi.requestedPermissions[numMatch] = permissions[i];
7844                            numMatch++;
7845                        }
7846                    }
7847                }
7848            }
7849            list.add(pi);
7850        }
7851    }
7852
7853    @Override
7854    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7855            String[] permissions, int flags, int userId) {
7856        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7857        flags = updateFlagsForPackage(flags, userId, permissions);
7858        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7859                true /* requireFullPermission */, false /* checkShell */,
7860                "get packages holding permissions");
7861        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7862
7863        // writer
7864        synchronized (mPackages) {
7865            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7866            boolean[] tmpBools = new boolean[permissions.length];
7867            if (listUninstalled) {
7868                for (PackageSetting ps : mSettings.mPackages.values()) {
7869                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7870                            userId);
7871                }
7872            } else {
7873                for (PackageParser.Package pkg : mPackages.values()) {
7874                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7875                    if (ps != null) {
7876                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7877                                userId);
7878                    }
7879                }
7880            }
7881
7882            return new ParceledListSlice<PackageInfo>(list);
7883        }
7884    }
7885
7886    @Override
7887    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7888        final int callingUid = Binder.getCallingUid();
7889        if (getInstantAppPackageName(callingUid) != null) {
7890            return ParceledListSlice.emptyList();
7891        }
7892        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7893        flags = updateFlagsForApplication(flags, userId, null);
7894        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7895
7896        // writer
7897        synchronized (mPackages) {
7898            ArrayList<ApplicationInfo> list;
7899            if (listUninstalled) {
7900                list = new ArrayList<>(mSettings.mPackages.size());
7901                for (PackageSetting ps : mSettings.mPackages.values()) {
7902                    ApplicationInfo ai;
7903                    int effectiveFlags = flags;
7904                    if (ps.isSystem()) {
7905                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7906                    }
7907                    if (ps.pkg != null) {
7908                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7909                            continue;
7910                        }
7911                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7912                            continue;
7913                        }
7914                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7915                                ps.readUserState(userId), userId);
7916                        if (ai != null) {
7917                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7918                        }
7919                    } else {
7920                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7921                        // and already converts to externally visible package name
7922                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7923                                callingUid, effectiveFlags, userId);
7924                    }
7925                    if (ai != null) {
7926                        list.add(ai);
7927                    }
7928                }
7929            } else {
7930                list = new ArrayList<>(mPackages.size());
7931                for (PackageParser.Package p : mPackages.values()) {
7932                    if (p.mExtras != null) {
7933                        PackageSetting ps = (PackageSetting) p.mExtras;
7934                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7935                            continue;
7936                        }
7937                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7938                            continue;
7939                        }
7940                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7941                                ps.readUserState(userId), userId);
7942                        if (ai != null) {
7943                            ai.packageName = resolveExternalPackageNameLPr(p);
7944                            list.add(ai);
7945                        }
7946                    }
7947                }
7948            }
7949
7950            return new ParceledListSlice<>(list);
7951        }
7952    }
7953
7954    @Override
7955    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7956        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7957            return null;
7958        }
7959        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7960            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7961                    "getEphemeralApplications");
7962        }
7963        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7964                true /* requireFullPermission */, false /* checkShell */,
7965                "getEphemeralApplications");
7966        synchronized (mPackages) {
7967            List<InstantAppInfo> instantApps = mInstantAppRegistry
7968                    .getInstantAppsLPr(userId);
7969            if (instantApps != null) {
7970                return new ParceledListSlice<>(instantApps);
7971            }
7972        }
7973        return null;
7974    }
7975
7976    @Override
7977    public boolean isInstantApp(String packageName, int userId) {
7978        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7979                true /* requireFullPermission */, false /* checkShell */,
7980                "isInstantApp");
7981        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7982            return false;
7983        }
7984
7985        synchronized (mPackages) {
7986            int callingUid = Binder.getCallingUid();
7987            if (Process.isIsolated(callingUid)) {
7988                callingUid = mIsolatedOwners.get(callingUid);
7989            }
7990            final PackageSetting ps = mSettings.mPackages.get(packageName);
7991            PackageParser.Package pkg = mPackages.get(packageName);
7992            final boolean returnAllowed =
7993                    ps != null
7994                    && (isCallerSameApp(packageName, callingUid)
7995                            || canViewInstantApps(callingUid, userId)
7996                            || mInstantAppRegistry.isInstantAccessGranted(
7997                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7998            if (returnAllowed) {
7999                return ps.getInstantApp(userId);
8000            }
8001        }
8002        return false;
8003    }
8004
8005    @Override
8006    public byte[] getInstantAppCookie(String packageName, int userId) {
8007        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8008            return null;
8009        }
8010
8011        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8012                true /* requireFullPermission */, false /* checkShell */,
8013                "getInstantAppCookie");
8014        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8015            return null;
8016        }
8017        synchronized (mPackages) {
8018            return mInstantAppRegistry.getInstantAppCookieLPw(
8019                    packageName, userId);
8020        }
8021    }
8022
8023    @Override
8024    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8025        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8026            return true;
8027        }
8028
8029        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8030                true /* requireFullPermission */, true /* checkShell */,
8031                "setInstantAppCookie");
8032        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8033            return false;
8034        }
8035        synchronized (mPackages) {
8036            return mInstantAppRegistry.setInstantAppCookieLPw(
8037                    packageName, cookie, userId);
8038        }
8039    }
8040
8041    @Override
8042    public Bitmap getInstantAppIcon(String packageName, int userId) {
8043        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8044            return null;
8045        }
8046
8047        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8048            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8049                    "getInstantAppIcon");
8050        }
8051        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8052                true /* requireFullPermission */, false /* checkShell */,
8053                "getInstantAppIcon");
8054
8055        synchronized (mPackages) {
8056            return mInstantAppRegistry.getInstantAppIconLPw(
8057                    packageName, userId);
8058        }
8059    }
8060
8061    private boolean isCallerSameApp(String packageName, int uid) {
8062        PackageParser.Package pkg = mPackages.get(packageName);
8063        return pkg != null
8064                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8065    }
8066
8067    @Override
8068    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8069        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8070            return ParceledListSlice.emptyList();
8071        }
8072        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8073    }
8074
8075    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8076        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8077
8078        // reader
8079        synchronized (mPackages) {
8080            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8081            final int userId = UserHandle.getCallingUserId();
8082            while (i.hasNext()) {
8083                final PackageParser.Package p = i.next();
8084                if (p.applicationInfo == null) continue;
8085
8086                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8087                        && !p.applicationInfo.isDirectBootAware();
8088                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8089                        && p.applicationInfo.isDirectBootAware();
8090
8091                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8092                        && (!mSafeMode || isSystemApp(p))
8093                        && (matchesUnaware || matchesAware)) {
8094                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8095                    if (ps != null) {
8096                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8097                                ps.readUserState(userId), userId);
8098                        if (ai != null) {
8099                            finalList.add(ai);
8100                        }
8101                    }
8102                }
8103            }
8104        }
8105
8106        return finalList;
8107    }
8108
8109    @Override
8110    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8111        return resolveContentProviderInternal(name, flags, userId);
8112    }
8113
8114    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8115        if (!sUserManager.exists(userId)) return null;
8116        flags = updateFlagsForComponent(flags, userId, name);
8117        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8118        // reader
8119        synchronized (mPackages) {
8120            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8121            PackageSetting ps = provider != null
8122                    ? mSettings.mPackages.get(provider.owner.packageName)
8123                    : null;
8124            if (ps != null) {
8125                final boolean isInstantApp = ps.getInstantApp(userId);
8126                // normal application; filter out instant application provider
8127                if (instantAppPkgName == null && isInstantApp) {
8128                    return null;
8129                }
8130                // instant application; filter out other instant applications
8131                if (instantAppPkgName != null
8132                        && isInstantApp
8133                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8134                    return null;
8135                }
8136                // instant application; filter out non-exposed provider
8137                if (instantAppPkgName != null
8138                        && !isInstantApp
8139                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8140                    return null;
8141                }
8142                // provider not enabled
8143                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8144                    return null;
8145                }
8146                return PackageParser.generateProviderInfo(
8147                        provider, flags, ps.readUserState(userId), userId);
8148            }
8149            return null;
8150        }
8151    }
8152
8153    /**
8154     * @deprecated
8155     */
8156    @Deprecated
8157    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8158        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8159            return;
8160        }
8161        // reader
8162        synchronized (mPackages) {
8163            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8164                    .entrySet().iterator();
8165            final int userId = UserHandle.getCallingUserId();
8166            while (i.hasNext()) {
8167                Map.Entry<String, PackageParser.Provider> entry = i.next();
8168                PackageParser.Provider p = entry.getValue();
8169                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8170
8171                if (ps != null && p.syncable
8172                        && (!mSafeMode || (p.info.applicationInfo.flags
8173                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8174                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8175                            ps.readUserState(userId), userId);
8176                    if (info != null) {
8177                        outNames.add(entry.getKey());
8178                        outInfo.add(info);
8179                    }
8180                }
8181            }
8182        }
8183    }
8184
8185    @Override
8186    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8187            int uid, int flags, String metaDataKey) {
8188        final int callingUid = Binder.getCallingUid();
8189        final int userId = processName != null ? UserHandle.getUserId(uid)
8190                : UserHandle.getCallingUserId();
8191        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8192        flags = updateFlagsForComponent(flags, userId, processName);
8193        ArrayList<ProviderInfo> finalList = null;
8194        // reader
8195        synchronized (mPackages) {
8196            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8197            while (i.hasNext()) {
8198                final PackageParser.Provider p = i.next();
8199                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8200                if (ps != null && p.info.authority != null
8201                        && (processName == null
8202                                || (p.info.processName.equals(processName)
8203                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8204                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8205
8206                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8207                    // parameter.
8208                    if (metaDataKey != null
8209                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8210                        continue;
8211                    }
8212                    final ComponentName component =
8213                            new ComponentName(p.info.packageName, p.info.name);
8214                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8215                        continue;
8216                    }
8217                    if (finalList == null) {
8218                        finalList = new ArrayList<ProviderInfo>(3);
8219                    }
8220                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8221                            ps.readUserState(userId), userId);
8222                    if (info != null) {
8223                        finalList.add(info);
8224                    }
8225                }
8226            }
8227        }
8228
8229        if (finalList != null) {
8230            Collections.sort(finalList, mProviderInitOrderSorter);
8231            return new ParceledListSlice<ProviderInfo>(finalList);
8232        }
8233
8234        return ParceledListSlice.emptyList();
8235    }
8236
8237    @Override
8238    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8239        // reader
8240        synchronized (mPackages) {
8241            final int callingUid = Binder.getCallingUid();
8242            final int callingUserId = UserHandle.getUserId(callingUid);
8243            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8244            if (ps == null) return null;
8245            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8246                return null;
8247            }
8248            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8249            return PackageParser.generateInstrumentationInfo(i, flags);
8250        }
8251    }
8252
8253    @Override
8254    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8255            String targetPackage, int flags) {
8256        final int callingUid = Binder.getCallingUid();
8257        final int callingUserId = UserHandle.getUserId(callingUid);
8258        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8259        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8260            return ParceledListSlice.emptyList();
8261        }
8262        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8263    }
8264
8265    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8266            int flags) {
8267        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8268
8269        // reader
8270        synchronized (mPackages) {
8271            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8272            while (i.hasNext()) {
8273                final PackageParser.Instrumentation p = i.next();
8274                if (targetPackage == null
8275                        || targetPackage.equals(p.info.targetPackage)) {
8276                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8277                            flags);
8278                    if (ii != null) {
8279                        finalList.add(ii);
8280                    }
8281                }
8282            }
8283        }
8284
8285        return finalList;
8286    }
8287
8288    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8289        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8290        try {
8291            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8292        } finally {
8293            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8294        }
8295    }
8296
8297    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8298        final File[] files = scanDir.listFiles();
8299        if (ArrayUtils.isEmpty(files)) {
8300            Log.d(TAG, "No files in app dir " + scanDir);
8301            return;
8302        }
8303
8304        if (DEBUG_PACKAGE_SCANNING) {
8305            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8306                    + " flags=0x" + Integer.toHexString(parseFlags));
8307        }
8308        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8309                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8310                mParallelPackageParserCallback)) {
8311            // Submit files for parsing in parallel
8312            int fileCount = 0;
8313            for (File file : files) {
8314                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8315                        && !PackageInstallerService.isStageName(file.getName());
8316                if (!isPackage) {
8317                    // Ignore entries which are not packages
8318                    continue;
8319                }
8320                parallelPackageParser.submit(file, parseFlags);
8321                fileCount++;
8322            }
8323
8324            // Process results one by one
8325            for (; fileCount > 0; fileCount--) {
8326                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8327                Throwable throwable = parseResult.throwable;
8328                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8329
8330                if (throwable == null) {
8331                    // TODO(toddke): move lower in the scan chain
8332                    // Static shared libraries have synthetic package names
8333                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8334                        renameStaticSharedLibraryPackage(parseResult.pkg);
8335                    }
8336                    try {
8337                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8338                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8339                                    currentTime, null);
8340                        }
8341                    } catch (PackageManagerException e) {
8342                        errorCode = e.error;
8343                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8344                    }
8345                } else if (throwable instanceof PackageParser.PackageParserException) {
8346                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8347                            throwable;
8348                    errorCode = e.error;
8349                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8350                } else {
8351                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8352                            + parseResult.scanFile, throwable);
8353                }
8354
8355                // Delete invalid userdata apps
8356                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8357                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8358                    logCriticalInfo(Log.WARN,
8359                            "Deleting invalid package at " + parseResult.scanFile);
8360                    removeCodePathLI(parseResult.scanFile);
8361                }
8362            }
8363        }
8364    }
8365
8366    public static void reportSettingsProblem(int priority, String msg) {
8367        logCriticalInfo(priority, msg);
8368    }
8369
8370    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8371            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8372        // When upgrading from pre-N MR1, verify the package time stamp using the package
8373        // directory and not the APK file.
8374        final long lastModifiedTime = mIsPreNMR1Upgrade
8375                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8376        if (ps != null && !forceCollect
8377                && ps.codePathString.equals(pkg.codePath)
8378                && ps.timeStamp == lastModifiedTime
8379                && !isCompatSignatureUpdateNeeded(pkg)
8380                && !isRecoverSignatureUpdateNeeded(pkg)) {
8381            if (ps.signatures.mSigningDetails.signatures != null
8382                    && ps.signatures.mSigningDetails.signatures.length != 0
8383                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8384                            != SignatureSchemeVersion.UNKNOWN) {
8385                // Optimization: reuse the existing cached signing data
8386                // if the package appears to be unchanged.
8387                pkg.mSigningDetails =
8388                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8389                return;
8390            }
8391
8392            Slog.w(TAG, "PackageSetting for " + ps.name
8393                    + " is missing signatures.  Collecting certs again to recover them.");
8394        } else {
8395            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8396                    (forceCollect ? " (forced)" : ""));
8397        }
8398
8399        try {
8400            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8401            PackageParser.collectCertificates(pkg, skipVerify);
8402        } catch (PackageParserException e) {
8403            throw PackageManagerException.from(e);
8404        } finally {
8405            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8406        }
8407    }
8408
8409    /**
8410     *  Traces a package scan.
8411     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8412     */
8413    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8414            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8416        try {
8417            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8418        } finally {
8419            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8420        }
8421    }
8422
8423    /**
8424     *  Scans a package and returns the newly parsed package.
8425     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8426     */
8427    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8428            long currentTime, UserHandle user) throws PackageManagerException {
8429        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8430        PackageParser pp = new PackageParser();
8431        pp.setSeparateProcesses(mSeparateProcesses);
8432        pp.setOnlyCoreApps(mOnlyCore);
8433        pp.setDisplayMetrics(mMetrics);
8434        pp.setCallback(mPackageParserCallback);
8435
8436        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8437        final PackageParser.Package pkg;
8438        try {
8439            pkg = pp.parsePackage(scanFile, parseFlags);
8440        } catch (PackageParserException e) {
8441            throw PackageManagerException.from(e);
8442        } finally {
8443            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8444        }
8445
8446        // Static shared libraries have synthetic package names
8447        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8448            renameStaticSharedLibraryPackage(pkg);
8449        }
8450
8451        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8452    }
8453
8454    /**
8455     *  Scans a package and returns the newly parsed package.
8456     *  @throws PackageManagerException on a parse error.
8457     */
8458    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8459            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8460            @Nullable UserHandle user)
8461                    throws PackageManagerException {
8462        // If the package has children and this is the first dive in the function
8463        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8464        // packages (parent and children) would be successfully scanned before the
8465        // actual scan since scanning mutates internal state and we want to atomically
8466        // install the package and its children.
8467        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8468            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8469                scanFlags |= SCAN_CHECK_ONLY;
8470            }
8471        } else {
8472            scanFlags &= ~SCAN_CHECK_ONLY;
8473        }
8474
8475        // Scan the parent
8476        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8477                scanFlags, currentTime, user);
8478
8479        // Scan the children
8480        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8481        for (int i = 0; i < childCount; i++) {
8482            PackageParser.Package childPackage = pkg.childPackages.get(i);
8483            addForInitLI(childPackage, parseFlags, scanFlags,
8484                    currentTime, user);
8485        }
8486
8487
8488        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8489            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8490        }
8491
8492        return scannedPkg;
8493    }
8494
8495    /**
8496     * Returns if full apk verification can be skipped for the whole package, including the splits.
8497     */
8498    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8499        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8500            return false;
8501        }
8502        // TODO: Allow base and splits to be verified individually.
8503        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8504            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8505                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8506                    return false;
8507                }
8508            }
8509        }
8510        return true;
8511    }
8512
8513    /**
8514     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8515     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8516     * match one in a trusted source, and should be done separately.
8517     */
8518    private boolean canSkipFullApkVerification(String apkPath) {
8519        byte[] rootHashObserved = null;
8520        try {
8521            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8522            if (rootHashObserved == null) {
8523                return false;  // APK does not contain Merkle tree root hash.
8524            }
8525            synchronized (mInstallLock) {
8526                // Returns whether the observed root hash matches what kernel has.
8527                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8528                return true;
8529            }
8530        } catch (InstallerException | IOException | DigestException |
8531                NoSuchAlgorithmException e) {
8532            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8533        }
8534        return false;
8535    }
8536
8537    // Temporary to catch potential issues with refactoring
8538    private static boolean REFACTOR_DEBUG = true;
8539    /**
8540     * Adds a new package to the internal data structures during platform initialization.
8541     * <p>After adding, the package is known to the system and available for querying.
8542     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8543     * etc...], additional checks are performed. Basic verification [such as ensuring
8544     * matching signatures, checking version codes, etc...] occurs if the package is
8545     * identical to a previously known package. If the package fails a signature check,
8546     * the version installed on /data will be removed. If the version of the new package
8547     * is less than or equal than the version on /data, it will be ignored.
8548     * <p>Regardless of the package location, the results are applied to the internal
8549     * structures and the package is made available to the rest of the system.
8550     * <p>NOTE: The return value should be removed. It's the passed in package object.
8551     */
8552    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8553            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8554            @Nullable UserHandle user)
8555                    throws PackageManagerException {
8556        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8557        final String renamedPkgName;
8558        final PackageSetting disabledPkgSetting;
8559        final boolean isSystemPkgUpdated;
8560        final boolean pkgAlreadyExists;
8561        PackageSetting pkgSetting;
8562
8563        // NOTE: installPackageLI() has the same code to setup the package's
8564        // application info. This probably should be done lower in the call
8565        // stack [such as scanPackageOnly()]. However, we verify the application
8566        // info prior to that [in scanPackageNew()] and thus have to setup
8567        // the application info early.
8568        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8569        pkg.setApplicationInfoCodePath(pkg.codePath);
8570        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8571        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8572        pkg.setApplicationInfoResourcePath(pkg.codePath);
8573        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8574        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8575
8576        synchronized (mPackages) {
8577            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8578            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8579if (REFACTOR_DEBUG) {
8580Slog.e("TODD",
8581        "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName));
8582}
8583            if (realPkgName != null) {
8584                ensurePackageRenamed(pkg, renamedPkgName);
8585            }
8586            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8587            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8588            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8589            pkgAlreadyExists = pkgSetting != null;
8590            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8591            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8592            isSystemPkgUpdated = disabledPkgSetting != null;
8593
8594            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8595                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8596            }
8597if (REFACTOR_DEBUG) {
8598Slog.e("TODD",
8599        "SSP? " + scanSystemPartition
8600        + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"")
8601        + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():""));
8602}
8603
8604            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8605                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8606                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8607                    : null;
8608            if (DEBUG_PACKAGE_SCANNING
8609                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8610                    && sharedUserSetting != null) {
8611                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8612                        + " (uid=" + sharedUserSetting.userId + "):"
8613                        + " packages=" + sharedUserSetting.packages);
8614if (REFACTOR_DEBUG) {
8615Slog.e("TODD",
8616        "Shared UserID " + pkg.mSharedUserId
8617        + " (uid=" + sharedUserSetting.userId + "):"
8618        + " packages=" + sharedUserSetting.packages);
8619}
8620            }
8621
8622            if (scanSystemPartition) {
8623                // Potentially prune child packages. If the application on the /system
8624                // partition has been updated via OTA, but, is still disabled by a
8625                // version on /data, cycle through all of its children packages and
8626                // remove children that are no longer defined.
8627                if (isSystemPkgUpdated) {
8628if (REFACTOR_DEBUG) {
8629Slog.e("TODD",
8630        "Disable child packages");
8631}
8632                    final int scannedChildCount = (pkg.childPackages != null)
8633                            ? pkg.childPackages.size() : 0;
8634                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8635                            ? disabledPkgSetting.childPackageNames.size() : 0;
8636                    for (int i = 0; i < disabledChildCount; i++) {
8637                        String disabledChildPackageName =
8638                                disabledPkgSetting.childPackageNames.get(i);
8639                        boolean disabledPackageAvailable = false;
8640                        for (int j = 0; j < scannedChildCount; j++) {
8641                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8642                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8643if (REFACTOR_DEBUG) {
8644Slog.e("TODD",
8645        "Ignore " + disabledChildPackageName);
8646}
8647                                disabledPackageAvailable = true;
8648                                break;
8649                            }
8650                        }
8651                        if (!disabledPackageAvailable) {
8652if (REFACTOR_DEBUG) {
8653Slog.e("TODD",
8654        "Disable " + disabledChildPackageName);
8655}
8656                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8657                        }
8658                    }
8659                    // we're updating the disabled package, so, scan it as the package setting
8660                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8661                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8662                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8663                            (pkg == mPlatformPackage), user);
8664if (REFACTOR_DEBUG) {
8665Slog.e("TODD",
8666        "Scan disabled system package");
8667Slog.e("TODD",
8668        "Pre: " + request.pkgSetting.dumpState_temp());
8669}
8670final ScanResult result =
8671                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8672if (REFACTOR_DEBUG) {
8673Slog.e("TODD",
8674        "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan"));
8675}
8676                }
8677            }
8678        }
8679
8680        final boolean newPkgChangedPaths =
8681                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8682if (REFACTOR_DEBUG) {
8683Slog.e("TODD",
8684        "paths changed? " + newPkgChangedPaths
8685        + "; old: " + pkg.codePath
8686        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString));
8687}
8688        final boolean newPkgVersionGreater =
8689                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8690if (REFACTOR_DEBUG) {
8691Slog.e("TODD",
8692        "version greater? " + newPkgVersionGreater
8693        + "; old: " + pkg.getLongVersionCode()
8694        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode));
8695}
8696        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8697                && newPkgChangedPaths && newPkgVersionGreater;
8698if (REFACTOR_DEBUG) {
8699    Slog.e("TODD",
8700            "system better? " + isSystemPkgBetter);
8701}
8702        if (isSystemPkgBetter) {
8703            // The version of the application on /system is greater than the version on
8704            // /data. Switch back to the application on /system.
8705            // It's safe to assume the application on /system will correctly scan. If not,
8706            // there won't be a working copy of the application.
8707            synchronized (mPackages) {
8708                // just remove the loaded entries from package lists
8709                mPackages.remove(pkgSetting.name);
8710            }
8711
8712            logCriticalInfo(Log.WARN,
8713                    "System package updated;"
8714                    + " name: " + pkgSetting.name
8715                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8716                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8717if (REFACTOR_DEBUG) {
8718Slog.e("TODD",
8719        "System package changed;"
8720        + " name: " + pkgSetting.name
8721        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8722        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8723}
8724
8725            final InstallArgs args = createInstallArgsForExisting(
8726                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8727                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8728            args.cleanUpResourcesLI();
8729            synchronized (mPackages) {
8730                mSettings.enableSystemPackageLPw(pkgSetting.name);
8731            }
8732        }
8733
8734        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8735if (REFACTOR_DEBUG) {
8736Slog.e("TODD",
8737        "THROW exception; system pkg version not good enough");
8738}
8739            // The version of the application on the /system partition is less than or
8740            // equal to the version on the /data partition. Throw an exception and use
8741            // the application already installed on the /data partition.
8742            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8743                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8744                    + " better than this " + pkg.getLongVersionCode());
8745        }
8746
8747        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8748        // force re-collecting certificate.
8749        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8750                disabledPkgSetting);
8751        // Full APK verification can be skipped during certificate collection, only if the file is
8752        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8753        // cases, only data in Signing Block is verified instead of the whole file.
8754        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8755                (forceCollect && canSkipFullPackageVerification(pkg));
8756        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8757
8758        boolean shouldHideSystemApp = false;
8759        // A new application appeared on /system, but, we already have a copy of
8760        // the application installed on /data.
8761        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8762                && !pkgSetting.isSystem()) {
8763
8764            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8765                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8766                logCriticalInfo(Log.WARN,
8767                        "System package signature mismatch;"
8768                        + " name: " + pkgSetting.name);
8769if (REFACTOR_DEBUG) {
8770Slog.e("TODD",
8771        "System package signature mismatch;"
8772        + " name: " + pkgSetting.name);
8773}
8774                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8775                        "scanPackageInternalLI")) {
8776                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8777                }
8778                pkgSetting = null;
8779            } else if (newPkgVersionGreater) {
8780                // The application on /system is newer than the application on /data.
8781                // Simply remove the application on /data [keeping application data]
8782                // and replace it with the version on /system.
8783                logCriticalInfo(Log.WARN,
8784                        "System package enabled;"
8785                        + " name: " + pkgSetting.name
8786                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8787                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8788if (REFACTOR_DEBUG) {
8789Slog.e("TODD",
8790        "System package enabled;"
8791        + " name: " + pkgSetting.name
8792        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8793        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8794}
8795                InstallArgs args = createInstallArgsForExisting(
8796                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8797                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8798                synchronized (mInstallLock) {
8799                    args.cleanUpResourcesLI();
8800                }
8801            } else {
8802                // The application on /system is older than the application on /data. Hide
8803                // the application on /system and the version on /data will be scanned later
8804                // and re-added like an update.
8805                shouldHideSystemApp = true;
8806                logCriticalInfo(Log.INFO,
8807                        "System package disabled;"
8808                        + " name: " + pkgSetting.name
8809                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8810                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8811if (REFACTOR_DEBUG) {
8812Slog.e("TODD",
8813        "System package disabled;"
8814        + " name: " + pkgSetting.name
8815        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8816        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8817}
8818            }
8819        }
8820
8821if (REFACTOR_DEBUG) {
8822Slog.e("TODD",
8823        "Scan package");
8824Slog.e("TODD",
8825        "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8826}
8827        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8828                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8829if (REFACTOR_DEBUG) {
8830pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8831Slog.e("TODD",
8832        "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8833}
8834
8835        if (shouldHideSystemApp) {
8836if (REFACTOR_DEBUG) {
8837Slog.e("TODD",
8838        "Disable package: " + pkg.packageName);
8839}
8840            synchronized (mPackages) {
8841                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8842            }
8843        }
8844        return scannedPkg;
8845    }
8846
8847    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8848        // Derive the new package synthetic package name
8849        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8850                + pkg.staticSharedLibVersion);
8851    }
8852
8853    private static String fixProcessName(String defProcessName,
8854            String processName) {
8855        if (processName == null) {
8856            return defProcessName;
8857        }
8858        return processName;
8859    }
8860
8861    /**
8862     * Enforces that only the system UID or root's UID can call a method exposed
8863     * via Binder.
8864     *
8865     * @param message used as message if SecurityException is thrown
8866     * @throws SecurityException if the caller is not system or root
8867     */
8868    private static final void enforceSystemOrRoot(String message) {
8869        final int uid = Binder.getCallingUid();
8870        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8871            throw new SecurityException(message);
8872        }
8873    }
8874
8875    @Override
8876    public void performFstrimIfNeeded() {
8877        enforceSystemOrRoot("Only the system can request fstrim");
8878
8879        // Before everything else, see whether we need to fstrim.
8880        try {
8881            IStorageManager sm = PackageHelper.getStorageManager();
8882            if (sm != null) {
8883                boolean doTrim = false;
8884                final long interval = android.provider.Settings.Global.getLong(
8885                        mContext.getContentResolver(),
8886                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8887                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8888                if (interval > 0) {
8889                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8890                    if (timeSinceLast > interval) {
8891                        doTrim = true;
8892                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8893                                + "; running immediately");
8894                    }
8895                }
8896                if (doTrim) {
8897                    final boolean dexOptDialogShown;
8898                    synchronized (mPackages) {
8899                        dexOptDialogShown = mDexOptDialogShown;
8900                    }
8901                    if (!isFirstBoot() && dexOptDialogShown) {
8902                        try {
8903                            ActivityManager.getService().showBootMessage(
8904                                    mContext.getResources().getString(
8905                                            R.string.android_upgrading_fstrim), true);
8906                        } catch (RemoteException e) {
8907                        }
8908                    }
8909                    sm.runMaintenance();
8910                }
8911            } else {
8912                Slog.e(TAG, "storageManager service unavailable!");
8913            }
8914        } catch (RemoteException e) {
8915            // Can't happen; StorageManagerService is local
8916        }
8917    }
8918
8919    @Override
8920    public void updatePackagesIfNeeded() {
8921        enforceSystemOrRoot("Only the system can request package update");
8922
8923        // We need to re-extract after an OTA.
8924        boolean causeUpgrade = isUpgrade();
8925
8926        // First boot or factory reset.
8927        // Note: we also handle devices that are upgrading to N right now as if it is their
8928        //       first boot, as they do not have profile data.
8929        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8930
8931        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8932        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8933
8934        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8935            return;
8936        }
8937
8938        List<PackageParser.Package> pkgs;
8939        synchronized (mPackages) {
8940            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8941        }
8942
8943        final long startTime = System.nanoTime();
8944        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8945                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8946                    false /* bootComplete */);
8947
8948        final int elapsedTimeSeconds =
8949                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8950
8951        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8952        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8953        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8954        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8955        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8956    }
8957
8958    /*
8959     * Return the prebuilt profile path given a package base code path.
8960     */
8961    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8962        return pkg.baseCodePath + ".prof";
8963    }
8964
8965    /**
8966     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8967     * containing statistics about the invocation. The array consists of three elements,
8968     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8969     * and {@code numberOfPackagesFailed}.
8970     */
8971    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8972            final String compilerFilter, boolean bootComplete) {
8973
8974        int numberOfPackagesVisited = 0;
8975        int numberOfPackagesOptimized = 0;
8976        int numberOfPackagesSkipped = 0;
8977        int numberOfPackagesFailed = 0;
8978        final int numberOfPackagesToDexopt = pkgs.size();
8979
8980        for (PackageParser.Package pkg : pkgs) {
8981            numberOfPackagesVisited++;
8982
8983            boolean useProfileForDexopt = false;
8984
8985            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8986                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8987                // that are already compiled.
8988                File profileFile = new File(getPrebuildProfilePath(pkg));
8989                // Copy profile if it exists.
8990                if (profileFile.exists()) {
8991                    try {
8992                        // We could also do this lazily before calling dexopt in
8993                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8994                        // is that we don't have a good way to say "do this only once".
8995                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8996                                pkg.applicationInfo.uid, pkg.packageName,
8997                                ArtManager.getProfileName(null))) {
8998                            Log.e(TAG, "Installer failed to copy system profile!");
8999                        } else {
9000                            // Disabled as this causes speed-profile compilation during first boot
9001                            // even if things are already compiled.
9002                            // useProfileForDexopt = true;
9003                        }
9004                    } catch (Exception e) {
9005                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9006                                e);
9007                    }
9008                } else {
9009                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9010                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9011                    // minimize the number off apps being speed-profile compiled during first boot.
9012                    // The other paths will not change the filter.
9013                    if (disabledPs != null && disabledPs.pkg.isStub) {
9014                        // The package is the stub one, remove the stub suffix to get the normal
9015                        // package and APK names.
9016                        String systemProfilePath =
9017                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9018                        profileFile = new File(systemProfilePath);
9019                        // If we have a profile for a compressed APK, copy it to the reference
9020                        // location.
9021                        // Note that copying the profile here will cause it to override the
9022                        // reference profile every OTA even though the existing reference profile
9023                        // may have more data. We can't copy during decompression since the
9024                        // directories are not set up at that point.
9025                        if (profileFile.exists()) {
9026                            try {
9027                                // We could also do this lazily before calling dexopt in
9028                                // PackageDexOptimizer to prevent this happening on first boot. The
9029                                // issue is that we don't have a good way to say "do this only
9030                                // once".
9031                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9032                                        pkg.applicationInfo.uid, pkg.packageName,
9033                                        ArtManager.getProfileName(null))) {
9034                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9035                                } else {
9036                                    useProfileForDexopt = true;
9037                                }
9038                            } catch (Exception e) {
9039                                Log.e(TAG, "Failed to copy profile " +
9040                                        profileFile.getAbsolutePath() + " ", e);
9041                            }
9042                        }
9043                    }
9044                }
9045            }
9046
9047            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9048                if (DEBUG_DEXOPT) {
9049                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9050                }
9051                numberOfPackagesSkipped++;
9052                continue;
9053            }
9054
9055            if (DEBUG_DEXOPT) {
9056                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9057                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9058            }
9059
9060            if (showDialog) {
9061                try {
9062                    ActivityManager.getService().showBootMessage(
9063                            mContext.getResources().getString(R.string.android_upgrading_apk,
9064                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9065                } catch (RemoteException e) {
9066                }
9067                synchronized (mPackages) {
9068                    mDexOptDialogShown = true;
9069                }
9070            }
9071
9072            String pkgCompilerFilter = compilerFilter;
9073            if (useProfileForDexopt) {
9074                // Use background dexopt mode to try and use the profile. Note that this does not
9075                // guarantee usage of the profile.
9076                pkgCompilerFilter =
9077                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9078                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9079            }
9080
9081            // checkProfiles is false to avoid merging profiles during boot which
9082            // might interfere with background compilation (b/28612421).
9083            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9084            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9085            // trade-off worth doing to save boot time work.
9086            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9087            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9088                    pkg.packageName,
9089                    pkgCompilerFilter,
9090                    dexoptFlags));
9091
9092            switch (primaryDexOptStaus) {
9093                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9094                    numberOfPackagesOptimized++;
9095                    break;
9096                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9097                    numberOfPackagesSkipped++;
9098                    break;
9099                case PackageDexOptimizer.DEX_OPT_FAILED:
9100                    numberOfPackagesFailed++;
9101                    break;
9102                default:
9103                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9104                    break;
9105            }
9106        }
9107
9108        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9109                numberOfPackagesFailed };
9110    }
9111
9112    @Override
9113    public void notifyPackageUse(String packageName, int reason) {
9114        synchronized (mPackages) {
9115            final int callingUid = Binder.getCallingUid();
9116            final int callingUserId = UserHandle.getUserId(callingUid);
9117            if (getInstantAppPackageName(callingUid) != null) {
9118                if (!isCallerSameApp(packageName, callingUid)) {
9119                    return;
9120                }
9121            } else {
9122                if (isInstantApp(packageName, callingUserId)) {
9123                    return;
9124                }
9125            }
9126            notifyPackageUseLocked(packageName, reason);
9127        }
9128    }
9129
9130    private void notifyPackageUseLocked(String packageName, int reason) {
9131        final PackageParser.Package p = mPackages.get(packageName);
9132        if (p == null) {
9133            return;
9134        }
9135        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9136    }
9137
9138    @Override
9139    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9140            List<String> classPaths, String loaderIsa) {
9141        int userId = UserHandle.getCallingUserId();
9142        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9143        if (ai == null) {
9144            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9145                + loadingPackageName + ", user=" + userId);
9146            return;
9147        }
9148        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9149    }
9150
9151    @Override
9152    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9153            IDexModuleRegisterCallback callback) {
9154        int userId = UserHandle.getCallingUserId();
9155        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9156        DexManager.RegisterDexModuleResult result;
9157        if (ai == null) {
9158            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9159                     " calling user. package=" + packageName + ", user=" + userId);
9160            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9161        } else {
9162            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9163        }
9164
9165        if (callback != null) {
9166            mHandler.post(() -> {
9167                try {
9168                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9169                } catch (RemoteException e) {
9170                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9171                }
9172            });
9173        }
9174    }
9175
9176    /**
9177     * Ask the package manager to perform a dex-opt with the given compiler filter.
9178     *
9179     * Note: exposed only for the shell command to allow moving packages explicitly to a
9180     *       definite state.
9181     */
9182    @Override
9183    public boolean performDexOptMode(String packageName,
9184            boolean checkProfiles, String targetCompilerFilter, boolean force,
9185            boolean bootComplete, String splitName) {
9186        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9187                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9188                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9189        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9190                splitName, flags));
9191    }
9192
9193    /**
9194     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9195     * secondary dex files belonging to the given package.
9196     *
9197     * Note: exposed only for the shell command to allow moving packages explicitly to a
9198     *       definite state.
9199     */
9200    @Override
9201    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9202            boolean force) {
9203        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9204                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9205                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9206                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9207        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9208    }
9209
9210    /*package*/ boolean performDexOpt(DexoptOptions options) {
9211        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9212            return false;
9213        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9214            return false;
9215        }
9216
9217        if (options.isDexoptOnlySecondaryDex()) {
9218            return mDexManager.dexoptSecondaryDex(options);
9219        } else {
9220            int dexoptStatus = performDexOptWithStatus(options);
9221            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9222        }
9223    }
9224
9225    /**
9226     * Perform dexopt on the given package and return one of following result:
9227     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9228     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9229     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9230     */
9231    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9232        return performDexOptTraced(options);
9233    }
9234
9235    private int performDexOptTraced(DexoptOptions options) {
9236        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9237        try {
9238            return performDexOptInternal(options);
9239        } finally {
9240            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9241        }
9242    }
9243
9244    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9245    // if the package can now be considered up to date for the given filter.
9246    private int performDexOptInternal(DexoptOptions options) {
9247        PackageParser.Package p;
9248        synchronized (mPackages) {
9249            p = mPackages.get(options.getPackageName());
9250            if (p == null) {
9251                // Package could not be found. Report failure.
9252                return PackageDexOptimizer.DEX_OPT_FAILED;
9253            }
9254            mPackageUsage.maybeWriteAsync(mPackages);
9255            mCompilerStats.maybeWriteAsync();
9256        }
9257        long callingId = Binder.clearCallingIdentity();
9258        try {
9259            synchronized (mInstallLock) {
9260                return performDexOptInternalWithDependenciesLI(p, options);
9261            }
9262        } finally {
9263            Binder.restoreCallingIdentity(callingId);
9264        }
9265    }
9266
9267    public ArraySet<String> getOptimizablePackages() {
9268        ArraySet<String> pkgs = new ArraySet<String>();
9269        synchronized (mPackages) {
9270            for (PackageParser.Package p : mPackages.values()) {
9271                if (PackageDexOptimizer.canOptimizePackage(p)) {
9272                    pkgs.add(p.packageName);
9273                }
9274            }
9275        }
9276        return pkgs;
9277    }
9278
9279    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9280            DexoptOptions options) {
9281        // Select the dex optimizer based on the force parameter.
9282        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9283        //       allocate an object here.
9284        PackageDexOptimizer pdo = options.isForce()
9285                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9286                : mPackageDexOptimizer;
9287
9288        // Dexopt all dependencies first. Note: we ignore the return value and march on
9289        // on errors.
9290        // Note that we are going to call performDexOpt on those libraries as many times as
9291        // they are referenced in packages. When we do a batch of performDexOpt (for example
9292        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9293        // and the first package that uses the library will dexopt it. The
9294        // others will see that the compiled code for the library is up to date.
9295        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9296        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9297        if (!deps.isEmpty()) {
9298            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9299                    options.getCompilerFilter(), options.getSplitName(),
9300                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9301            for (PackageParser.Package depPackage : deps) {
9302                // TODO: Analyze and investigate if we (should) profile libraries.
9303                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9304                        getOrCreateCompilerPackageStats(depPackage),
9305                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9306            }
9307        }
9308        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9309                getOrCreateCompilerPackageStats(p),
9310                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9311    }
9312
9313    /**
9314     * Reconcile the information we have about the secondary dex files belonging to
9315     * {@code packagName} and the actual dex files. For all dex files that were
9316     * deleted, update the internal records and delete the generated oat files.
9317     */
9318    @Override
9319    public void reconcileSecondaryDexFiles(String packageName) {
9320        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9321            return;
9322        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9323            return;
9324        }
9325        mDexManager.reconcileSecondaryDexFiles(packageName);
9326    }
9327
9328    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9329    // a reference there.
9330    /*package*/ DexManager getDexManager() {
9331        return mDexManager;
9332    }
9333
9334    /**
9335     * Execute the background dexopt job immediately.
9336     */
9337    @Override
9338    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9339        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9340            return false;
9341        }
9342        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9343    }
9344
9345    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9346        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9347                || p.usesStaticLibraries != null) {
9348            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9349            Set<String> collectedNames = new HashSet<>();
9350            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9351
9352            retValue.remove(p);
9353
9354            return retValue;
9355        } else {
9356            return Collections.emptyList();
9357        }
9358    }
9359
9360    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9361            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9362        if (!collectedNames.contains(p.packageName)) {
9363            collectedNames.add(p.packageName);
9364            collected.add(p);
9365
9366            if (p.usesLibraries != null) {
9367                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9368                        null, collected, collectedNames);
9369            }
9370            if (p.usesOptionalLibraries != null) {
9371                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9372                        null, collected, collectedNames);
9373            }
9374            if (p.usesStaticLibraries != null) {
9375                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9376                        p.usesStaticLibrariesVersions, collected, collectedNames);
9377            }
9378        }
9379    }
9380
9381    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9382            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9383        final int libNameCount = libs.size();
9384        for (int i = 0; i < libNameCount; i++) {
9385            String libName = libs.get(i);
9386            long version = (versions != null && versions.length == libNameCount)
9387                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9388            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9389            if (libPkg != null) {
9390                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9391            }
9392        }
9393    }
9394
9395    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9396        synchronized (mPackages) {
9397            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9398            if (libEntry != null) {
9399                return mPackages.get(libEntry.apk);
9400            }
9401            return null;
9402        }
9403    }
9404
9405    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9406        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9407        if (versionedLib == null) {
9408            return null;
9409        }
9410        return versionedLib.get(version);
9411    }
9412
9413    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9414        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9415                pkg.staticSharedLibName);
9416        if (versionedLib == null) {
9417            return null;
9418        }
9419        long previousLibVersion = -1;
9420        final int versionCount = versionedLib.size();
9421        for (int i = 0; i < versionCount; i++) {
9422            final long libVersion = versionedLib.keyAt(i);
9423            if (libVersion < pkg.staticSharedLibVersion) {
9424                previousLibVersion = Math.max(previousLibVersion, libVersion);
9425            }
9426        }
9427        if (previousLibVersion >= 0) {
9428            return versionedLib.get(previousLibVersion);
9429        }
9430        return null;
9431    }
9432
9433    public void shutdown() {
9434        mPackageUsage.writeNow(mPackages);
9435        mCompilerStats.writeNow();
9436        mDexManager.writePackageDexUsageNow();
9437    }
9438
9439    @Override
9440    public void dumpProfiles(String packageName) {
9441        PackageParser.Package pkg;
9442        synchronized (mPackages) {
9443            pkg = mPackages.get(packageName);
9444            if (pkg == null) {
9445                throw new IllegalArgumentException("Unknown package: " + packageName);
9446            }
9447        }
9448        /* Only the shell, root, or the app user should be able to dump profiles. */
9449        int callingUid = Binder.getCallingUid();
9450        if (callingUid != Process.SHELL_UID &&
9451            callingUid != Process.ROOT_UID &&
9452            callingUid != pkg.applicationInfo.uid) {
9453            throw new SecurityException("dumpProfiles");
9454        }
9455
9456        synchronized (mInstallLock) {
9457            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9458            mArtManagerService.dumpProfiles(pkg);
9459            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9460        }
9461    }
9462
9463    @Override
9464    public void forceDexOpt(String packageName) {
9465        enforceSystemOrRoot("forceDexOpt");
9466
9467        PackageParser.Package pkg;
9468        synchronized (mPackages) {
9469            pkg = mPackages.get(packageName);
9470            if (pkg == null) {
9471                throw new IllegalArgumentException("Unknown package: " + packageName);
9472            }
9473        }
9474
9475        synchronized (mInstallLock) {
9476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9477
9478            // Whoever is calling forceDexOpt wants a compiled package.
9479            // Don't use profiles since that may cause compilation to be skipped.
9480            final int res = performDexOptInternalWithDependenciesLI(
9481                    pkg,
9482                    new DexoptOptions(packageName,
9483                            getDefaultCompilerFilter(),
9484                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9485
9486            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9487            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9488                throw new IllegalStateException("Failed to dexopt: " + res);
9489            }
9490        }
9491    }
9492
9493    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9494        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9495            Slog.w(TAG, "Unable to update from " + oldPkg.name
9496                    + " to " + newPkg.packageName
9497                    + ": old package not in system partition");
9498            return false;
9499        } else if (mPackages.get(oldPkg.name) != null) {
9500            Slog.w(TAG, "Unable to update from " + oldPkg.name
9501                    + " to " + newPkg.packageName
9502                    + ": old package still exists");
9503            return false;
9504        }
9505        return true;
9506    }
9507
9508    void removeCodePathLI(File codePath) {
9509        if (codePath.isDirectory()) {
9510            try {
9511                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9512            } catch (InstallerException e) {
9513                Slog.w(TAG, "Failed to remove code path", e);
9514            }
9515        } else {
9516            codePath.delete();
9517        }
9518    }
9519
9520    private int[] resolveUserIds(int userId) {
9521        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9522    }
9523
9524    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9525        if (pkg == null) {
9526            Slog.wtf(TAG, "Package was null!", new Throwable());
9527            return;
9528        }
9529        clearAppDataLeafLIF(pkg, userId, flags);
9530        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9531        for (int i = 0; i < childCount; i++) {
9532            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9533        }
9534
9535        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9536    }
9537
9538    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9539        final PackageSetting ps;
9540        synchronized (mPackages) {
9541            ps = mSettings.mPackages.get(pkg.packageName);
9542        }
9543        for (int realUserId : resolveUserIds(userId)) {
9544            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9545            try {
9546                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9547                        ceDataInode);
9548            } catch (InstallerException e) {
9549                Slog.w(TAG, String.valueOf(e));
9550            }
9551        }
9552    }
9553
9554    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9555        if (pkg == null) {
9556            Slog.wtf(TAG, "Package was null!", new Throwable());
9557            return;
9558        }
9559        destroyAppDataLeafLIF(pkg, userId, flags);
9560        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9561        for (int i = 0; i < childCount; i++) {
9562            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9563        }
9564    }
9565
9566    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9567        final PackageSetting ps;
9568        synchronized (mPackages) {
9569            ps = mSettings.mPackages.get(pkg.packageName);
9570        }
9571        for (int realUserId : resolveUserIds(userId)) {
9572            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9573            try {
9574                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9575                        ceDataInode);
9576            } catch (InstallerException e) {
9577                Slog.w(TAG, String.valueOf(e));
9578            }
9579            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9580        }
9581    }
9582
9583    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9584        if (pkg == null) {
9585            Slog.wtf(TAG, "Package was null!", new Throwable());
9586            return;
9587        }
9588        destroyAppProfilesLeafLIF(pkg);
9589        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9590        for (int i = 0; i < childCount; i++) {
9591            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9592        }
9593    }
9594
9595    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9596        try {
9597            mInstaller.destroyAppProfiles(pkg.packageName);
9598        } catch (InstallerException e) {
9599            Slog.w(TAG, String.valueOf(e));
9600        }
9601    }
9602
9603    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9604        if (pkg == null) {
9605            Slog.wtf(TAG, "Package was null!", new Throwable());
9606            return;
9607        }
9608        mArtManagerService.clearAppProfiles(pkg);
9609        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9610        for (int i = 0; i < childCount; i++) {
9611            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9612        }
9613    }
9614
9615    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9616            long lastUpdateTime) {
9617        // Set parent install/update time
9618        PackageSetting ps = (PackageSetting) pkg.mExtras;
9619        if (ps != null) {
9620            ps.firstInstallTime = firstInstallTime;
9621            ps.lastUpdateTime = lastUpdateTime;
9622        }
9623        // Set children install/update time
9624        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9625        for (int i = 0; i < childCount; i++) {
9626            PackageParser.Package childPkg = pkg.childPackages.get(i);
9627            ps = (PackageSetting) childPkg.mExtras;
9628            if (ps != null) {
9629                ps.firstInstallTime = firstInstallTime;
9630                ps.lastUpdateTime = lastUpdateTime;
9631            }
9632        }
9633    }
9634
9635    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9636            SharedLibraryEntry file,
9637            PackageParser.Package changingLib) {
9638        if (file.path != null) {
9639            usesLibraryFiles.add(file.path);
9640            return;
9641        }
9642        PackageParser.Package p = mPackages.get(file.apk);
9643        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9644            // If we are doing this while in the middle of updating a library apk,
9645            // then we need to make sure to use that new apk for determining the
9646            // dependencies here.  (We haven't yet finished committing the new apk
9647            // to the package manager state.)
9648            if (p == null || p.packageName.equals(changingLib.packageName)) {
9649                p = changingLib;
9650            }
9651        }
9652        if (p != null) {
9653            usesLibraryFiles.addAll(p.getAllCodePaths());
9654            if (p.usesLibraryFiles != null) {
9655                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9656            }
9657        }
9658    }
9659
9660    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9661            PackageParser.Package changingLib) throws PackageManagerException {
9662        if (pkg == null) {
9663            return;
9664        }
9665        // The collection used here must maintain the order of addition (so
9666        // that libraries are searched in the correct order) and must have no
9667        // duplicates.
9668        Set<String> usesLibraryFiles = null;
9669        if (pkg.usesLibraries != null) {
9670            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9671                    null, null, pkg.packageName, changingLib, true,
9672                    pkg.applicationInfo.targetSdkVersion, null);
9673        }
9674        if (pkg.usesStaticLibraries != null) {
9675            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9676                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9677                    pkg.packageName, changingLib, true,
9678                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9679        }
9680        if (pkg.usesOptionalLibraries != null) {
9681            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9682                    null, null, pkg.packageName, changingLib, false,
9683                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9684        }
9685        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9686            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9687        } else {
9688            pkg.usesLibraryFiles = null;
9689        }
9690    }
9691
9692    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9693            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9694            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9695            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9696            throws PackageManagerException {
9697        final int libCount = requestedLibraries.size();
9698        for (int i = 0; i < libCount; i++) {
9699            final String libName = requestedLibraries.get(i);
9700            final long libVersion = requiredVersions != null ? requiredVersions[i]
9701                    : SharedLibraryInfo.VERSION_UNDEFINED;
9702            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9703            if (libEntry == null) {
9704                if (required) {
9705                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9706                            "Package " + packageName + " requires unavailable shared library "
9707                                    + libName + "; failing!");
9708                } else if (DEBUG_SHARED_LIBRARIES) {
9709                    Slog.i(TAG, "Package " + packageName
9710                            + " desires unavailable shared library "
9711                            + libName + "; ignoring!");
9712                }
9713            } else {
9714                if (requiredVersions != null && requiredCertDigests != null) {
9715                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9716                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9717                            "Package " + packageName + " requires unavailable static shared"
9718                                    + " library " + libName + " version "
9719                                    + libEntry.info.getLongVersion() + "; failing!");
9720                    }
9721
9722                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9723                    if (libPkg == null) {
9724                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9725                                "Package " + packageName + " requires unavailable static shared"
9726                                        + " library; failing!");
9727                    }
9728
9729                    final String[] expectedCertDigests = requiredCertDigests[i];
9730
9731
9732                    if (expectedCertDigests.length > 1) {
9733
9734                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9735                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9736                                ? PackageUtils.computeSignaturesSha256Digests(
9737                                libPkg.mSigningDetails.signatures)
9738                                : PackageUtils.computeSignaturesSha256Digests(
9739                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9740
9741                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9742                        // target O we don't parse the "additional-certificate" tags similarly
9743                        // how we only consider all certs only for apps targeting O (see above).
9744                        // Therefore, the size check is safe to make.
9745                        if (expectedCertDigests.length != libCertDigests.length) {
9746                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9747                                    "Package " + packageName + " requires differently signed" +
9748                                            " static shared library; failing!");
9749                        }
9750
9751                        // Use a predictable order as signature order may vary
9752                        Arrays.sort(libCertDigests);
9753                        Arrays.sort(expectedCertDigests);
9754
9755                        final int certCount = libCertDigests.length;
9756                        for (int j = 0; j < certCount; j++) {
9757                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9758                                throw new PackageManagerException(
9759                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9760                                        "Package " + packageName + " requires differently signed" +
9761                                                " static shared library; failing!");
9762                            }
9763                        }
9764                    } else {
9765
9766                        // lib signing cert could have rotated beyond the one expected, check to see
9767                        // if the new one has been blessed by the old
9768                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9769                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9770                            throw new PackageManagerException(
9771                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9772                                    "Package " + packageName + " requires differently signed" +
9773                                            " static shared library; failing!");
9774                        }
9775                    }
9776                }
9777
9778                if (outUsedLibraries == null) {
9779                    // Use LinkedHashSet to preserve the order of files added to
9780                    // usesLibraryFiles while eliminating duplicates.
9781                    outUsedLibraries = new LinkedHashSet<>();
9782                }
9783                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9784            }
9785        }
9786        return outUsedLibraries;
9787    }
9788
9789    private static boolean hasString(List<String> list, List<String> which) {
9790        if (list == null) {
9791            return false;
9792        }
9793        for (int i=list.size()-1; i>=0; i--) {
9794            for (int j=which.size()-1; j>=0; j--) {
9795                if (which.get(j).equals(list.get(i))) {
9796                    return true;
9797                }
9798            }
9799        }
9800        return false;
9801    }
9802
9803    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9804            PackageParser.Package changingPkg) {
9805        ArrayList<PackageParser.Package> res = null;
9806        for (PackageParser.Package pkg : mPackages.values()) {
9807            if (changingPkg != null
9808                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9809                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9810                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9811                            changingPkg.staticSharedLibName)) {
9812                return null;
9813            }
9814            if (res == null) {
9815                res = new ArrayList<>();
9816            }
9817            res.add(pkg);
9818            try {
9819                updateSharedLibrariesLPr(pkg, changingPkg);
9820            } catch (PackageManagerException e) {
9821                // If a system app update or an app and a required lib missing we
9822                // delete the package and for updated system apps keep the data as
9823                // it is better for the user to reinstall than to be in an limbo
9824                // state. Also libs disappearing under an app should never happen
9825                // - just in case.
9826                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9827                    final int flags = pkg.isUpdatedSystemApp()
9828                            ? PackageManager.DELETE_KEEP_DATA : 0;
9829                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9830                            flags , null, true, null);
9831                }
9832                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9833            }
9834        }
9835        return res;
9836    }
9837
9838    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9839            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9840            @Nullable UserHandle user) throws PackageManagerException {
9841        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9842        // If the package has children and this is the first dive in the function
9843        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9844        // whether all packages (parent and children) would be successfully scanned
9845        // before the actual scan since scanning mutates internal state and we want
9846        // to atomically install the package and its children.
9847        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9848            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9849                scanFlags |= SCAN_CHECK_ONLY;
9850            }
9851        } else {
9852            scanFlags &= ~SCAN_CHECK_ONLY;
9853        }
9854
9855        final PackageParser.Package scannedPkg;
9856        try {
9857            // Scan the parent
9858            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9859            // Scan the children
9860            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9861            for (int i = 0; i < childCount; i++) {
9862                PackageParser.Package childPkg = pkg.childPackages.get(i);
9863                scanPackageNewLI(childPkg, parseFlags,
9864                        scanFlags, currentTime, user);
9865            }
9866        } finally {
9867            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9868        }
9869
9870        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9871            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9872        }
9873
9874        return scannedPkg;
9875    }
9876
9877    /** The result of a package scan. */
9878    private static class ScanResult {
9879        /** Whether or not the package scan was successful */
9880        public final boolean success;
9881        /**
9882         * The final package settings. This may be the same object passed in
9883         * the {@link ScanRequest}, but, with modified values.
9884         */
9885        @Nullable public final PackageSetting pkgSetting;
9886        /** ABI code paths that have changed in the package scan */
9887        @Nullable public final List<String> changedAbiCodePath;
9888        public ScanResult(
9889                boolean success,
9890                @Nullable PackageSetting pkgSetting,
9891                @Nullable List<String> changedAbiCodePath) {
9892            this.success = success;
9893            this.pkgSetting = pkgSetting;
9894            this.changedAbiCodePath = changedAbiCodePath;
9895        }
9896    }
9897
9898    /** A package to be scanned */
9899    private static class ScanRequest {
9900        /** The parsed package */
9901        @NonNull public final PackageParser.Package pkg;
9902        /** Shared user settings, if the package has a shared user */
9903        @Nullable public final SharedUserSetting sharedUserSetting;
9904        /**
9905         * Package settings of the currently installed version.
9906         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9907         * during scan.
9908         */
9909        @Nullable public final PackageSetting pkgSetting;
9910        /** A copy of the settings for the currently installed version */
9911        @Nullable public final PackageSetting oldPkgSetting;
9912        /** Package settings for the disabled version on the /system partition */
9913        @Nullable public final PackageSetting disabledPkgSetting;
9914        /** Package settings for the installed version under its original package name */
9915        @Nullable public final PackageSetting originalPkgSetting;
9916        /** The real package name of a renamed application */
9917        @Nullable public final String realPkgName;
9918        public final @ParseFlags int parseFlags;
9919        public final @ScanFlags int scanFlags;
9920        /** The user for which the package is being scanned */
9921        @Nullable public final UserHandle user;
9922        /** Whether or not the platform package is being scanned */
9923        public final boolean isPlatformPackage;
9924        public ScanRequest(
9925                @NonNull PackageParser.Package pkg,
9926                @Nullable SharedUserSetting sharedUserSetting,
9927                @Nullable PackageSetting pkgSetting,
9928                @Nullable PackageSetting disabledPkgSetting,
9929                @Nullable PackageSetting originalPkgSetting,
9930                @Nullable String realPkgName,
9931                @ParseFlags int parseFlags,
9932                @ScanFlags int scanFlags,
9933                boolean isPlatformPackage,
9934                @Nullable UserHandle user) {
9935            this.pkg = pkg;
9936            this.pkgSetting = pkgSetting;
9937            this.sharedUserSetting = sharedUserSetting;
9938            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9939            this.disabledPkgSetting = disabledPkgSetting;
9940            this.originalPkgSetting = originalPkgSetting;
9941            this.realPkgName = realPkgName;
9942            this.parseFlags = parseFlags;
9943            this.scanFlags = scanFlags;
9944            this.isPlatformPackage = isPlatformPackage;
9945            this.user = user;
9946        }
9947    }
9948
9949    /**
9950     * Returns the actual scan flags depending upon the state of the other settings.
9951     * <p>Updated system applications will not have the following flags set
9952     * by default and need to be adjusted after the fact:
9953     * <ul>
9954     * <li>{@link #SCAN_AS_SYSTEM}</li>
9955     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9956     * <li>{@link #SCAN_AS_OEM}</li>
9957     * <li>{@link #SCAN_AS_VENDOR}</li>
9958     * <li>{@link #SCAN_AS_PRODUCT}</li>
9959     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9960     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9961     * </ul>
9962     */
9963    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9964            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9965            PackageParser.Package pkg) {
9966        if (disabledPkgSetting != null) {
9967            // updated system application, must at least have SCAN_AS_SYSTEM
9968            scanFlags |= SCAN_AS_SYSTEM;
9969            if ((disabledPkgSetting.pkgPrivateFlags
9970                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9971                scanFlags |= SCAN_AS_PRIVILEGED;
9972            }
9973            if ((disabledPkgSetting.pkgPrivateFlags
9974                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9975                scanFlags |= SCAN_AS_OEM;
9976            }
9977            if ((disabledPkgSetting.pkgPrivateFlags
9978                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9979                scanFlags |= SCAN_AS_VENDOR;
9980            }
9981            if ((disabledPkgSetting.pkgPrivateFlags
9982                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9983                scanFlags |= SCAN_AS_PRODUCT;
9984            }
9985        }
9986        if (pkgSetting != null) {
9987            final int userId = ((user == null) ? 0 : user.getIdentifier());
9988            if (pkgSetting.getInstantApp(userId)) {
9989                scanFlags |= SCAN_AS_INSTANT_APP;
9990            }
9991            if (pkgSetting.getVirtulalPreload(userId)) {
9992                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9993            }
9994        }
9995
9996        // Scan as privileged apps that share a user with a priv-app.
9997        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9998                && (pkg.mSharedUserId != null)) {
9999            SharedUserSetting sharedUserSetting = null;
10000            try {
10001                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10002            } catch (PackageManagerException ignore) {}
10003            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10004                // Exempt SharedUsers signed with the platform key.
10005                // TODO(b/72378145) Fix this exemption. Force signature apps
10006                // to whitelist their privileged permissions just like other
10007                // priv-apps.
10008                synchronized (mPackages) {
10009                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10010                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
10011                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10012                        scanFlags |= SCAN_AS_PRIVILEGED;
10013                    }
10014                }
10015            }
10016        }
10017
10018        return scanFlags;
10019    }
10020
10021    @GuardedBy("mInstallLock")
10022    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10023            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10024            @Nullable UserHandle user) throws PackageManagerException {
10025
10026        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10027        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10028        if (realPkgName != null) {
10029            ensurePackageRenamed(pkg, renamedPkgName);
10030        }
10031        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10032        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10033        final PackageSetting disabledPkgSetting =
10034                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10035
10036        if (mTransferedPackages.contains(pkg.packageName)) {
10037            Slog.w(TAG, "Package " + pkg.packageName
10038                    + " was transferred to another, but its .apk remains");
10039        }
10040
10041        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10042        synchronized (mPackages) {
10043            applyPolicy(pkg, parseFlags, scanFlags);
10044            assertPackageIsValid(pkg, parseFlags, scanFlags);
10045
10046            SharedUserSetting sharedUserSetting = null;
10047            if (pkg.mSharedUserId != null) {
10048                // SIDE EFFECTS; may potentially allocate a new shared user
10049                sharedUserSetting = mSettings.getSharedUserLPw(
10050                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10051                if (DEBUG_PACKAGE_SCANNING) {
10052                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10053                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10054                                + " (uid=" + sharedUserSetting.userId + "):"
10055                                + " packages=" + sharedUserSetting.packages);
10056                }
10057            }
10058
10059            boolean scanSucceeded = false;
10060            try {
10061                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10062                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10063                        (pkg == mPlatformPackage), user);
10064                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10065                if (result.success) {
10066                    commitScanResultsLocked(request, result);
10067                }
10068                scanSucceeded = true;
10069            } finally {
10070                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10071                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10072                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10073                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10074                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10075                  }
10076            }
10077        }
10078        return pkg;
10079    }
10080
10081    /**
10082     * Commits the package scan and modifies system state.
10083     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10084     * of committing the package, leaving the system in an inconsistent state.
10085     * This needs to be fixed so, once we get to this point, no errors are
10086     * possible and the system is not left in an inconsistent state.
10087     */
10088    @GuardedBy("mPackages")
10089    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10090            throws PackageManagerException {
10091        final PackageParser.Package pkg = request.pkg;
10092        final @ParseFlags int parseFlags = request.parseFlags;
10093        final @ScanFlags int scanFlags = request.scanFlags;
10094        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10095        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10096        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10097        final UserHandle user = request.user;
10098        final String realPkgName = request.realPkgName;
10099        final PackageSetting pkgSetting = result.pkgSetting;
10100        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10101        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10102
10103        if (newPkgSettingCreated) {
10104            if (originalPkgSetting != null) {
10105                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10106            }
10107            // THROWS: when we can't allocate a user id. add call to check if there's
10108            // enough space to ensure we won't throw; otherwise, don't modify state
10109            mSettings.addUserToSettingLPw(pkgSetting);
10110
10111            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10112                mTransferedPackages.add(originalPkgSetting.name);
10113            }
10114        }
10115        // TODO(toddke): Consider a method specifically for modifying the Package object
10116        // post scan; or, moving this stuff out of the Package object since it has nothing
10117        // to do with the package on disk.
10118        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10119        // for creating the application ID. If we did this earlier, we would be saving the
10120        // correct ID.
10121        pkg.applicationInfo.uid = pkgSetting.appId;
10122
10123        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10124
10125        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10126            mTransferedPackages.add(pkg.packageName);
10127        }
10128
10129        // THROWS: when requested libraries that can't be found. it only changes
10130        // the state of the passed in pkg object, so, move to the top of the method
10131        // and allow it to abort
10132        if ((scanFlags & SCAN_BOOTING) == 0
10133                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10134            // Check all shared libraries and map to their actual file path.
10135            // We only do this here for apps not on a system dir, because those
10136            // are the only ones that can fail an install due to this.  We
10137            // will take care of the system apps by updating all of their
10138            // library paths after the scan is done. Also during the initial
10139            // scan don't update any libs as we do this wholesale after all
10140            // apps are scanned to avoid dependency based scanning.
10141            updateSharedLibrariesLPr(pkg, null);
10142        }
10143
10144        // All versions of a static shared library are referenced with the same
10145        // package name. Internally, we use a synthetic package name to allow
10146        // multiple versions of the same shared library to be installed. So,
10147        // we need to generate the synthetic package name of the latest shared
10148        // library in order to compare signatures.
10149        PackageSetting signatureCheckPs = pkgSetting;
10150        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10151            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10152            if (libraryEntry != null) {
10153                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10154            }
10155        }
10156
10157        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10158        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10159            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10160                // We just determined the app is signed correctly, so bring
10161                // over the latest parsed certs.
10162                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10163            } else {
10164                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10165                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10166                            "Package " + pkg.packageName + " upgrade keys do not match the "
10167                                    + "previously installed version");
10168                } else {
10169                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10170                    String msg = "System package " + pkg.packageName
10171                            + " signature changed; retaining data.";
10172                    reportSettingsProblem(Log.WARN, msg);
10173                }
10174            }
10175        } else {
10176            try {
10177                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10178                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10179                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10180                        pkg.mSigningDetails, compareCompat, compareRecover);
10181                // The new KeySets will be re-added later in the scanning process.
10182                if (compatMatch) {
10183                    synchronized (mPackages) {
10184                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10185                    }
10186                }
10187                // We just determined the app is signed correctly, so bring
10188                // over the latest parsed certs.
10189                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10190
10191
10192                // if this is is a sharedUser, check to see if the new package is signed by a newer
10193                // signing certificate than the existing one, and if so, copy over the new details
10194                if (signatureCheckPs.sharedUser != null
10195                        && pkg.mSigningDetails.hasAncestor(
10196                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10197                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10198                }
10199            } catch (PackageManagerException e) {
10200                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10201                    throw e;
10202                }
10203                // The signature has changed, but this package is in the system
10204                // image...  let's recover!
10205                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10206                // However...  if this package is part of a shared user, but it
10207                // doesn't match the signature of the shared user, let's fail.
10208                // What this means is that you can't change the signatures
10209                // associated with an overall shared user, which doesn't seem all
10210                // that unreasonable.
10211                if (signatureCheckPs.sharedUser != null) {
10212                    if (compareSignatures(
10213                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10214                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10215                        throw new PackageManagerException(
10216                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10217                                "Signature mismatch for shared user: "
10218                                        + pkgSetting.sharedUser);
10219                    }
10220                }
10221                // File a report about this.
10222                String msg = "System package " + pkg.packageName
10223                        + " signature changed; retaining data.";
10224                reportSettingsProblem(Log.WARN, msg);
10225            } catch (IllegalArgumentException e) {
10226
10227                // should never happen: certs matched when checking, but not when comparing
10228                // old to new for sharedUser
10229                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10230                        "Signing certificates comparison made on incomparable signing details"
10231                        + " but somehow passed verifySignatures!");
10232            }
10233        }
10234
10235        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10236            // This package wants to adopt ownership of permissions from
10237            // another package.
10238            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10239                final String origName = pkg.mAdoptPermissions.get(i);
10240                final PackageSetting orig = mSettings.getPackageLPr(origName);
10241                if (orig != null) {
10242                    if (verifyPackageUpdateLPr(orig, pkg)) {
10243                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10244                                + pkg.packageName);
10245                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10246                    }
10247                }
10248            }
10249        }
10250
10251        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10252            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10253                final String codePathString = changedAbiCodePath.get(i);
10254                try {
10255                    mInstaller.rmdex(codePathString,
10256                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10257                } catch (InstallerException ignored) {
10258                }
10259            }
10260        }
10261
10262        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10263            if (oldPkgSetting != null) {
10264                synchronized (mPackages) {
10265                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10266                }
10267            }
10268        } else {
10269            final int userId = user == null ? 0 : user.getIdentifier();
10270            // Modify state for the given package setting
10271            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10272                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10273            if (pkgSetting.getInstantApp(userId)) {
10274                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10275            }
10276        }
10277    }
10278
10279    /**
10280     * Returns the "real" name of the package.
10281     * <p>This may differ from the package's actual name if the application has already
10282     * been installed under one of this package's original names.
10283     */
10284    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10285            @Nullable String renamedPkgName) {
10286        if (isPackageRenamed(pkg, renamedPkgName)) {
10287            return pkg.mRealPackage;
10288        }
10289        return null;
10290    }
10291
10292    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10293    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10294            @Nullable String renamedPkgName) {
10295        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10296    }
10297
10298    /**
10299     * Returns the original package setting.
10300     * <p>A package can migrate its name during an update. In this scenario, a package
10301     * designates a set of names that it considers as one of its original names.
10302     * <p>An original package must be signed identically and it must have the same
10303     * shared user [if any].
10304     */
10305    @GuardedBy("mPackages")
10306    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10307            @Nullable String renamedPkgName) {
10308        if (!isPackageRenamed(pkg, renamedPkgName)) {
10309            return null;
10310        }
10311        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10312            final PackageSetting originalPs =
10313                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10314            if (originalPs != null) {
10315                // the package is already installed under its original name...
10316                // but, should we use it?
10317                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10318                    // the new package is incompatible with the original
10319                    continue;
10320                } else if (originalPs.sharedUser != null) {
10321                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10322                        // the shared user id is incompatible with the original
10323                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10324                                + " to " + pkg.packageName + ": old uid "
10325                                + originalPs.sharedUser.name
10326                                + " differs from " + pkg.mSharedUserId);
10327                        continue;
10328                    }
10329                    // TODO: Add case when shared user id is added [b/28144775]
10330                } else {
10331                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10332                            + pkg.packageName + " to old name " + originalPs.name);
10333                }
10334                return originalPs;
10335            }
10336        }
10337        return null;
10338    }
10339
10340    /**
10341     * Renames the package if it was installed under a different name.
10342     * <p>When we've already installed the package under an original name, update
10343     * the new package so we can continue to have the old name.
10344     */
10345    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10346            @NonNull String renamedPackageName) {
10347        if (pkg.mOriginalPackages == null
10348                || !pkg.mOriginalPackages.contains(renamedPackageName)
10349                || pkg.packageName.equals(renamedPackageName)) {
10350            return;
10351        }
10352        pkg.setPackageName(renamedPackageName);
10353    }
10354
10355    /**
10356     * Just scans the package without any side effects.
10357     * <p>Not entirely true at the moment. There is still one side effect -- this
10358     * method potentially modifies a live {@link PackageSetting} object representing
10359     * the package being scanned. This will be resolved in the future.
10360     *
10361     * @param request Information about the package to be scanned
10362     * @param isUnderFactoryTest Whether or not the device is under factory test
10363     * @param currentTime The current time, in millis
10364     * @return The results of the scan
10365     */
10366    @GuardedBy("mInstallLock")
10367    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10368            boolean isUnderFactoryTest, long currentTime)
10369                    throws PackageManagerException {
10370        final PackageParser.Package pkg = request.pkg;
10371        PackageSetting pkgSetting = request.pkgSetting;
10372        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10373        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10374        final @ParseFlags int parseFlags = request.parseFlags;
10375        final @ScanFlags int scanFlags = request.scanFlags;
10376        final String realPkgName = request.realPkgName;
10377        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10378        final UserHandle user = request.user;
10379        final boolean isPlatformPackage = request.isPlatformPackage;
10380
10381        List<String> changedAbiCodePath = null;
10382
10383        if (DEBUG_PACKAGE_SCANNING) {
10384            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10385                Log.d(TAG, "Scanning package " + pkg.packageName);
10386        }
10387
10388        if (Build.IS_DEBUGGABLE &&
10389                pkg.isPrivileged() &&
10390                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10391            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10392        }
10393
10394        // Initialize package source and resource directories
10395        final File scanFile = new File(pkg.codePath);
10396        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10397        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10398
10399        // We keep references to the derived CPU Abis from settings in oder to reuse
10400        // them in the case where we're not upgrading or booting for the first time.
10401        String primaryCpuAbiFromSettings = null;
10402        String secondaryCpuAbiFromSettings = null;
10403        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10404
10405        if (!needToDeriveAbi) {
10406            if (pkgSetting != null) {
10407                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10408                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10409            } else {
10410                // Re-scanning a system package after uninstalling updates; need to derive ABI
10411                needToDeriveAbi = true;
10412            }
10413        }
10414
10415        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10416            PackageManagerService.reportSettingsProblem(Log.WARN,
10417                    "Package " + pkg.packageName + " shared user changed from "
10418                            + (pkgSetting.sharedUser != null
10419                            ? pkgSetting.sharedUser.name : "<nothing>")
10420                            + " to "
10421                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10422                            + "; replacing with new");
10423            pkgSetting = null;
10424        }
10425
10426        String[] usesStaticLibraries = null;
10427        if (pkg.usesStaticLibraries != null) {
10428            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10429            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10430        }
10431        final boolean createNewPackage = (pkgSetting == null);
10432        if (createNewPackage) {
10433            final String parentPackageName = (pkg.parentPackage != null)
10434                    ? pkg.parentPackage.packageName : null;
10435            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10436            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10437            // REMOVE SharedUserSetting from method; update in a separate call
10438            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10439                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10440                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10441                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10442                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10443                    user, true /*allowInstall*/, instantApp, virtualPreload,
10444                    parentPackageName, pkg.getChildPackageNames(),
10445                    UserManagerService.getInstance(), usesStaticLibraries,
10446                    pkg.usesStaticLibrariesVersions);
10447        } else {
10448            // REMOVE SharedUserSetting from method; update in a separate call.
10449            //
10450            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10451            // secondaryCpuAbi are not known at this point so we always update them
10452            // to null here, only to reset them at a later point.
10453            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10454                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10455                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10456                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10457                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10458                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10459        }
10460        if (createNewPackage && originalPkgSetting != null) {
10461            // This is the initial transition from the original package, so,
10462            // fix up the new package's name now. We must do this after looking
10463            // up the package under its new name, so getPackageLP takes care of
10464            // fiddling things correctly.
10465            pkg.setPackageName(originalPkgSetting.name);
10466
10467            // File a report about this.
10468            String msg = "New package " + pkgSetting.realName
10469                    + " renamed to replace old package " + pkgSetting.name;
10470            reportSettingsProblem(Log.WARN, msg);
10471        }
10472
10473        if (disabledPkgSetting != null) {
10474            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10475        }
10476
10477        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10478        // To ensure that apps with sharedUserId are placed in the same selinux domain
10479        // without breaking any assumptions about access, put them into the least
10480        // restrictive targetSdkVersion=25 domain.
10481        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10482        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10483        final int targetSdk = (sharedUserSetting != null) ? 25
10484                : pkg.applicationInfo.targetSdkVersion;
10485        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10486        // They currently can be if the sharedUser apps are signed with the platform key.
10487        final boolean isPrivileged = (sharedUserSetting != null) ?
10488            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10489
10490        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10491
10492        pkg.mExtras = pkgSetting;
10493        pkg.applicationInfo.processName = fixProcessName(
10494                pkg.applicationInfo.packageName,
10495                pkg.applicationInfo.processName);
10496
10497        if (!isPlatformPackage) {
10498            // Get all of our default paths setup
10499            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10500        }
10501
10502        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10503
10504        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10505            if (needToDeriveAbi) {
10506                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10507                final boolean extractNativeLibs = !pkg.isLibrary();
10508                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10509                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10510
10511                // Some system apps still use directory structure for native libraries
10512                // in which case we might end up not detecting abi solely based on apk
10513                // structure. Try to detect abi based on directory structure.
10514                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10515                        pkg.applicationInfo.primaryCpuAbi == null) {
10516                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10517                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10518                }
10519            } else {
10520                // This is not a first boot or an upgrade, don't bother deriving the
10521                // ABI during the scan. Instead, trust the value that was stored in the
10522                // package setting.
10523                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10524                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10525
10526                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10527
10528                if (DEBUG_ABI_SELECTION) {
10529                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10530                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10531                            pkg.applicationInfo.secondaryCpuAbi);
10532                }
10533            }
10534        } else {
10535            if ((scanFlags & SCAN_MOVE) != 0) {
10536                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10537                // but we already have this packages package info in the PackageSetting. We just
10538                // use that and derive the native library path based on the new codepath.
10539                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10540                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10541            }
10542
10543            // Set native library paths again. For moves, the path will be updated based on the
10544            // ABIs we've determined above. For non-moves, the path will be updated based on the
10545            // ABIs we determined during compilation, but the path will depend on the final
10546            // package path (after the rename away from the stage path).
10547            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10548        }
10549
10550        // This is a special case for the "system" package, where the ABI is
10551        // dictated by the zygote configuration (and init.rc). We should keep track
10552        // of this ABI so that we can deal with "normal" applications that run under
10553        // the same UID correctly.
10554        if (isPlatformPackage) {
10555            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10556                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10557        }
10558
10559        // If there's a mismatch between the abi-override in the package setting
10560        // and the abiOverride specified for the install. Warn about this because we
10561        // would've already compiled the app without taking the package setting into
10562        // account.
10563        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10564            if (cpuAbiOverride == null && pkg.packageName != null) {
10565                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10566                        " for package " + pkg.packageName);
10567            }
10568        }
10569
10570        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10571        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10572        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10573
10574        // Copy the derived override back to the parsed package, so that we can
10575        // update the package settings accordingly.
10576        pkg.cpuAbiOverride = cpuAbiOverride;
10577
10578        if (DEBUG_ABI_SELECTION) {
10579            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10580                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10581                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10582        }
10583
10584        // Push the derived path down into PackageSettings so we know what to
10585        // clean up at uninstall time.
10586        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10587
10588        if (DEBUG_ABI_SELECTION) {
10589            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10590                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10591                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10592        }
10593
10594        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10595            // We don't do this here during boot because we can do it all
10596            // at once after scanning all existing packages.
10597            //
10598            // We also do this *before* we perform dexopt on this package, so that
10599            // we can avoid redundant dexopts, and also to make sure we've got the
10600            // code and package path correct.
10601            changedAbiCodePath =
10602                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10603        }
10604
10605        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10606                android.Manifest.permission.FACTORY_TEST)) {
10607            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10608        }
10609
10610        if (isSystemApp(pkg)) {
10611            pkgSetting.isOrphaned = true;
10612        }
10613
10614        // Take care of first install / last update times.
10615        final long scanFileTime = getLastModifiedTime(pkg);
10616        if (currentTime != 0) {
10617            if (pkgSetting.firstInstallTime == 0) {
10618                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10619            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10620                pkgSetting.lastUpdateTime = currentTime;
10621            }
10622        } else if (pkgSetting.firstInstallTime == 0) {
10623            // We need *something*.  Take time time stamp of the file.
10624            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10625        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10626            if (scanFileTime != pkgSetting.timeStamp) {
10627                // A package on the system image has changed; consider this
10628                // to be an update.
10629                pkgSetting.lastUpdateTime = scanFileTime;
10630            }
10631        }
10632        pkgSetting.setTimeStamp(scanFileTime);
10633
10634        pkgSetting.pkg = pkg;
10635        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10636        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10637            pkgSetting.versionCode = pkg.getLongVersionCode();
10638        }
10639        // Update volume if needed
10640        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10641        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10642            Slog.i(PackageManagerService.TAG,
10643                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10644                    + " package " + pkg.packageName
10645                    + " volume from " + pkgSetting.volumeUuid
10646                    + " to " + volumeUuid);
10647            pkgSetting.volumeUuid = volumeUuid;
10648        }
10649
10650        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10651    }
10652
10653    /**
10654     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10655     */
10656    private static boolean apkHasCode(String fileName) {
10657        StrictJarFile jarFile = null;
10658        try {
10659            jarFile = new StrictJarFile(fileName,
10660                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10661            return jarFile.findEntry("classes.dex") != null;
10662        } catch (IOException ignore) {
10663        } finally {
10664            try {
10665                if (jarFile != null) {
10666                    jarFile.close();
10667                }
10668            } catch (IOException ignore) {}
10669        }
10670        return false;
10671    }
10672
10673    /**
10674     * Enforces code policy for the package. This ensures that if an APK has
10675     * declared hasCode="true" in its manifest that the APK actually contains
10676     * code.
10677     *
10678     * @throws PackageManagerException If bytecode could not be found when it should exist
10679     */
10680    private static void assertCodePolicy(PackageParser.Package pkg)
10681            throws PackageManagerException {
10682        final boolean shouldHaveCode =
10683                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10684        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10685            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10686                    "Package " + pkg.baseCodePath + " code is missing");
10687        }
10688
10689        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10690            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10691                final boolean splitShouldHaveCode =
10692                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10693                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10694                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10695                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10696                }
10697            }
10698        }
10699    }
10700
10701    /**
10702     * Applies policy to the parsed package based upon the given policy flags.
10703     * Ensures the package is in a good state.
10704     * <p>
10705     * Implementation detail: This method must NOT have any side effect. It would
10706     * ideally be static, but, it requires locks to read system state.
10707     */
10708    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10709            final @ScanFlags int scanFlags) {
10710        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10711            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10712            if (pkg.applicationInfo.isDirectBootAware()) {
10713                // we're direct boot aware; set for all components
10714                for (PackageParser.Service s : pkg.services) {
10715                    s.info.encryptionAware = s.info.directBootAware = true;
10716                }
10717                for (PackageParser.Provider p : pkg.providers) {
10718                    p.info.encryptionAware = p.info.directBootAware = true;
10719                }
10720                for (PackageParser.Activity a : pkg.activities) {
10721                    a.info.encryptionAware = a.info.directBootAware = true;
10722                }
10723                for (PackageParser.Activity r : pkg.receivers) {
10724                    r.info.encryptionAware = r.info.directBootAware = true;
10725                }
10726            }
10727            if (compressedFileExists(pkg.codePath)) {
10728                pkg.isStub = true;
10729            }
10730        } else {
10731            // non system apps can't be flagged as core
10732            pkg.coreApp = false;
10733            // clear flags not applicable to regular apps
10734            pkg.applicationInfo.flags &=
10735                    ~ApplicationInfo.FLAG_PERSISTENT;
10736            pkg.applicationInfo.privateFlags &=
10737                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10738            pkg.applicationInfo.privateFlags &=
10739                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10740            // clear protected broadcasts
10741            pkg.protectedBroadcasts = null;
10742            // cap permission priorities
10743            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10744                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10745                    pkg.permissionGroups.get(i).info.priority = 0;
10746                }
10747            }
10748        }
10749        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10750            // ignore export request for single user receivers
10751            if (pkg.receivers != null) {
10752                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10753                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10754                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10755                        receiver.info.exported = false;
10756                    }
10757                }
10758            }
10759            // ignore export request for single user services
10760            if (pkg.services != null) {
10761                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10762                    final PackageParser.Service service = pkg.services.get(i);
10763                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10764                        service.info.exported = false;
10765                    }
10766                }
10767            }
10768            // ignore export request for single user providers
10769            if (pkg.providers != null) {
10770                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10771                    final PackageParser.Provider provider = pkg.providers.get(i);
10772                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10773                        provider.info.exported = false;
10774                    }
10775                }
10776            }
10777        }
10778
10779        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10780            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10781        }
10782
10783        if ((scanFlags & SCAN_AS_OEM) != 0) {
10784            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10785        }
10786
10787        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10788            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10789        }
10790
10791        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10792            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10793        }
10794
10795        if (!isSystemApp(pkg)) {
10796            // Only system apps can use these features.
10797            pkg.mOriginalPackages = null;
10798            pkg.mRealPackage = null;
10799            pkg.mAdoptPermissions = null;
10800        }
10801    }
10802
10803    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10804            throws PackageManagerException {
10805        if (object == null) {
10806            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10807        }
10808        return object;
10809    }
10810
10811    /**
10812     * Asserts the parsed package is valid according to the given policy. If the
10813     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10814     * <p>
10815     * Implementation detail: This method must NOT have any side effects. It would
10816     * ideally be static, but, it requires locks to read system state.
10817     *
10818     * @throws PackageManagerException If the package fails any of the validation checks
10819     */
10820    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10821            final @ScanFlags int scanFlags)
10822                    throws PackageManagerException {
10823        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10824            assertCodePolicy(pkg);
10825        }
10826
10827        if (pkg.applicationInfo.getCodePath() == null ||
10828                pkg.applicationInfo.getResourcePath() == null) {
10829            // Bail out. The resource and code paths haven't been set.
10830            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10831                    "Code and resource paths haven't been set correctly");
10832        }
10833
10834        // Make sure we're not adding any bogus keyset info
10835        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10836        ksms.assertScannedPackageValid(pkg);
10837
10838        synchronized (mPackages) {
10839            // The special "android" package can only be defined once
10840            if (pkg.packageName.equals("android")) {
10841                if (mAndroidApplication != null) {
10842                    Slog.w(TAG, "*************************************************");
10843                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10844                    Slog.w(TAG, " codePath=" + pkg.codePath);
10845                    Slog.w(TAG, "*************************************************");
10846                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10847                            "Core android package being redefined.  Skipping.");
10848                }
10849            }
10850
10851            // A package name must be unique; don't allow duplicates
10852            if (mPackages.containsKey(pkg.packageName)) {
10853                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10854                        "Application package " + pkg.packageName
10855                        + " already installed.  Skipping duplicate.");
10856            }
10857
10858            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10859                // Static libs have a synthetic package name containing the version
10860                // but we still want the base name to be unique.
10861                if (mPackages.containsKey(pkg.manifestPackageName)) {
10862                    throw new PackageManagerException(
10863                            "Duplicate static shared lib provider package");
10864                }
10865
10866                // Static shared libraries should have at least O target SDK
10867                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10868                    throw new PackageManagerException(
10869                            "Packages declaring static-shared libs must target O SDK or higher");
10870                }
10871
10872                // Package declaring static a shared lib cannot be instant apps
10873                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10874                    throw new PackageManagerException(
10875                            "Packages declaring static-shared libs cannot be instant apps");
10876                }
10877
10878                // Package declaring static a shared lib cannot be renamed since the package
10879                // name is synthetic and apps can't code around package manager internals.
10880                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10881                    throw new PackageManagerException(
10882                            "Packages declaring static-shared libs cannot be renamed");
10883                }
10884
10885                // Package declaring static a shared lib cannot declare child packages
10886                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10887                    throw new PackageManagerException(
10888                            "Packages declaring static-shared libs cannot have child packages");
10889                }
10890
10891                // Package declaring static a shared lib cannot declare dynamic libs
10892                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10893                    throw new PackageManagerException(
10894                            "Packages declaring static-shared libs cannot declare dynamic libs");
10895                }
10896
10897                // Package declaring static a shared lib cannot declare shared users
10898                if (pkg.mSharedUserId != null) {
10899                    throw new PackageManagerException(
10900                            "Packages declaring static-shared libs cannot declare shared users");
10901                }
10902
10903                // Static shared libs cannot declare activities
10904                if (!pkg.activities.isEmpty()) {
10905                    throw new PackageManagerException(
10906                            "Static shared libs cannot declare activities");
10907                }
10908
10909                // Static shared libs cannot declare services
10910                if (!pkg.services.isEmpty()) {
10911                    throw new PackageManagerException(
10912                            "Static shared libs cannot declare services");
10913                }
10914
10915                // Static shared libs cannot declare providers
10916                if (!pkg.providers.isEmpty()) {
10917                    throw new PackageManagerException(
10918                            "Static shared libs cannot declare content providers");
10919                }
10920
10921                // Static shared libs cannot declare receivers
10922                if (!pkg.receivers.isEmpty()) {
10923                    throw new PackageManagerException(
10924                            "Static shared libs cannot declare broadcast receivers");
10925                }
10926
10927                // Static shared libs cannot declare permission groups
10928                if (!pkg.permissionGroups.isEmpty()) {
10929                    throw new PackageManagerException(
10930                            "Static shared libs cannot declare permission groups");
10931                }
10932
10933                // Static shared libs cannot declare permissions
10934                if (!pkg.permissions.isEmpty()) {
10935                    throw new PackageManagerException(
10936                            "Static shared libs cannot declare permissions");
10937                }
10938
10939                // Static shared libs cannot declare protected broadcasts
10940                if (pkg.protectedBroadcasts != null) {
10941                    throw new PackageManagerException(
10942                            "Static shared libs cannot declare protected broadcasts");
10943                }
10944
10945                // Static shared libs cannot be overlay targets
10946                if (pkg.mOverlayTarget != null) {
10947                    throw new PackageManagerException(
10948                            "Static shared libs cannot be overlay targets");
10949                }
10950
10951                // The version codes must be ordered as lib versions
10952                long minVersionCode = Long.MIN_VALUE;
10953                long maxVersionCode = Long.MAX_VALUE;
10954
10955                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10956                        pkg.staticSharedLibName);
10957                if (versionedLib != null) {
10958                    final int versionCount = versionedLib.size();
10959                    for (int i = 0; i < versionCount; i++) {
10960                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10961                        final long libVersionCode = libInfo.getDeclaringPackage()
10962                                .getLongVersionCode();
10963                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10964                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10965                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10966                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10967                        } else {
10968                            minVersionCode = maxVersionCode = libVersionCode;
10969                            break;
10970                        }
10971                    }
10972                }
10973                if (pkg.getLongVersionCode() < minVersionCode
10974                        || pkg.getLongVersionCode() > maxVersionCode) {
10975                    throw new PackageManagerException("Static shared"
10976                            + " lib version codes must be ordered as lib versions");
10977                }
10978            }
10979
10980            // Only privileged apps and updated privileged apps can add child packages.
10981            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10982                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10983                    throw new PackageManagerException("Only privileged apps can add child "
10984                            + "packages. Ignoring package " + pkg.packageName);
10985                }
10986                final int childCount = pkg.childPackages.size();
10987                for (int i = 0; i < childCount; i++) {
10988                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10989                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10990                            childPkg.packageName)) {
10991                        throw new PackageManagerException("Can't override child of "
10992                                + "another disabled app. Ignoring package " + pkg.packageName);
10993                    }
10994                }
10995            }
10996
10997            // If we're only installing presumed-existing packages, require that the
10998            // scanned APK is both already known and at the path previously established
10999            // for it.  Previously unknown packages we pick up normally, but if we have an
11000            // a priori expectation about this package's install presence, enforce it.
11001            // With a singular exception for new system packages. When an OTA contains
11002            // a new system package, we allow the codepath to change from a system location
11003            // to the user-installed location. If we don't allow this change, any newer,
11004            // user-installed version of the application will be ignored.
11005            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11006                if (mExpectingBetter.containsKey(pkg.packageName)) {
11007                    logCriticalInfo(Log.WARN,
11008                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11009                } else {
11010                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11011                    if (known != null) {
11012                        if (DEBUG_PACKAGE_SCANNING) {
11013                            Log.d(TAG, "Examining " + pkg.codePath
11014                                    + " and requiring known paths " + known.codePathString
11015                                    + " & " + known.resourcePathString);
11016                        }
11017                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11018                                || !pkg.applicationInfo.getResourcePath().equals(
11019                                        known.resourcePathString)) {
11020                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11021                                    "Application package " + pkg.packageName
11022                                    + " found at " + pkg.applicationInfo.getCodePath()
11023                                    + " but expected at " + known.codePathString
11024                                    + "; ignoring.");
11025                        }
11026                    } else {
11027                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11028                                "Application package " + pkg.packageName
11029                                + " not found; ignoring.");
11030                    }
11031                }
11032            }
11033
11034            // Verify that this new package doesn't have any content providers
11035            // that conflict with existing packages.  Only do this if the
11036            // package isn't already installed, since we don't want to break
11037            // things that are installed.
11038            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11039                final int N = pkg.providers.size();
11040                int i;
11041                for (i=0; i<N; i++) {
11042                    PackageParser.Provider p = pkg.providers.get(i);
11043                    if (p.info.authority != null) {
11044                        String names[] = p.info.authority.split(";");
11045                        for (int j = 0; j < names.length; j++) {
11046                            if (mProvidersByAuthority.containsKey(names[j])) {
11047                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11048                                final String otherPackageName =
11049                                        ((other != null && other.getComponentName() != null) ?
11050                                                other.getComponentName().getPackageName() : "?");
11051                                throw new PackageManagerException(
11052                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11053                                        "Can't install because provider name " + names[j]
11054                                                + " (in package " + pkg.applicationInfo.packageName
11055                                                + ") is already used by " + otherPackageName);
11056                            }
11057                        }
11058                    }
11059                }
11060            }
11061
11062            // Verify that packages sharing a user with a privileged app are marked as privileged.
11063            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11064                SharedUserSetting sharedUserSetting = null;
11065                try {
11066                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11067                } catch (PackageManagerException ignore) {}
11068                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11069                    // Exempt SharedUsers signed with the platform key.
11070                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11071                    if ((platformPkgSetting.signatures.mSigningDetails
11072                            != PackageParser.SigningDetails.UNKNOWN)
11073                            && (compareSignatures(
11074                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11075                                    pkg.mSigningDetails.signatures)
11076                                            != PackageManager.SIGNATURE_MATCH)) {
11077                        throw new PackageManagerException("Apps that share a user with a " +
11078                                "privileged app must themselves be marked as privileged. " +
11079                                pkg.packageName + " shares privileged user " +
11080                                pkg.mSharedUserId + ".");
11081                    }
11082                }
11083            }
11084
11085            // Apply policies specific for runtime resource overlays (RROs).
11086            if (pkg.mOverlayTarget != null) {
11087                // System overlays have some restrictions on their use of the 'static' state.
11088                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11089                    // We are scanning a system overlay. This can be the first scan of the
11090                    // system/vendor/oem partition, or an update to the system overlay.
11091                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11092                        // This must be an update to a system overlay.
11093                        final PackageSetting previousPkg = assertNotNull(
11094                                mSettings.getPackageLPr(pkg.packageName),
11095                                "previous package state not present");
11096
11097                        // Static overlays cannot be updated.
11098                        if (previousPkg.pkg.mOverlayIsStatic) {
11099                            throw new PackageManagerException("Overlay " + pkg.packageName +
11100                                    " is static and cannot be upgraded.");
11101                        // Non-static overlays cannot be converted to static overlays.
11102                        } else if (pkg.mOverlayIsStatic) {
11103                            throw new PackageManagerException("Overlay " + pkg.packageName +
11104                                    " cannot be upgraded into a static overlay.");
11105                        }
11106                    }
11107                } else {
11108                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11109                    if (pkg.mOverlayIsStatic) {
11110                        throw new PackageManagerException("Overlay " + pkg.packageName +
11111                                " is static but not pre-installed.");
11112                    }
11113
11114                    // The only case where we allow installation of a non-system overlay is when
11115                    // its signature is signed with the platform certificate.
11116                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11117                    if ((platformPkgSetting.signatures.mSigningDetails
11118                            != PackageParser.SigningDetails.UNKNOWN)
11119                            && (compareSignatures(
11120                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11121                                    pkg.mSigningDetails.signatures)
11122                                            != PackageManager.SIGNATURE_MATCH)) {
11123                        throw new PackageManagerException("Overlay " + pkg.packageName +
11124                                " must be signed with the platform certificate.");
11125                    }
11126                }
11127            }
11128        }
11129    }
11130
11131    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11132            int type, String declaringPackageName, long declaringVersionCode) {
11133        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11134        if (versionedLib == null) {
11135            versionedLib = new LongSparseArray<>();
11136            mSharedLibraries.put(name, versionedLib);
11137            if (type == SharedLibraryInfo.TYPE_STATIC) {
11138                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11139            }
11140        } else if (versionedLib.indexOfKey(version) >= 0) {
11141            return false;
11142        }
11143        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11144                version, type, declaringPackageName, declaringVersionCode);
11145        versionedLib.put(version, libEntry);
11146        return true;
11147    }
11148
11149    private boolean removeSharedLibraryLPw(String name, long version) {
11150        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11151        if (versionedLib == null) {
11152            return false;
11153        }
11154        final int libIdx = versionedLib.indexOfKey(version);
11155        if (libIdx < 0) {
11156            return false;
11157        }
11158        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11159        versionedLib.remove(version);
11160        if (versionedLib.size() <= 0) {
11161            mSharedLibraries.remove(name);
11162            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11163                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11164                        .getPackageName());
11165            }
11166        }
11167        return true;
11168    }
11169
11170    /**
11171     * Adds a scanned package to the system. When this method is finished, the package will
11172     * be available for query, resolution, etc...
11173     */
11174    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11175            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11176        final String pkgName = pkg.packageName;
11177        if (mCustomResolverComponentName != null &&
11178                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11179            setUpCustomResolverActivity(pkg);
11180        }
11181
11182        if (pkg.packageName.equals("android")) {
11183            synchronized (mPackages) {
11184                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11185                    // Set up information for our fall-back user intent resolution activity.
11186                    mPlatformPackage = pkg;
11187                    pkg.mVersionCode = mSdkVersion;
11188                    pkg.mVersionCodeMajor = 0;
11189                    mAndroidApplication = pkg.applicationInfo;
11190                    if (!mResolverReplaced) {
11191                        mResolveActivity.applicationInfo = mAndroidApplication;
11192                        mResolveActivity.name = ResolverActivity.class.getName();
11193                        mResolveActivity.packageName = mAndroidApplication.packageName;
11194                        mResolveActivity.processName = "system:ui";
11195                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11196                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11197                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11198                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11199                        mResolveActivity.exported = true;
11200                        mResolveActivity.enabled = true;
11201                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11202                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11203                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11204                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11205                                | ActivityInfo.CONFIG_ORIENTATION
11206                                | ActivityInfo.CONFIG_KEYBOARD
11207                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11208                        mResolveInfo.activityInfo = mResolveActivity;
11209                        mResolveInfo.priority = 0;
11210                        mResolveInfo.preferredOrder = 0;
11211                        mResolveInfo.match = 0;
11212                        mResolveComponentName = new ComponentName(
11213                                mAndroidApplication.packageName, mResolveActivity.name);
11214                    }
11215                }
11216            }
11217        }
11218
11219        ArrayList<PackageParser.Package> clientLibPkgs = null;
11220        // writer
11221        synchronized (mPackages) {
11222            boolean hasStaticSharedLibs = false;
11223
11224            // Any app can add new static shared libraries
11225            if (pkg.staticSharedLibName != null) {
11226                // Static shared libs don't allow renaming as they have synthetic package
11227                // names to allow install of multiple versions, so use name from manifest.
11228                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11229                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11230                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11231                    hasStaticSharedLibs = true;
11232                } else {
11233                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11234                                + pkg.staticSharedLibName + " already exists; skipping");
11235                }
11236                // Static shared libs cannot be updated once installed since they
11237                // use synthetic package name which includes the version code, so
11238                // not need to update other packages's shared lib dependencies.
11239            }
11240
11241            if (!hasStaticSharedLibs
11242                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11243                // Only system apps can add new dynamic shared libraries.
11244                if (pkg.libraryNames != null) {
11245                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11246                        String name = pkg.libraryNames.get(i);
11247                        boolean allowed = false;
11248                        if (pkg.isUpdatedSystemApp()) {
11249                            // New library entries can only be added through the
11250                            // system image.  This is important to get rid of a lot
11251                            // of nasty edge cases: for example if we allowed a non-
11252                            // system update of the app to add a library, then uninstalling
11253                            // the update would make the library go away, and assumptions
11254                            // we made such as through app install filtering would now
11255                            // have allowed apps on the device which aren't compatible
11256                            // with it.  Better to just have the restriction here, be
11257                            // conservative, and create many fewer cases that can negatively
11258                            // impact the user experience.
11259                            final PackageSetting sysPs = mSettings
11260                                    .getDisabledSystemPkgLPr(pkg.packageName);
11261                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11262                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11263                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11264                                        allowed = true;
11265                                        break;
11266                                    }
11267                                }
11268                            }
11269                        } else {
11270                            allowed = true;
11271                        }
11272                        if (allowed) {
11273                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11274                                    SharedLibraryInfo.VERSION_UNDEFINED,
11275                                    SharedLibraryInfo.TYPE_DYNAMIC,
11276                                    pkg.packageName, pkg.getLongVersionCode())) {
11277                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11278                                        + name + " already exists; skipping");
11279                            }
11280                        } else {
11281                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11282                                    + name + " that is not declared on system image; skipping");
11283                        }
11284                    }
11285
11286                    if ((scanFlags & SCAN_BOOTING) == 0) {
11287                        // If we are not booting, we need to update any applications
11288                        // that are clients of our shared library.  If we are booting,
11289                        // this will all be done once the scan is complete.
11290                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11291                    }
11292                }
11293            }
11294        }
11295
11296        if ((scanFlags & SCAN_BOOTING) != 0) {
11297            // No apps can run during boot scan, so they don't need to be frozen
11298        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11299            // Caller asked to not kill app, so it's probably not frozen
11300        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11301            // Caller asked us to ignore frozen check for some reason; they
11302            // probably didn't know the package name
11303        } else {
11304            // We're doing major surgery on this package, so it better be frozen
11305            // right now to keep it from launching
11306            checkPackageFrozen(pkgName);
11307        }
11308
11309        // Also need to kill any apps that are dependent on the library.
11310        if (clientLibPkgs != null) {
11311            for (int i=0; i<clientLibPkgs.size(); i++) {
11312                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11313                killApplication(clientPkg.applicationInfo.packageName,
11314                        clientPkg.applicationInfo.uid, "update lib");
11315            }
11316        }
11317
11318        // writer
11319        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11320
11321        synchronized (mPackages) {
11322            // We don't expect installation to fail beyond this point
11323
11324            // Add the new setting to mSettings
11325            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11326            // Add the new setting to mPackages
11327            mPackages.put(pkg.applicationInfo.packageName, pkg);
11328            // Make sure we don't accidentally delete its data.
11329            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11330            while (iter.hasNext()) {
11331                PackageCleanItem item = iter.next();
11332                if (pkgName.equals(item.packageName)) {
11333                    iter.remove();
11334                }
11335            }
11336
11337            // Add the package's KeySets to the global KeySetManagerService
11338            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11339            ksms.addScannedPackageLPw(pkg);
11340
11341            int N = pkg.providers.size();
11342            StringBuilder r = null;
11343            int i;
11344            for (i=0; i<N; i++) {
11345                PackageParser.Provider p = pkg.providers.get(i);
11346                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11347                        p.info.processName);
11348                mProviders.addProvider(p);
11349                p.syncable = p.info.isSyncable;
11350                if (p.info.authority != null) {
11351                    String names[] = p.info.authority.split(";");
11352                    p.info.authority = null;
11353                    for (int j = 0; j < names.length; j++) {
11354                        if (j == 1 && p.syncable) {
11355                            // We only want the first authority for a provider to possibly be
11356                            // syncable, so if we already added this provider using a different
11357                            // authority clear the syncable flag. We copy the provider before
11358                            // changing it because the mProviders object contains a reference
11359                            // to a provider that we don't want to change.
11360                            // Only do this for the second authority since the resulting provider
11361                            // object can be the same for all future authorities for this provider.
11362                            p = new PackageParser.Provider(p);
11363                            p.syncable = false;
11364                        }
11365                        if (!mProvidersByAuthority.containsKey(names[j])) {
11366                            mProvidersByAuthority.put(names[j], p);
11367                            if (p.info.authority == null) {
11368                                p.info.authority = names[j];
11369                            } else {
11370                                p.info.authority = p.info.authority + ";" + names[j];
11371                            }
11372                            if (DEBUG_PACKAGE_SCANNING) {
11373                                if (chatty)
11374                                    Log.d(TAG, "Registered content provider: " + names[j]
11375                                            + ", className = " + p.info.name + ", isSyncable = "
11376                                            + p.info.isSyncable);
11377                            }
11378                        } else {
11379                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11380                            Slog.w(TAG, "Skipping provider name " + names[j] +
11381                                    " (in package " + pkg.applicationInfo.packageName +
11382                                    "): name already used by "
11383                                    + ((other != null && other.getComponentName() != null)
11384                                            ? other.getComponentName().getPackageName() : "?"));
11385                        }
11386                    }
11387                }
11388                if (chatty) {
11389                    if (r == null) {
11390                        r = new StringBuilder(256);
11391                    } else {
11392                        r.append(' ');
11393                    }
11394                    r.append(p.info.name);
11395                }
11396            }
11397            if (r != null) {
11398                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11399            }
11400
11401            N = pkg.services.size();
11402            r = null;
11403            for (i=0; i<N; i++) {
11404                PackageParser.Service s = pkg.services.get(i);
11405                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11406                        s.info.processName);
11407                mServices.addService(s);
11408                if (chatty) {
11409                    if (r == null) {
11410                        r = new StringBuilder(256);
11411                    } else {
11412                        r.append(' ');
11413                    }
11414                    r.append(s.info.name);
11415                }
11416            }
11417            if (r != null) {
11418                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11419            }
11420
11421            N = pkg.receivers.size();
11422            r = null;
11423            for (i=0; i<N; i++) {
11424                PackageParser.Activity a = pkg.receivers.get(i);
11425                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11426                        a.info.processName);
11427                mReceivers.addActivity(a, "receiver");
11428                if (chatty) {
11429                    if (r == null) {
11430                        r = new StringBuilder(256);
11431                    } else {
11432                        r.append(' ');
11433                    }
11434                    r.append(a.info.name);
11435                }
11436            }
11437            if (r != null) {
11438                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11439            }
11440
11441            N = pkg.activities.size();
11442            r = null;
11443            for (i=0; i<N; i++) {
11444                PackageParser.Activity a = pkg.activities.get(i);
11445                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11446                        a.info.processName);
11447                mActivities.addActivity(a, "activity");
11448                if (chatty) {
11449                    if (r == null) {
11450                        r = new StringBuilder(256);
11451                    } else {
11452                        r.append(' ');
11453                    }
11454                    r.append(a.info.name);
11455                }
11456            }
11457            if (r != null) {
11458                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11459            }
11460
11461            // Don't allow ephemeral applications to define new permissions groups.
11462            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11463                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11464                        + " ignored: instant apps cannot define new permission groups.");
11465            } else {
11466                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11467            }
11468
11469            // Don't allow ephemeral applications to define new permissions.
11470            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11471                Slog.w(TAG, "Permissions from package " + pkg.packageName
11472                        + " ignored: instant apps cannot define new permissions.");
11473            } else {
11474                mPermissionManager.addAllPermissions(pkg, chatty);
11475            }
11476
11477            N = pkg.instrumentation.size();
11478            r = null;
11479            for (i=0; i<N; i++) {
11480                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11481                a.info.packageName = pkg.applicationInfo.packageName;
11482                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11483                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11484                a.info.splitNames = pkg.splitNames;
11485                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11486                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11487                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11488                a.info.dataDir = pkg.applicationInfo.dataDir;
11489                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11490                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11491                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11492                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11493                mInstrumentation.put(a.getComponentName(), a);
11494                if (chatty) {
11495                    if (r == null) {
11496                        r = new StringBuilder(256);
11497                    } else {
11498                        r.append(' ');
11499                    }
11500                    r.append(a.info.name);
11501                }
11502            }
11503            if (r != null) {
11504                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11505            }
11506
11507            if (pkg.protectedBroadcasts != null) {
11508                N = pkg.protectedBroadcasts.size();
11509                synchronized (mProtectedBroadcasts) {
11510                    for (i = 0; i < N; i++) {
11511                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11512                    }
11513                }
11514            }
11515        }
11516
11517        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11518    }
11519
11520    /**
11521     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11522     * is derived purely on the basis of the contents of {@code scanFile} and
11523     * {@code cpuAbiOverride}.
11524     *
11525     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11526     */
11527    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11528            boolean extractLibs)
11529                    throws PackageManagerException {
11530        // Give ourselves some initial paths; we'll come back for another
11531        // pass once we've determined ABI below.
11532        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11533
11534        // We would never need to extract libs for forward-locked and external packages,
11535        // since the container service will do it for us. We shouldn't attempt to
11536        // extract libs from system app when it was not updated.
11537        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11538                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11539            extractLibs = false;
11540        }
11541
11542        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11543        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11544
11545        NativeLibraryHelper.Handle handle = null;
11546        try {
11547            handle = NativeLibraryHelper.Handle.create(pkg);
11548            // TODO(multiArch): This can be null for apps that didn't go through the
11549            // usual installation process. We can calculate it again, like we
11550            // do during install time.
11551            //
11552            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11553            // unnecessary.
11554            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11555
11556            // Null out the abis so that they can be recalculated.
11557            pkg.applicationInfo.primaryCpuAbi = null;
11558            pkg.applicationInfo.secondaryCpuAbi = null;
11559            if (isMultiArch(pkg.applicationInfo)) {
11560                // Warn if we've set an abiOverride for multi-lib packages..
11561                // By definition, we need to copy both 32 and 64 bit libraries for
11562                // such packages.
11563                if (pkg.cpuAbiOverride != null
11564                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11565                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11566                }
11567
11568                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11569                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11570                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11571                    if (extractLibs) {
11572                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11573                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11574                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11575                                useIsaSpecificSubdirs);
11576                    } else {
11577                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11578                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11579                    }
11580                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11581                }
11582
11583                // Shared library native code should be in the APK zip aligned
11584                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11585                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11586                            "Shared library native lib extraction not supported");
11587                }
11588
11589                maybeThrowExceptionForMultiArchCopy(
11590                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11591
11592                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11593                    if (extractLibs) {
11594                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11595                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11596                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11597                                useIsaSpecificSubdirs);
11598                    } else {
11599                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11600                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11601                    }
11602                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11603                }
11604
11605                maybeThrowExceptionForMultiArchCopy(
11606                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11607
11608                if (abi64 >= 0) {
11609                    // Shared library native libs should be in the APK zip aligned
11610                    if (extractLibs && pkg.isLibrary()) {
11611                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11612                                "Shared library native lib extraction not supported");
11613                    }
11614                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11615                }
11616
11617                if (abi32 >= 0) {
11618                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11619                    if (abi64 >= 0) {
11620                        if (pkg.use32bitAbi) {
11621                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11622                            pkg.applicationInfo.primaryCpuAbi = abi;
11623                        } else {
11624                            pkg.applicationInfo.secondaryCpuAbi = abi;
11625                        }
11626                    } else {
11627                        pkg.applicationInfo.primaryCpuAbi = abi;
11628                    }
11629                }
11630            } else {
11631                String[] abiList = (cpuAbiOverride != null) ?
11632                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11633
11634                // Enable gross and lame hacks for apps that are built with old
11635                // SDK tools. We must scan their APKs for renderscript bitcode and
11636                // not launch them if it's present. Don't bother checking on devices
11637                // that don't have 64 bit support.
11638                boolean needsRenderScriptOverride = false;
11639                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11640                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11641                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11642                    needsRenderScriptOverride = true;
11643                }
11644
11645                final int copyRet;
11646                if (extractLibs) {
11647                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11648                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11649                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11650                } else {
11651                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11652                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11653                }
11654                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11655
11656                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11657                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11658                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11659                }
11660
11661                if (copyRet >= 0) {
11662                    // Shared libraries that have native libs must be multi-architecture
11663                    if (pkg.isLibrary()) {
11664                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11665                                "Shared library with native libs must be multiarch");
11666                    }
11667                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11668                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11669                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11670                } else if (needsRenderScriptOverride) {
11671                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11672                }
11673            }
11674        } catch (IOException ioe) {
11675            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11676        } finally {
11677            IoUtils.closeQuietly(handle);
11678        }
11679
11680        // Now that we've calculated the ABIs and determined if it's an internal app,
11681        // we will go ahead and populate the nativeLibraryPath.
11682        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11683    }
11684
11685    /**
11686     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11687     * i.e, so that all packages can be run inside a single process if required.
11688     *
11689     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11690     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11691     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11692     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11693     * updating a package that belongs to a shared user.
11694     *
11695     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11696     * adds unnecessary complexity.
11697     */
11698    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11699            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11700        List<String> changedAbiCodePath = null;
11701        String requiredInstructionSet = null;
11702        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11703            requiredInstructionSet = VMRuntime.getInstructionSet(
11704                     scannedPackage.applicationInfo.primaryCpuAbi);
11705        }
11706
11707        PackageSetting requirer = null;
11708        for (PackageSetting ps : packagesForUser) {
11709            // If packagesForUser contains scannedPackage, we skip it. This will happen
11710            // when scannedPackage is an update of an existing package. Without this check,
11711            // we will never be able to change the ABI of any package belonging to a shared
11712            // user, even if it's compatible with other packages.
11713            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11714                if (ps.primaryCpuAbiString == null) {
11715                    continue;
11716                }
11717
11718                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11719                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11720                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11721                    // this but there's not much we can do.
11722                    String errorMessage = "Instruction set mismatch, "
11723                            + ((requirer == null) ? "[caller]" : requirer)
11724                            + " requires " + requiredInstructionSet + " whereas " + ps
11725                            + " requires " + instructionSet;
11726                    Slog.w(TAG, errorMessage);
11727                }
11728
11729                if (requiredInstructionSet == null) {
11730                    requiredInstructionSet = instructionSet;
11731                    requirer = ps;
11732                }
11733            }
11734        }
11735
11736        if (requiredInstructionSet != null) {
11737            String adjustedAbi;
11738            if (requirer != null) {
11739                // requirer != null implies that either scannedPackage was null or that scannedPackage
11740                // did not require an ABI, in which case we have to adjust scannedPackage to match
11741                // the ABI of the set (which is the same as requirer's ABI)
11742                adjustedAbi = requirer.primaryCpuAbiString;
11743                if (scannedPackage != null) {
11744                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11745                }
11746            } else {
11747                // requirer == null implies that we're updating all ABIs in the set to
11748                // match scannedPackage.
11749                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11750            }
11751
11752            for (PackageSetting ps : packagesForUser) {
11753                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11754                    if (ps.primaryCpuAbiString != null) {
11755                        continue;
11756                    }
11757
11758                    ps.primaryCpuAbiString = adjustedAbi;
11759                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11760                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11761                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11762                        if (DEBUG_ABI_SELECTION) {
11763                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11764                                    + " (requirer="
11765                                    + (requirer != null ? requirer.pkg : "null")
11766                                    + ", scannedPackage="
11767                                    + (scannedPackage != null ? scannedPackage : "null")
11768                                    + ")");
11769                        }
11770                        if (changedAbiCodePath == null) {
11771                            changedAbiCodePath = new ArrayList<>();
11772                        }
11773                        changedAbiCodePath.add(ps.codePathString);
11774                    }
11775                }
11776            }
11777        }
11778        return changedAbiCodePath;
11779    }
11780
11781    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11782        synchronized (mPackages) {
11783            mResolverReplaced = true;
11784            // Set up information for custom user intent resolution activity.
11785            mResolveActivity.applicationInfo = pkg.applicationInfo;
11786            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11787            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11788            mResolveActivity.processName = pkg.applicationInfo.packageName;
11789            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11790            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11791                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11792            mResolveActivity.theme = 0;
11793            mResolveActivity.exported = true;
11794            mResolveActivity.enabled = true;
11795            mResolveInfo.activityInfo = mResolveActivity;
11796            mResolveInfo.priority = 0;
11797            mResolveInfo.preferredOrder = 0;
11798            mResolveInfo.match = 0;
11799            mResolveComponentName = mCustomResolverComponentName;
11800            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11801                    mResolveComponentName);
11802        }
11803    }
11804
11805    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11806        if (installerActivity == null) {
11807            if (DEBUG_INSTANT) {
11808                Slog.d(TAG, "Clear ephemeral installer activity");
11809            }
11810            mInstantAppInstallerActivity = null;
11811            return;
11812        }
11813
11814        if (DEBUG_INSTANT) {
11815            Slog.d(TAG, "Set ephemeral installer activity: "
11816                    + installerActivity.getComponentName());
11817        }
11818        // Set up information for ephemeral installer activity
11819        mInstantAppInstallerActivity = installerActivity;
11820        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11821                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11822        mInstantAppInstallerActivity.exported = true;
11823        mInstantAppInstallerActivity.enabled = true;
11824        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11825        mInstantAppInstallerInfo.priority = 1;
11826        mInstantAppInstallerInfo.preferredOrder = 1;
11827        mInstantAppInstallerInfo.isDefault = true;
11828        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11829                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11830    }
11831
11832    private static String calculateBundledApkRoot(final String codePathString) {
11833        final File codePath = new File(codePathString);
11834        final File codeRoot;
11835        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11836            codeRoot = Environment.getRootDirectory();
11837        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11838            codeRoot = Environment.getOemDirectory();
11839        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11840            codeRoot = Environment.getVendorDirectory();
11841        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11842            codeRoot = Environment.getProductDirectory();
11843        } else {
11844            // Unrecognized code path; take its top real segment as the apk root:
11845            // e.g. /something/app/blah.apk => /something
11846            try {
11847                File f = codePath.getCanonicalFile();
11848                File parent = f.getParentFile();    // non-null because codePath is a file
11849                File tmp;
11850                while ((tmp = parent.getParentFile()) != null) {
11851                    f = parent;
11852                    parent = tmp;
11853                }
11854                codeRoot = f;
11855                Slog.w(TAG, "Unrecognized code path "
11856                        + codePath + " - using " + codeRoot);
11857            } catch (IOException e) {
11858                // Can't canonicalize the code path -- shenanigans?
11859                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11860                return Environment.getRootDirectory().getPath();
11861            }
11862        }
11863        return codeRoot.getPath();
11864    }
11865
11866    /**
11867     * Derive and set the location of native libraries for the given package,
11868     * which varies depending on where and how the package was installed.
11869     */
11870    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11871        final ApplicationInfo info = pkg.applicationInfo;
11872        final String codePath = pkg.codePath;
11873        final File codeFile = new File(codePath);
11874        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11875        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11876
11877        info.nativeLibraryRootDir = null;
11878        info.nativeLibraryRootRequiresIsa = false;
11879        info.nativeLibraryDir = null;
11880        info.secondaryNativeLibraryDir = null;
11881
11882        if (isApkFile(codeFile)) {
11883            // Monolithic install
11884            if (bundledApp) {
11885                // If "/system/lib64/apkname" exists, assume that is the per-package
11886                // native library directory to use; otherwise use "/system/lib/apkname".
11887                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11888                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11889                        getPrimaryInstructionSet(info));
11890
11891                // This is a bundled system app so choose the path based on the ABI.
11892                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11893                // is just the default path.
11894                final String apkName = deriveCodePathName(codePath);
11895                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11896                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11897                        apkName).getAbsolutePath();
11898
11899                if (info.secondaryCpuAbi != null) {
11900                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11901                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11902                            secondaryLibDir, apkName).getAbsolutePath();
11903                }
11904            } else if (asecApp) {
11905                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11906                        .getAbsolutePath();
11907            } else {
11908                final String apkName = deriveCodePathName(codePath);
11909                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11910                        .getAbsolutePath();
11911            }
11912
11913            info.nativeLibraryRootRequiresIsa = false;
11914            info.nativeLibraryDir = info.nativeLibraryRootDir;
11915        } else {
11916            // Cluster install
11917            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11918            info.nativeLibraryRootRequiresIsa = true;
11919
11920            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11921                    getPrimaryInstructionSet(info)).getAbsolutePath();
11922
11923            if (info.secondaryCpuAbi != null) {
11924                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11925                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11926            }
11927        }
11928    }
11929
11930    /**
11931     * Calculate the abis and roots for a bundled app. These can uniquely
11932     * be determined from the contents of the system partition, i.e whether
11933     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11934     * of this information, and instead assume that the system was built
11935     * sensibly.
11936     */
11937    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11938                                           PackageSetting pkgSetting) {
11939        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11940
11941        // If "/system/lib64/apkname" exists, assume that is the per-package
11942        // native library directory to use; otherwise use "/system/lib/apkname".
11943        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11944        setBundledAppAbi(pkg, apkRoot, apkName);
11945        // pkgSetting might be null during rescan following uninstall of updates
11946        // to a bundled app, so accommodate that possibility.  The settings in
11947        // that case will be established later from the parsed package.
11948        //
11949        // If the settings aren't null, sync them up with what we've just derived.
11950        // note that apkRoot isn't stored in the package settings.
11951        if (pkgSetting != null) {
11952            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11953            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11954        }
11955    }
11956
11957    /**
11958     * Deduces the ABI of a bundled app and sets the relevant fields on the
11959     * parsed pkg object.
11960     *
11961     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11962     *        under which system libraries are installed.
11963     * @param apkName the name of the installed package.
11964     */
11965    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11966        final File codeFile = new File(pkg.codePath);
11967
11968        final boolean has64BitLibs;
11969        final boolean has32BitLibs;
11970        if (isApkFile(codeFile)) {
11971            // Monolithic install
11972            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11973            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11974        } else {
11975            // Cluster install
11976            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11977            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11978                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11979                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11980                has64BitLibs = (new File(rootDir, isa)).exists();
11981            } else {
11982                has64BitLibs = false;
11983            }
11984            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11985                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11986                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11987                has32BitLibs = (new File(rootDir, isa)).exists();
11988            } else {
11989                has32BitLibs = false;
11990            }
11991        }
11992
11993        if (has64BitLibs && !has32BitLibs) {
11994            // The package has 64 bit libs, but not 32 bit libs. Its primary
11995            // ABI should be 64 bit. We can safely assume here that the bundled
11996            // native libraries correspond to the most preferred ABI in the list.
11997
11998            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11999            pkg.applicationInfo.secondaryCpuAbi = null;
12000        } else if (has32BitLibs && !has64BitLibs) {
12001            // The package has 32 bit libs but not 64 bit libs. Its primary
12002            // ABI should be 32 bit.
12003
12004            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12005            pkg.applicationInfo.secondaryCpuAbi = null;
12006        } else if (has32BitLibs && has64BitLibs) {
12007            // The application has both 64 and 32 bit bundled libraries. We check
12008            // here that the app declares multiArch support, and warn if it doesn't.
12009            //
12010            // We will be lenient here and record both ABIs. The primary will be the
12011            // ABI that's higher on the list, i.e, a device that's configured to prefer
12012            // 64 bit apps will see a 64 bit primary ABI,
12013
12014            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12015                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12016            }
12017
12018            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12019                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12020                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12021            } else {
12022                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12023                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12024            }
12025        } else {
12026            pkg.applicationInfo.primaryCpuAbi = null;
12027            pkg.applicationInfo.secondaryCpuAbi = null;
12028        }
12029    }
12030
12031    private void killApplication(String pkgName, int appId, String reason) {
12032        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12033    }
12034
12035    private void killApplication(String pkgName, int appId, int userId, String reason) {
12036        // Request the ActivityManager to kill the process(only for existing packages)
12037        // so that we do not end up in a confused state while the user is still using the older
12038        // version of the application while the new one gets installed.
12039        final long token = Binder.clearCallingIdentity();
12040        try {
12041            IActivityManager am = ActivityManager.getService();
12042            if (am != null) {
12043                try {
12044                    am.killApplication(pkgName, appId, userId, reason);
12045                } catch (RemoteException e) {
12046                }
12047            }
12048        } finally {
12049            Binder.restoreCallingIdentity(token);
12050        }
12051    }
12052
12053    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12054        // Remove the parent package setting
12055        PackageSetting ps = (PackageSetting) pkg.mExtras;
12056        if (ps != null) {
12057            removePackageLI(ps, chatty);
12058        }
12059        // Remove the child package setting
12060        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12061        for (int i = 0; i < childCount; i++) {
12062            PackageParser.Package childPkg = pkg.childPackages.get(i);
12063            ps = (PackageSetting) childPkg.mExtras;
12064            if (ps != null) {
12065                removePackageLI(ps, chatty);
12066            }
12067        }
12068    }
12069
12070    void removePackageLI(PackageSetting ps, boolean chatty) {
12071        if (DEBUG_INSTALL) {
12072            if (chatty)
12073                Log.d(TAG, "Removing package " + ps.name);
12074        }
12075
12076        // writer
12077        synchronized (mPackages) {
12078            mPackages.remove(ps.name);
12079            final PackageParser.Package pkg = ps.pkg;
12080            if (pkg != null) {
12081                cleanPackageDataStructuresLILPw(pkg, chatty);
12082            }
12083        }
12084    }
12085
12086    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12087        if (DEBUG_INSTALL) {
12088            if (chatty)
12089                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12090        }
12091
12092        // writer
12093        synchronized (mPackages) {
12094            // Remove the parent package
12095            mPackages.remove(pkg.applicationInfo.packageName);
12096            cleanPackageDataStructuresLILPw(pkg, chatty);
12097
12098            // Remove the child packages
12099            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12100            for (int i = 0; i < childCount; i++) {
12101                PackageParser.Package childPkg = pkg.childPackages.get(i);
12102                mPackages.remove(childPkg.applicationInfo.packageName);
12103                cleanPackageDataStructuresLILPw(childPkg, chatty);
12104            }
12105        }
12106    }
12107
12108    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12109        int N = pkg.providers.size();
12110        StringBuilder r = null;
12111        int i;
12112        for (i=0; i<N; i++) {
12113            PackageParser.Provider p = pkg.providers.get(i);
12114            mProviders.removeProvider(p);
12115            if (p.info.authority == null) {
12116
12117                /* There was another ContentProvider with this authority when
12118                 * this app was installed so this authority is null,
12119                 * Ignore it as we don't have to unregister the provider.
12120                 */
12121                continue;
12122            }
12123            String names[] = p.info.authority.split(";");
12124            for (int j = 0; j < names.length; j++) {
12125                if (mProvidersByAuthority.get(names[j]) == p) {
12126                    mProvidersByAuthority.remove(names[j]);
12127                    if (DEBUG_REMOVE) {
12128                        if (chatty)
12129                            Log.d(TAG, "Unregistered content provider: " + names[j]
12130                                    + ", className = " + p.info.name + ", isSyncable = "
12131                                    + p.info.isSyncable);
12132                    }
12133                }
12134            }
12135            if (DEBUG_REMOVE && chatty) {
12136                if (r == null) {
12137                    r = new StringBuilder(256);
12138                } else {
12139                    r.append(' ');
12140                }
12141                r.append(p.info.name);
12142            }
12143        }
12144        if (r != null) {
12145            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12146        }
12147
12148        N = pkg.services.size();
12149        r = null;
12150        for (i=0; i<N; i++) {
12151            PackageParser.Service s = pkg.services.get(i);
12152            mServices.removeService(s);
12153            if (chatty) {
12154                if (r == null) {
12155                    r = new StringBuilder(256);
12156                } else {
12157                    r.append(' ');
12158                }
12159                r.append(s.info.name);
12160            }
12161        }
12162        if (r != null) {
12163            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12164        }
12165
12166        N = pkg.receivers.size();
12167        r = null;
12168        for (i=0; i<N; i++) {
12169            PackageParser.Activity a = pkg.receivers.get(i);
12170            mReceivers.removeActivity(a, "receiver");
12171            if (DEBUG_REMOVE && chatty) {
12172                if (r == null) {
12173                    r = new StringBuilder(256);
12174                } else {
12175                    r.append(' ');
12176                }
12177                r.append(a.info.name);
12178            }
12179        }
12180        if (r != null) {
12181            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12182        }
12183
12184        N = pkg.activities.size();
12185        r = null;
12186        for (i=0; i<N; i++) {
12187            PackageParser.Activity a = pkg.activities.get(i);
12188            mActivities.removeActivity(a, "activity");
12189            if (DEBUG_REMOVE && chatty) {
12190                if (r == null) {
12191                    r = new StringBuilder(256);
12192                } else {
12193                    r.append(' ');
12194                }
12195                r.append(a.info.name);
12196            }
12197        }
12198        if (r != null) {
12199            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12200        }
12201
12202        mPermissionManager.removeAllPermissions(pkg, chatty);
12203
12204        N = pkg.instrumentation.size();
12205        r = null;
12206        for (i=0; i<N; i++) {
12207            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12208            mInstrumentation.remove(a.getComponentName());
12209            if (DEBUG_REMOVE && chatty) {
12210                if (r == null) {
12211                    r = new StringBuilder(256);
12212                } else {
12213                    r.append(' ');
12214                }
12215                r.append(a.info.name);
12216            }
12217        }
12218        if (r != null) {
12219            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12220        }
12221
12222        r = null;
12223        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12224            // Only system apps can hold shared libraries.
12225            if (pkg.libraryNames != null) {
12226                for (i = 0; i < pkg.libraryNames.size(); i++) {
12227                    String name = pkg.libraryNames.get(i);
12228                    if (removeSharedLibraryLPw(name, 0)) {
12229                        if (DEBUG_REMOVE && chatty) {
12230                            if (r == null) {
12231                                r = new StringBuilder(256);
12232                            } else {
12233                                r.append(' ');
12234                            }
12235                            r.append(name);
12236                        }
12237                    }
12238                }
12239            }
12240        }
12241
12242        r = null;
12243
12244        // Any package can hold static shared libraries.
12245        if (pkg.staticSharedLibName != null) {
12246            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12247                if (DEBUG_REMOVE && chatty) {
12248                    if (r == null) {
12249                        r = new StringBuilder(256);
12250                    } else {
12251                        r.append(' ');
12252                    }
12253                    r.append(pkg.staticSharedLibName);
12254                }
12255            }
12256        }
12257
12258        if (r != null) {
12259            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12260        }
12261    }
12262
12263
12264    final class ActivityIntentResolver
12265            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12266        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12267                boolean defaultOnly, int userId) {
12268            if (!sUserManager.exists(userId)) return null;
12269            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12270            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12271        }
12272
12273        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12274                int userId) {
12275            if (!sUserManager.exists(userId)) return null;
12276            mFlags = flags;
12277            return super.queryIntent(intent, resolvedType,
12278                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12279                    userId);
12280        }
12281
12282        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12283                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12284            if (!sUserManager.exists(userId)) return null;
12285            if (packageActivities == null) {
12286                return null;
12287            }
12288            mFlags = flags;
12289            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12290            final int N = packageActivities.size();
12291            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12292                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12293
12294            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12295            for (int i = 0; i < N; ++i) {
12296                intentFilters = packageActivities.get(i).intents;
12297                if (intentFilters != null && intentFilters.size() > 0) {
12298                    PackageParser.ActivityIntentInfo[] array =
12299                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12300                    intentFilters.toArray(array);
12301                    listCut.add(array);
12302                }
12303            }
12304            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12305        }
12306
12307        /**
12308         * Finds a privileged activity that matches the specified activity names.
12309         */
12310        private PackageParser.Activity findMatchingActivity(
12311                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12312            for (PackageParser.Activity sysActivity : activityList) {
12313                if (sysActivity.info.name.equals(activityInfo.name)) {
12314                    return sysActivity;
12315                }
12316                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12317                    return sysActivity;
12318                }
12319                if (sysActivity.info.targetActivity != null) {
12320                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12321                        return sysActivity;
12322                    }
12323                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12324                        return sysActivity;
12325                    }
12326                }
12327            }
12328            return null;
12329        }
12330
12331        public class IterGenerator<E> {
12332            public Iterator<E> generate(ActivityIntentInfo info) {
12333                return null;
12334            }
12335        }
12336
12337        public class ActionIterGenerator extends IterGenerator<String> {
12338            @Override
12339            public Iterator<String> generate(ActivityIntentInfo info) {
12340                return info.actionsIterator();
12341            }
12342        }
12343
12344        public class CategoriesIterGenerator extends IterGenerator<String> {
12345            @Override
12346            public Iterator<String> generate(ActivityIntentInfo info) {
12347                return info.categoriesIterator();
12348            }
12349        }
12350
12351        public class SchemesIterGenerator extends IterGenerator<String> {
12352            @Override
12353            public Iterator<String> generate(ActivityIntentInfo info) {
12354                return info.schemesIterator();
12355            }
12356        }
12357
12358        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12359            @Override
12360            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12361                return info.authoritiesIterator();
12362            }
12363        }
12364
12365        /**
12366         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12367         * MODIFIED. Do not pass in a list that should not be changed.
12368         */
12369        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12370                IterGenerator<T> generator, Iterator<T> searchIterator) {
12371            // loop through the set of actions; every one must be found in the intent filter
12372            while (searchIterator.hasNext()) {
12373                // we must have at least one filter in the list to consider a match
12374                if (intentList.size() == 0) {
12375                    break;
12376                }
12377
12378                final T searchAction = searchIterator.next();
12379
12380                // loop through the set of intent filters
12381                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12382                while (intentIter.hasNext()) {
12383                    final ActivityIntentInfo intentInfo = intentIter.next();
12384                    boolean selectionFound = false;
12385
12386                    // loop through the intent filter's selection criteria; at least one
12387                    // of them must match the searched criteria
12388                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12389                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12390                        final T intentSelection = intentSelectionIter.next();
12391                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12392                            selectionFound = true;
12393                            break;
12394                        }
12395                    }
12396
12397                    // the selection criteria wasn't found in this filter's set; this filter
12398                    // is not a potential match
12399                    if (!selectionFound) {
12400                        intentIter.remove();
12401                    }
12402                }
12403            }
12404        }
12405
12406        private boolean isProtectedAction(ActivityIntentInfo filter) {
12407            final Iterator<String> actionsIter = filter.actionsIterator();
12408            while (actionsIter != null && actionsIter.hasNext()) {
12409                final String filterAction = actionsIter.next();
12410                if (PROTECTED_ACTIONS.contains(filterAction)) {
12411                    return true;
12412                }
12413            }
12414            return false;
12415        }
12416
12417        /**
12418         * Adjusts the priority of the given intent filter according to policy.
12419         * <p>
12420         * <ul>
12421         * <li>The priority for non privileged applications is capped to '0'</li>
12422         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12423         * <li>The priority for unbundled updates to privileged applications is capped to the
12424         *      priority defined on the system partition</li>
12425         * </ul>
12426         * <p>
12427         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12428         * allowed to obtain any priority on any action.
12429         */
12430        private void adjustPriority(
12431                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12432            // nothing to do; priority is fine as-is
12433            if (intent.getPriority() <= 0) {
12434                return;
12435            }
12436
12437            final ActivityInfo activityInfo = intent.activity.info;
12438            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12439
12440            final boolean privilegedApp =
12441                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12442            if (!privilegedApp) {
12443                // non-privileged applications can never define a priority >0
12444                if (DEBUG_FILTERS) {
12445                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12446                            + " package: " + applicationInfo.packageName
12447                            + " activity: " + intent.activity.className
12448                            + " origPrio: " + intent.getPriority());
12449                }
12450                intent.setPriority(0);
12451                return;
12452            }
12453
12454            if (systemActivities == null) {
12455                // the system package is not disabled; we're parsing the system partition
12456                if (isProtectedAction(intent)) {
12457                    if (mDeferProtectedFilters) {
12458                        // We can't deal with these just yet. No component should ever obtain a
12459                        // >0 priority for a protected actions, with ONE exception -- the setup
12460                        // wizard. The setup wizard, however, cannot be known until we're able to
12461                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12462                        // until all intent filters have been processed. Chicken, meet egg.
12463                        // Let the filter temporarily have a high priority and rectify the
12464                        // priorities after all system packages have been scanned.
12465                        mProtectedFilters.add(intent);
12466                        if (DEBUG_FILTERS) {
12467                            Slog.i(TAG, "Protected action; save for later;"
12468                                    + " package: " + applicationInfo.packageName
12469                                    + " activity: " + intent.activity.className
12470                                    + " origPrio: " + intent.getPriority());
12471                        }
12472                        return;
12473                    } else {
12474                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12475                            Slog.i(TAG, "No setup wizard;"
12476                                + " All protected intents capped to priority 0");
12477                        }
12478                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12479                            if (DEBUG_FILTERS) {
12480                                Slog.i(TAG, "Found setup wizard;"
12481                                    + " allow priority " + intent.getPriority() + ";"
12482                                    + " package: " + intent.activity.info.packageName
12483                                    + " activity: " + intent.activity.className
12484                                    + " priority: " + intent.getPriority());
12485                            }
12486                            // setup wizard gets whatever it wants
12487                            return;
12488                        }
12489                        if (DEBUG_FILTERS) {
12490                            Slog.i(TAG, "Protected action; cap priority to 0;"
12491                                    + " package: " + intent.activity.info.packageName
12492                                    + " activity: " + intent.activity.className
12493                                    + " origPrio: " + intent.getPriority());
12494                        }
12495                        intent.setPriority(0);
12496                        return;
12497                    }
12498                }
12499                // privileged apps on the system image get whatever priority they request
12500                return;
12501            }
12502
12503            // privileged app unbundled update ... try to find the same activity
12504            final PackageParser.Activity foundActivity =
12505                    findMatchingActivity(systemActivities, activityInfo);
12506            if (foundActivity == null) {
12507                // this is a new activity; it cannot obtain >0 priority
12508                if (DEBUG_FILTERS) {
12509                    Slog.i(TAG, "New activity; cap priority to 0;"
12510                            + " package: " + applicationInfo.packageName
12511                            + " activity: " + intent.activity.className
12512                            + " origPrio: " + intent.getPriority());
12513                }
12514                intent.setPriority(0);
12515                return;
12516            }
12517
12518            // found activity, now check for filter equivalence
12519
12520            // a shallow copy is enough; we modify the list, not its contents
12521            final List<ActivityIntentInfo> intentListCopy =
12522                    new ArrayList<>(foundActivity.intents);
12523            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12524
12525            // find matching action subsets
12526            final Iterator<String> actionsIterator = intent.actionsIterator();
12527            if (actionsIterator != null) {
12528                getIntentListSubset(
12529                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12530                if (intentListCopy.size() == 0) {
12531                    // no more intents to match; we're not equivalent
12532                    if (DEBUG_FILTERS) {
12533                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12534                                + " package: " + applicationInfo.packageName
12535                                + " activity: " + intent.activity.className
12536                                + " origPrio: " + intent.getPriority());
12537                    }
12538                    intent.setPriority(0);
12539                    return;
12540                }
12541            }
12542
12543            // find matching category subsets
12544            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12545            if (categoriesIterator != null) {
12546                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12547                        categoriesIterator);
12548                if (intentListCopy.size() == 0) {
12549                    // no more intents to match; we're not equivalent
12550                    if (DEBUG_FILTERS) {
12551                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12552                                + " package: " + applicationInfo.packageName
12553                                + " activity: " + intent.activity.className
12554                                + " origPrio: " + intent.getPriority());
12555                    }
12556                    intent.setPriority(0);
12557                    return;
12558                }
12559            }
12560
12561            // find matching schemes subsets
12562            final Iterator<String> schemesIterator = intent.schemesIterator();
12563            if (schemesIterator != null) {
12564                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12565                        schemesIterator);
12566                if (intentListCopy.size() == 0) {
12567                    // no more intents to match; we're not equivalent
12568                    if (DEBUG_FILTERS) {
12569                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12570                                + " package: " + applicationInfo.packageName
12571                                + " activity: " + intent.activity.className
12572                                + " origPrio: " + intent.getPriority());
12573                    }
12574                    intent.setPriority(0);
12575                    return;
12576                }
12577            }
12578
12579            // find matching authorities subsets
12580            final Iterator<IntentFilter.AuthorityEntry>
12581                    authoritiesIterator = intent.authoritiesIterator();
12582            if (authoritiesIterator != null) {
12583                getIntentListSubset(intentListCopy,
12584                        new AuthoritiesIterGenerator(),
12585                        authoritiesIterator);
12586                if (intentListCopy.size() == 0) {
12587                    // no more intents to match; we're not equivalent
12588                    if (DEBUG_FILTERS) {
12589                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12590                                + " package: " + applicationInfo.packageName
12591                                + " activity: " + intent.activity.className
12592                                + " origPrio: " + intent.getPriority());
12593                    }
12594                    intent.setPriority(0);
12595                    return;
12596                }
12597            }
12598
12599            // we found matching filter(s); app gets the max priority of all intents
12600            int cappedPriority = 0;
12601            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12602                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12603            }
12604            if (intent.getPriority() > cappedPriority) {
12605                if (DEBUG_FILTERS) {
12606                    Slog.i(TAG, "Found matching filter(s);"
12607                            + " cap priority to " + cappedPriority + ";"
12608                            + " package: " + applicationInfo.packageName
12609                            + " activity: " + intent.activity.className
12610                            + " origPrio: " + intent.getPriority());
12611                }
12612                intent.setPriority(cappedPriority);
12613                return;
12614            }
12615            // all this for nothing; the requested priority was <= what was on the system
12616        }
12617
12618        public final void addActivity(PackageParser.Activity a, String type) {
12619            mActivities.put(a.getComponentName(), a);
12620            if (DEBUG_SHOW_INFO)
12621                Log.v(
12622                TAG, "  " + type + " " +
12623                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12624            if (DEBUG_SHOW_INFO)
12625                Log.v(TAG, "    Class=" + a.info.name);
12626            final int NI = a.intents.size();
12627            for (int j=0; j<NI; j++) {
12628                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12629                if ("activity".equals(type)) {
12630                    final PackageSetting ps =
12631                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12632                    final List<PackageParser.Activity> systemActivities =
12633                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12634                    adjustPriority(systemActivities, intent);
12635                }
12636                if (DEBUG_SHOW_INFO) {
12637                    Log.v(TAG, "    IntentFilter:");
12638                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12639                }
12640                if (!intent.debugCheck()) {
12641                    Log.w(TAG, "==> For Activity " + a.info.name);
12642                }
12643                addFilter(intent);
12644            }
12645        }
12646
12647        public final void removeActivity(PackageParser.Activity a, String type) {
12648            mActivities.remove(a.getComponentName());
12649            if (DEBUG_SHOW_INFO) {
12650                Log.v(TAG, "  " + type + " "
12651                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12652                                : a.info.name) + ":");
12653                Log.v(TAG, "    Class=" + a.info.name);
12654            }
12655            final int NI = a.intents.size();
12656            for (int j=0; j<NI; j++) {
12657                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12658                if (DEBUG_SHOW_INFO) {
12659                    Log.v(TAG, "    IntentFilter:");
12660                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12661                }
12662                removeFilter(intent);
12663            }
12664        }
12665
12666        @Override
12667        protected boolean allowFilterResult(
12668                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12669            ActivityInfo filterAi = filter.activity.info;
12670            for (int i=dest.size()-1; i>=0; i--) {
12671                ActivityInfo destAi = dest.get(i).activityInfo;
12672                if (destAi.name == filterAi.name
12673                        && destAi.packageName == filterAi.packageName) {
12674                    return false;
12675                }
12676            }
12677            return true;
12678        }
12679
12680        @Override
12681        protected ActivityIntentInfo[] newArray(int size) {
12682            return new ActivityIntentInfo[size];
12683        }
12684
12685        @Override
12686        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12687            if (!sUserManager.exists(userId)) return true;
12688            PackageParser.Package p = filter.activity.owner;
12689            if (p != null) {
12690                PackageSetting ps = (PackageSetting)p.mExtras;
12691                if (ps != null) {
12692                    // System apps are never considered stopped for purposes of
12693                    // filtering, because there may be no way for the user to
12694                    // actually re-launch them.
12695                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12696                            && ps.getStopped(userId);
12697                }
12698            }
12699            return false;
12700        }
12701
12702        @Override
12703        protected boolean isPackageForFilter(String packageName,
12704                PackageParser.ActivityIntentInfo info) {
12705            return packageName.equals(info.activity.owner.packageName);
12706        }
12707
12708        @Override
12709        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12710                int match, int userId) {
12711            if (!sUserManager.exists(userId)) return null;
12712            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12713                return null;
12714            }
12715            final PackageParser.Activity activity = info.activity;
12716            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12717            if (ps == null) {
12718                return null;
12719            }
12720            final PackageUserState userState = ps.readUserState(userId);
12721            ActivityInfo ai =
12722                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12723            if (ai == null) {
12724                return null;
12725            }
12726            final boolean matchExplicitlyVisibleOnly =
12727                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12728            final boolean matchVisibleToInstantApp =
12729                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12730            final boolean componentVisible =
12731                    matchVisibleToInstantApp
12732                    && info.isVisibleToInstantApp()
12733                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12734            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12735            // throw out filters that aren't visible to ephemeral apps
12736            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12737                return null;
12738            }
12739            // throw out instant app filters if we're not explicitly requesting them
12740            if (!matchInstantApp && userState.instantApp) {
12741                return null;
12742            }
12743            // throw out instant app filters if updates are available; will trigger
12744            // instant app resolution
12745            if (userState.instantApp && ps.isUpdateAvailable()) {
12746                return null;
12747            }
12748            final ResolveInfo res = new ResolveInfo();
12749            res.activityInfo = ai;
12750            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12751                res.filter = info;
12752            }
12753            if (info != null) {
12754                res.handleAllWebDataURI = info.handleAllWebDataURI();
12755            }
12756            res.priority = info.getPriority();
12757            res.preferredOrder = activity.owner.mPreferredOrder;
12758            //System.out.println("Result: " + res.activityInfo.className +
12759            //                   " = " + res.priority);
12760            res.match = match;
12761            res.isDefault = info.hasDefault;
12762            res.labelRes = info.labelRes;
12763            res.nonLocalizedLabel = info.nonLocalizedLabel;
12764            if (userNeedsBadging(userId)) {
12765                res.noResourceId = true;
12766            } else {
12767                res.icon = info.icon;
12768            }
12769            res.iconResourceId = info.icon;
12770            res.system = res.activityInfo.applicationInfo.isSystemApp();
12771            res.isInstantAppAvailable = userState.instantApp;
12772            return res;
12773        }
12774
12775        @Override
12776        protected void sortResults(List<ResolveInfo> results) {
12777            Collections.sort(results, mResolvePrioritySorter);
12778        }
12779
12780        @Override
12781        protected void dumpFilter(PrintWriter out, String prefix,
12782                PackageParser.ActivityIntentInfo filter) {
12783            out.print(prefix); out.print(
12784                    Integer.toHexString(System.identityHashCode(filter.activity)));
12785                    out.print(' ');
12786                    filter.activity.printComponentShortName(out);
12787                    out.print(" filter ");
12788                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12789        }
12790
12791        @Override
12792        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12793            return filter.activity;
12794        }
12795
12796        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12797            PackageParser.Activity activity = (PackageParser.Activity)label;
12798            out.print(prefix); out.print(
12799                    Integer.toHexString(System.identityHashCode(activity)));
12800                    out.print(' ');
12801                    activity.printComponentShortName(out);
12802            if (count > 1) {
12803                out.print(" ("); out.print(count); out.print(" filters)");
12804            }
12805            out.println();
12806        }
12807
12808        // Keys are String (activity class name), values are Activity.
12809        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12810                = new ArrayMap<ComponentName, PackageParser.Activity>();
12811        private int mFlags;
12812    }
12813
12814    private final class ServiceIntentResolver
12815            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12816        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12817                boolean defaultOnly, int userId) {
12818            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12819            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12820        }
12821
12822        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12823                int userId) {
12824            if (!sUserManager.exists(userId)) return null;
12825            mFlags = flags;
12826            return super.queryIntent(intent, resolvedType,
12827                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12828                    userId);
12829        }
12830
12831        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12832                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12833            if (!sUserManager.exists(userId)) return null;
12834            if (packageServices == null) {
12835                return null;
12836            }
12837            mFlags = flags;
12838            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12839            final int N = packageServices.size();
12840            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12841                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12842
12843            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12844            for (int i = 0; i < N; ++i) {
12845                intentFilters = packageServices.get(i).intents;
12846                if (intentFilters != null && intentFilters.size() > 0) {
12847                    PackageParser.ServiceIntentInfo[] array =
12848                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12849                    intentFilters.toArray(array);
12850                    listCut.add(array);
12851                }
12852            }
12853            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12854        }
12855
12856        public final void addService(PackageParser.Service s) {
12857            mServices.put(s.getComponentName(), s);
12858            if (DEBUG_SHOW_INFO) {
12859                Log.v(TAG, "  "
12860                        + (s.info.nonLocalizedLabel != null
12861                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12862                Log.v(TAG, "    Class=" + s.info.name);
12863            }
12864            final int NI = s.intents.size();
12865            int j;
12866            for (j=0; j<NI; j++) {
12867                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12868                if (DEBUG_SHOW_INFO) {
12869                    Log.v(TAG, "    IntentFilter:");
12870                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12871                }
12872                if (!intent.debugCheck()) {
12873                    Log.w(TAG, "==> For Service " + s.info.name);
12874                }
12875                addFilter(intent);
12876            }
12877        }
12878
12879        public final void removeService(PackageParser.Service s) {
12880            mServices.remove(s.getComponentName());
12881            if (DEBUG_SHOW_INFO) {
12882                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12883                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12884                Log.v(TAG, "    Class=" + s.info.name);
12885            }
12886            final int NI = s.intents.size();
12887            int j;
12888            for (j=0; j<NI; j++) {
12889                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12890                if (DEBUG_SHOW_INFO) {
12891                    Log.v(TAG, "    IntentFilter:");
12892                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12893                }
12894                removeFilter(intent);
12895            }
12896        }
12897
12898        @Override
12899        protected boolean allowFilterResult(
12900                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12901            ServiceInfo filterSi = filter.service.info;
12902            for (int i=dest.size()-1; i>=0; i--) {
12903                ServiceInfo destAi = dest.get(i).serviceInfo;
12904                if (destAi.name == filterSi.name
12905                        && destAi.packageName == filterSi.packageName) {
12906                    return false;
12907                }
12908            }
12909            return true;
12910        }
12911
12912        @Override
12913        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12914            return new PackageParser.ServiceIntentInfo[size];
12915        }
12916
12917        @Override
12918        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12919            if (!sUserManager.exists(userId)) return true;
12920            PackageParser.Package p = filter.service.owner;
12921            if (p != null) {
12922                PackageSetting ps = (PackageSetting)p.mExtras;
12923                if (ps != null) {
12924                    // System apps are never considered stopped for purposes of
12925                    // filtering, because there may be no way for the user to
12926                    // actually re-launch them.
12927                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12928                            && ps.getStopped(userId);
12929                }
12930            }
12931            return false;
12932        }
12933
12934        @Override
12935        protected boolean isPackageForFilter(String packageName,
12936                PackageParser.ServiceIntentInfo info) {
12937            return packageName.equals(info.service.owner.packageName);
12938        }
12939
12940        @Override
12941        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12942                int match, int userId) {
12943            if (!sUserManager.exists(userId)) return null;
12944            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12945            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12946                return null;
12947            }
12948            final PackageParser.Service service = info.service;
12949            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12950            if (ps == null) {
12951                return null;
12952            }
12953            final PackageUserState userState = ps.readUserState(userId);
12954            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12955                    userState, userId);
12956            if (si == null) {
12957                return null;
12958            }
12959            final boolean matchVisibleToInstantApp =
12960                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12961            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12962            // throw out filters that aren't visible to ephemeral apps
12963            if (matchVisibleToInstantApp
12964                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12965                return null;
12966            }
12967            // throw out ephemeral filters if we're not explicitly requesting them
12968            if (!isInstantApp && userState.instantApp) {
12969                return null;
12970            }
12971            // throw out instant app filters if updates are available; will trigger
12972            // instant app resolution
12973            if (userState.instantApp && ps.isUpdateAvailable()) {
12974                return null;
12975            }
12976            final ResolveInfo res = new ResolveInfo();
12977            res.serviceInfo = si;
12978            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12979                res.filter = filter;
12980            }
12981            res.priority = info.getPriority();
12982            res.preferredOrder = service.owner.mPreferredOrder;
12983            res.match = match;
12984            res.isDefault = info.hasDefault;
12985            res.labelRes = info.labelRes;
12986            res.nonLocalizedLabel = info.nonLocalizedLabel;
12987            res.icon = info.icon;
12988            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12989            return res;
12990        }
12991
12992        @Override
12993        protected void sortResults(List<ResolveInfo> results) {
12994            Collections.sort(results, mResolvePrioritySorter);
12995        }
12996
12997        @Override
12998        protected void dumpFilter(PrintWriter out, String prefix,
12999                PackageParser.ServiceIntentInfo filter) {
13000            out.print(prefix); out.print(
13001                    Integer.toHexString(System.identityHashCode(filter.service)));
13002                    out.print(' ');
13003                    filter.service.printComponentShortName(out);
13004                    out.print(" filter ");
13005                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13006                    if (filter.service.info.permission != null) {
13007                        out.print(" permission "); out.println(filter.service.info.permission);
13008                    } else {
13009                        out.println();
13010                    }
13011        }
13012
13013        @Override
13014        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13015            return filter.service;
13016        }
13017
13018        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13019            PackageParser.Service service = (PackageParser.Service)label;
13020            out.print(prefix); out.print(
13021                    Integer.toHexString(System.identityHashCode(service)));
13022                    out.print(' ');
13023                    service.printComponentShortName(out);
13024            if (count > 1) {
13025                out.print(" ("); out.print(count); out.print(" filters)");
13026            }
13027            out.println();
13028        }
13029
13030//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13031//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13032//            final List<ResolveInfo> retList = Lists.newArrayList();
13033//            while (i.hasNext()) {
13034//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13035//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13036//                    retList.add(resolveInfo);
13037//                }
13038//            }
13039//            return retList;
13040//        }
13041
13042        // Keys are String (activity class name), values are Activity.
13043        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13044                = new ArrayMap<ComponentName, PackageParser.Service>();
13045        private int mFlags;
13046    }
13047
13048    private final class ProviderIntentResolver
13049            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13050        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13051                boolean defaultOnly, int userId) {
13052            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13053            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13054        }
13055
13056        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13057                int userId) {
13058            if (!sUserManager.exists(userId))
13059                return null;
13060            mFlags = flags;
13061            return super.queryIntent(intent, resolvedType,
13062                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13063                    userId);
13064        }
13065
13066        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13067                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13068            if (!sUserManager.exists(userId))
13069                return null;
13070            if (packageProviders == null) {
13071                return null;
13072            }
13073            mFlags = flags;
13074            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13075            final int N = packageProviders.size();
13076            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13077                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13078
13079            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13080            for (int i = 0; i < N; ++i) {
13081                intentFilters = packageProviders.get(i).intents;
13082                if (intentFilters != null && intentFilters.size() > 0) {
13083                    PackageParser.ProviderIntentInfo[] array =
13084                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13085                    intentFilters.toArray(array);
13086                    listCut.add(array);
13087                }
13088            }
13089            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13090        }
13091
13092        public final void addProvider(PackageParser.Provider p) {
13093            if (mProviders.containsKey(p.getComponentName())) {
13094                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13095                return;
13096            }
13097
13098            mProviders.put(p.getComponentName(), p);
13099            if (DEBUG_SHOW_INFO) {
13100                Log.v(TAG, "  "
13101                        + (p.info.nonLocalizedLabel != null
13102                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13103                Log.v(TAG, "    Class=" + p.info.name);
13104            }
13105            final int NI = p.intents.size();
13106            int j;
13107            for (j = 0; j < NI; j++) {
13108                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13109                if (DEBUG_SHOW_INFO) {
13110                    Log.v(TAG, "    IntentFilter:");
13111                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13112                }
13113                if (!intent.debugCheck()) {
13114                    Log.w(TAG, "==> For Provider " + p.info.name);
13115                }
13116                addFilter(intent);
13117            }
13118        }
13119
13120        public final void removeProvider(PackageParser.Provider p) {
13121            mProviders.remove(p.getComponentName());
13122            if (DEBUG_SHOW_INFO) {
13123                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13124                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13125                Log.v(TAG, "    Class=" + p.info.name);
13126            }
13127            final int NI = p.intents.size();
13128            int j;
13129            for (j = 0; j < NI; j++) {
13130                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13131                if (DEBUG_SHOW_INFO) {
13132                    Log.v(TAG, "    IntentFilter:");
13133                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13134                }
13135                removeFilter(intent);
13136            }
13137        }
13138
13139        @Override
13140        protected boolean allowFilterResult(
13141                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13142            ProviderInfo filterPi = filter.provider.info;
13143            for (int i = dest.size() - 1; i >= 0; i--) {
13144                ProviderInfo destPi = dest.get(i).providerInfo;
13145                if (destPi.name == filterPi.name
13146                        && destPi.packageName == filterPi.packageName) {
13147                    return false;
13148                }
13149            }
13150            return true;
13151        }
13152
13153        @Override
13154        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13155            return new PackageParser.ProviderIntentInfo[size];
13156        }
13157
13158        @Override
13159        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13160            if (!sUserManager.exists(userId))
13161                return true;
13162            PackageParser.Package p = filter.provider.owner;
13163            if (p != null) {
13164                PackageSetting ps = (PackageSetting) p.mExtras;
13165                if (ps != null) {
13166                    // System apps are never considered stopped for purposes of
13167                    // filtering, because there may be no way for the user to
13168                    // actually re-launch them.
13169                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13170                            && ps.getStopped(userId);
13171                }
13172            }
13173            return false;
13174        }
13175
13176        @Override
13177        protected boolean isPackageForFilter(String packageName,
13178                PackageParser.ProviderIntentInfo info) {
13179            return packageName.equals(info.provider.owner.packageName);
13180        }
13181
13182        @Override
13183        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13184                int match, int userId) {
13185            if (!sUserManager.exists(userId))
13186                return null;
13187            final PackageParser.ProviderIntentInfo info = filter;
13188            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13189                return null;
13190            }
13191            final PackageParser.Provider provider = info.provider;
13192            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13193            if (ps == null) {
13194                return null;
13195            }
13196            final PackageUserState userState = ps.readUserState(userId);
13197            final boolean matchVisibleToInstantApp =
13198                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13199            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13200            // throw out filters that aren't visible to instant applications
13201            if (matchVisibleToInstantApp
13202                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13203                return null;
13204            }
13205            // throw out instant application filters if we're not explicitly requesting them
13206            if (!isInstantApp && userState.instantApp) {
13207                return null;
13208            }
13209            // throw out instant application filters if updates are available; will trigger
13210            // instant application resolution
13211            if (userState.instantApp && ps.isUpdateAvailable()) {
13212                return null;
13213            }
13214            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13215                    userState, userId);
13216            if (pi == null) {
13217                return null;
13218            }
13219            final ResolveInfo res = new ResolveInfo();
13220            res.providerInfo = pi;
13221            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13222                res.filter = filter;
13223            }
13224            res.priority = info.getPriority();
13225            res.preferredOrder = provider.owner.mPreferredOrder;
13226            res.match = match;
13227            res.isDefault = info.hasDefault;
13228            res.labelRes = info.labelRes;
13229            res.nonLocalizedLabel = info.nonLocalizedLabel;
13230            res.icon = info.icon;
13231            res.system = res.providerInfo.applicationInfo.isSystemApp();
13232            return res;
13233        }
13234
13235        @Override
13236        protected void sortResults(List<ResolveInfo> results) {
13237            Collections.sort(results, mResolvePrioritySorter);
13238        }
13239
13240        @Override
13241        protected void dumpFilter(PrintWriter out, String prefix,
13242                PackageParser.ProviderIntentInfo filter) {
13243            out.print(prefix);
13244            out.print(
13245                    Integer.toHexString(System.identityHashCode(filter.provider)));
13246            out.print(' ');
13247            filter.provider.printComponentShortName(out);
13248            out.print(" filter ");
13249            out.println(Integer.toHexString(System.identityHashCode(filter)));
13250        }
13251
13252        @Override
13253        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13254            return filter.provider;
13255        }
13256
13257        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13258            PackageParser.Provider provider = (PackageParser.Provider)label;
13259            out.print(prefix); out.print(
13260                    Integer.toHexString(System.identityHashCode(provider)));
13261                    out.print(' ');
13262                    provider.printComponentShortName(out);
13263            if (count > 1) {
13264                out.print(" ("); out.print(count); out.print(" filters)");
13265            }
13266            out.println();
13267        }
13268
13269        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13270                = new ArrayMap<ComponentName, PackageParser.Provider>();
13271        private int mFlags;
13272    }
13273
13274    static final class InstantAppIntentResolver
13275            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13276            AuxiliaryResolveInfo.AuxiliaryFilter> {
13277        /**
13278         * The result that has the highest defined order. Ordering applies on a
13279         * per-package basis. Mapping is from package name to Pair of order and
13280         * EphemeralResolveInfo.
13281         * <p>
13282         * NOTE: This is implemented as a field variable for convenience and efficiency.
13283         * By having a field variable, we're able to track filter ordering as soon as
13284         * a non-zero order is defined. Otherwise, multiple loops across the result set
13285         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13286         * this needs to be contained entirely within {@link #filterResults}.
13287         */
13288        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13289
13290        @Override
13291        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13292            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13293        }
13294
13295        @Override
13296        protected boolean isPackageForFilter(String packageName,
13297                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13298            return true;
13299        }
13300
13301        @Override
13302        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13303                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13304            if (!sUserManager.exists(userId)) {
13305                return null;
13306            }
13307            final String packageName = responseObj.resolveInfo.getPackageName();
13308            final Integer order = responseObj.getOrder();
13309            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13310                    mOrderResult.get(packageName);
13311            // ordering is enabled and this item's order isn't high enough
13312            if (lastOrderResult != null && lastOrderResult.first >= order) {
13313                return null;
13314            }
13315            final InstantAppResolveInfo res = responseObj.resolveInfo;
13316            if (order > 0) {
13317                // non-zero order, enable ordering
13318                mOrderResult.put(packageName, new Pair<>(order, res));
13319            }
13320            return responseObj;
13321        }
13322
13323        @Override
13324        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13325            // only do work if ordering is enabled [most of the time it won't be]
13326            if (mOrderResult.size() == 0) {
13327                return;
13328            }
13329            int resultSize = results.size();
13330            for (int i = 0; i < resultSize; i++) {
13331                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13332                final String packageName = info.getPackageName();
13333                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13334                if (savedInfo == null) {
13335                    // package doesn't having ordering
13336                    continue;
13337                }
13338                if (savedInfo.second == info) {
13339                    // circled back to the highest ordered item; remove from order list
13340                    mOrderResult.remove(packageName);
13341                    if (mOrderResult.size() == 0) {
13342                        // no more ordered items
13343                        break;
13344                    }
13345                    continue;
13346                }
13347                // item has a worse order, remove it from the result list
13348                results.remove(i);
13349                resultSize--;
13350                i--;
13351            }
13352        }
13353    }
13354
13355    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13356            new Comparator<ResolveInfo>() {
13357        public int compare(ResolveInfo r1, ResolveInfo r2) {
13358            int v1 = r1.priority;
13359            int v2 = r2.priority;
13360            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13361            if (v1 != v2) {
13362                return (v1 > v2) ? -1 : 1;
13363            }
13364            v1 = r1.preferredOrder;
13365            v2 = r2.preferredOrder;
13366            if (v1 != v2) {
13367                return (v1 > v2) ? -1 : 1;
13368            }
13369            if (r1.isDefault != r2.isDefault) {
13370                return r1.isDefault ? -1 : 1;
13371            }
13372            v1 = r1.match;
13373            v2 = r2.match;
13374            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13375            if (v1 != v2) {
13376                return (v1 > v2) ? -1 : 1;
13377            }
13378            if (r1.system != r2.system) {
13379                return r1.system ? -1 : 1;
13380            }
13381            if (r1.activityInfo != null) {
13382                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13383            }
13384            if (r1.serviceInfo != null) {
13385                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13386            }
13387            if (r1.providerInfo != null) {
13388                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13389            }
13390            return 0;
13391        }
13392    };
13393
13394    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13395            new Comparator<ProviderInfo>() {
13396        public int compare(ProviderInfo p1, ProviderInfo p2) {
13397            final int v1 = p1.initOrder;
13398            final int v2 = p2.initOrder;
13399            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13400        }
13401    };
13402
13403    @Override
13404    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13405            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13406            final int[] userIds, int[] instantUserIds) {
13407        mHandler.post(new Runnable() {
13408            @Override
13409            public void run() {
13410                try {
13411                    final IActivityManager am = ActivityManager.getService();
13412                    if (am == null) return;
13413                    final int[] resolvedUserIds;
13414                    if (userIds == null) {
13415                        resolvedUserIds = am.getRunningUserIds();
13416                    } else {
13417                        resolvedUserIds = userIds;
13418                    }
13419                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13420                            resolvedUserIds, false);
13421                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13422                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13423                                instantUserIds, true);
13424                    }
13425                } catch (RemoteException ex) {
13426                }
13427            }
13428        });
13429    }
13430
13431    @Override
13432    public void notifyPackageAdded(String packageName) {
13433        final PackageListObserver[] observers;
13434        synchronized (mPackages) {
13435            if (mPackageListObservers.size() == 0) {
13436                return;
13437            }
13438            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13439        }
13440        for (int i = observers.length - 1; i >= 0; --i) {
13441            observers[i].onPackageAdded(packageName);
13442        }
13443    }
13444
13445    @Override
13446    public void notifyPackageRemoved(String packageName) {
13447        final PackageListObserver[] observers;
13448        synchronized (mPackages) {
13449            if (mPackageListObservers.size() == 0) {
13450                return;
13451            }
13452            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13453        }
13454        for (int i = observers.length - 1; i >= 0; --i) {
13455            observers[i].onPackageRemoved(packageName);
13456        }
13457    }
13458
13459    /**
13460     * Sends a broadcast for the given action.
13461     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13462     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13463     * the system and applications allowed to see instant applications to receive package
13464     * lifecycle events for instant applications.
13465     */
13466    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13467            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13468            int[] userIds, boolean isInstantApp)
13469                    throws RemoteException {
13470        for (int id : userIds) {
13471            final Intent intent = new Intent(action,
13472                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13473            final String[] requiredPermissions =
13474                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13475            if (extras != null) {
13476                intent.putExtras(extras);
13477            }
13478            if (targetPkg != null) {
13479                intent.setPackage(targetPkg);
13480            }
13481            // Modify the UID when posting to other users
13482            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13483            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13484                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13485                intent.putExtra(Intent.EXTRA_UID, uid);
13486            }
13487            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13488            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13489            if (DEBUG_BROADCASTS) {
13490                RuntimeException here = new RuntimeException("here");
13491                here.fillInStackTrace();
13492                Slog.d(TAG, "Sending to user " + id + ": "
13493                        + intent.toShortString(false, true, false, false)
13494                        + " " + intent.getExtras(), here);
13495            }
13496            am.broadcastIntent(null, intent, null, finishedReceiver,
13497                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13498                    null, finishedReceiver != null, false, id);
13499        }
13500    }
13501
13502    /**
13503     * Check if the external storage media is available. This is true if there
13504     * is a mounted external storage medium or if the external storage is
13505     * emulated.
13506     */
13507    private boolean isExternalMediaAvailable() {
13508        return mMediaMounted || Environment.isExternalStorageEmulated();
13509    }
13510
13511    @Override
13512    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13513        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13514            return null;
13515        }
13516        if (!isExternalMediaAvailable()) {
13517                // If the external storage is no longer mounted at this point,
13518                // the caller may not have been able to delete all of this
13519                // packages files and can not delete any more.  Bail.
13520            return null;
13521        }
13522        synchronized (mPackages) {
13523            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13524            if (lastPackage != null) {
13525                pkgs.remove(lastPackage);
13526            }
13527            if (pkgs.size() > 0) {
13528                return pkgs.get(0);
13529            }
13530        }
13531        return null;
13532    }
13533
13534    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13535        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13536                userId, andCode ? 1 : 0, packageName);
13537        if (mSystemReady) {
13538            msg.sendToTarget();
13539        } else {
13540            if (mPostSystemReadyMessages == null) {
13541                mPostSystemReadyMessages = new ArrayList<>();
13542            }
13543            mPostSystemReadyMessages.add(msg);
13544        }
13545    }
13546
13547    void startCleaningPackages() {
13548        // reader
13549        if (!isExternalMediaAvailable()) {
13550            return;
13551        }
13552        synchronized (mPackages) {
13553            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13554                return;
13555            }
13556        }
13557        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13558        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13559        IActivityManager am = ActivityManager.getService();
13560        if (am != null) {
13561            int dcsUid = -1;
13562            synchronized (mPackages) {
13563                if (!mDefaultContainerWhitelisted) {
13564                    mDefaultContainerWhitelisted = true;
13565                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13566                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13567                }
13568            }
13569            try {
13570                if (dcsUid > 0) {
13571                    am.backgroundWhitelistUid(dcsUid);
13572                }
13573                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13574                        UserHandle.USER_SYSTEM);
13575            } catch (RemoteException e) {
13576            }
13577        }
13578    }
13579
13580    /**
13581     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13582     * it is acting on behalf on an enterprise or the user).
13583     *
13584     * Note that the ordering of the conditionals in this method is important. The checks we perform
13585     * are as follows, in this order:
13586     *
13587     * 1) If the install is being performed by a system app, we can trust the app to have set the
13588     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13589     *    what it is.
13590     * 2) If the install is being performed by a device or profile owner app, the install reason
13591     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13592     *    set the install reason correctly. If the app targets an older SDK version where install
13593     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13594     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13595     * 3) In all other cases, the install is being performed by a regular app that is neither part
13596     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13597     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13598     *    set to enterprise policy and if so, change it to unknown instead.
13599     */
13600    private int fixUpInstallReason(String installerPackageName, int installerUid,
13601            int installReason) {
13602        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13603                == PERMISSION_GRANTED) {
13604            // If the install is being performed by a system app, we trust that app to have set the
13605            // install reason correctly.
13606            return installReason;
13607        }
13608
13609        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13610            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13611        if (dpm != null) {
13612            ComponentName owner = null;
13613            try {
13614                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13615                if (owner == null) {
13616                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13617                }
13618            } catch (RemoteException e) {
13619            }
13620            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13621                // If the install is being performed by a device or profile owner, the install
13622                // reason should be enterprise policy.
13623                return PackageManager.INSTALL_REASON_POLICY;
13624            }
13625        }
13626
13627        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13628            // If the install is being performed by a regular app (i.e. neither system app nor
13629            // device or profile owner), we have no reason to believe that the app is acting on
13630            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13631            // change it to unknown instead.
13632            return PackageManager.INSTALL_REASON_UNKNOWN;
13633        }
13634
13635        // If the install is being performed by a regular app and the install reason was set to any
13636        // value but enterprise policy, leave the install reason unchanged.
13637        return installReason;
13638    }
13639
13640    void installStage(String packageName, File stagedDir,
13641            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13642            String installerPackageName, int installerUid, UserHandle user,
13643            PackageParser.SigningDetails signingDetails) {
13644        if (DEBUG_INSTANT) {
13645            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13646                Slog.d(TAG, "Ephemeral install of " + packageName);
13647            }
13648        }
13649        final VerificationInfo verificationInfo = new VerificationInfo(
13650                sessionParams.originatingUri, sessionParams.referrerUri,
13651                sessionParams.originatingUid, installerUid);
13652
13653        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13654
13655        final Message msg = mHandler.obtainMessage(INIT_COPY);
13656        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13657                sessionParams.installReason);
13658        final InstallParams params = new InstallParams(origin, null, observer,
13659                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13660                verificationInfo, user, sessionParams.abiOverride,
13661                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13662        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13663        msg.obj = params;
13664
13665        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13666                System.identityHashCode(msg.obj));
13667        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13668                System.identityHashCode(msg.obj));
13669
13670        mHandler.sendMessage(msg);
13671    }
13672
13673    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13674            int userId) {
13675        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13676        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13677        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13678        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13679        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13680                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13681
13682        // Send a session commit broadcast
13683        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13684        info.installReason = pkgSetting.getInstallReason(userId);
13685        info.appPackageName = packageName;
13686        sendSessionCommitBroadcast(info, userId);
13687    }
13688
13689    @Override
13690    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13691            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13692        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13693            return;
13694        }
13695        Bundle extras = new Bundle(1);
13696        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13697        final int uid = UserHandle.getUid(
13698                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13699        extras.putInt(Intent.EXTRA_UID, uid);
13700
13701        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13702                packageName, extras, 0, null, null, userIds, instantUserIds);
13703        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13704            mHandler.post(() -> {
13705                        for (int userId : userIds) {
13706                            sendBootCompletedBroadcastToSystemApp(
13707                                    packageName, includeStopped, userId);
13708                        }
13709                    }
13710            );
13711        }
13712    }
13713
13714    /**
13715     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13716     * automatically without needing an explicit launch.
13717     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13718     */
13719    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13720            int userId) {
13721        // If user is not running, the app didn't miss any broadcast
13722        if (!mUserManagerInternal.isUserRunning(userId)) {
13723            return;
13724        }
13725        final IActivityManager am = ActivityManager.getService();
13726        try {
13727            // Deliver LOCKED_BOOT_COMPLETED first
13728            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13729                    .setPackage(packageName);
13730            if (includeStopped) {
13731                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13732            }
13733            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13734            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13735                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13736
13737            // Deliver BOOT_COMPLETED only if user is unlocked
13738            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13739                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13740                if (includeStopped) {
13741                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13742                }
13743                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13744                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13745            }
13746        } catch (RemoteException e) {
13747            throw e.rethrowFromSystemServer();
13748        }
13749    }
13750
13751    @Override
13752    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13753            int userId) {
13754        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13755        PackageSetting pkgSetting;
13756        final int callingUid = Binder.getCallingUid();
13757        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13758                true /* requireFullPermission */, true /* checkShell */,
13759                "setApplicationHiddenSetting for user " + userId);
13760
13761        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13762            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13763            return false;
13764        }
13765
13766        long callingId = Binder.clearCallingIdentity();
13767        try {
13768            boolean sendAdded = false;
13769            boolean sendRemoved = false;
13770            // writer
13771            synchronized (mPackages) {
13772                pkgSetting = mSettings.mPackages.get(packageName);
13773                if (pkgSetting == null) {
13774                    return false;
13775                }
13776                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13777                    return false;
13778                }
13779                // Do not allow "android" is being disabled
13780                if ("android".equals(packageName)) {
13781                    Slog.w(TAG, "Cannot hide package: android");
13782                    return false;
13783                }
13784                // Cannot hide static shared libs as they are considered
13785                // a part of the using app (emulating static linking). Also
13786                // static libs are installed always on internal storage.
13787                PackageParser.Package pkg = mPackages.get(packageName);
13788                if (pkg != null && pkg.staticSharedLibName != null) {
13789                    Slog.w(TAG, "Cannot hide package: " + packageName
13790                            + " providing static shared library: "
13791                            + pkg.staticSharedLibName);
13792                    return false;
13793                }
13794                // Only allow protected packages to hide themselves.
13795                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13796                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13797                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13798                    return false;
13799                }
13800
13801                if (pkgSetting.getHidden(userId) != hidden) {
13802                    pkgSetting.setHidden(hidden, userId);
13803                    mSettings.writePackageRestrictionsLPr(userId);
13804                    if (hidden) {
13805                        sendRemoved = true;
13806                    } else {
13807                        sendAdded = true;
13808                    }
13809                }
13810            }
13811            if (sendAdded) {
13812                sendPackageAddedForUser(packageName, pkgSetting, userId);
13813                return true;
13814            }
13815            if (sendRemoved) {
13816                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13817                        "hiding pkg");
13818                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13819                return true;
13820            }
13821        } finally {
13822            Binder.restoreCallingIdentity(callingId);
13823        }
13824        return false;
13825    }
13826
13827    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13828            int userId) {
13829        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13830        info.removedPackage = packageName;
13831        info.installerPackageName = pkgSetting.installerPackageName;
13832        info.removedUsers = new int[] {userId};
13833        info.broadcastUsers = new int[] {userId};
13834        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13835        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13836    }
13837
13838    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13839        if (pkgList.length > 0) {
13840            Bundle extras = new Bundle(1);
13841            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13842
13843            sendPackageBroadcast(
13844                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13845                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13846                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13847                    new int[] {userId}, null);
13848        }
13849    }
13850
13851    /**
13852     * Returns true if application is not found or there was an error. Otherwise it returns
13853     * the hidden state of the package for the given user.
13854     */
13855    @Override
13856    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13857        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13858        final int callingUid = Binder.getCallingUid();
13859        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13860                true /* requireFullPermission */, false /* checkShell */,
13861                "getApplicationHidden for user " + userId);
13862        PackageSetting ps;
13863        long callingId = Binder.clearCallingIdentity();
13864        try {
13865            // writer
13866            synchronized (mPackages) {
13867                ps = mSettings.mPackages.get(packageName);
13868                if (ps == null) {
13869                    return true;
13870                }
13871                if (filterAppAccessLPr(ps, callingUid, userId)) {
13872                    return true;
13873                }
13874                return ps.getHidden(userId);
13875            }
13876        } finally {
13877            Binder.restoreCallingIdentity(callingId);
13878        }
13879    }
13880
13881    /**
13882     * @hide
13883     */
13884    @Override
13885    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13886            int installReason) {
13887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13888                null);
13889        PackageSetting pkgSetting;
13890        final int callingUid = Binder.getCallingUid();
13891        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13892                true /* requireFullPermission */, true /* checkShell */,
13893                "installExistingPackage for user " + userId);
13894        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13895            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13896        }
13897
13898        long callingId = Binder.clearCallingIdentity();
13899        try {
13900            boolean installed = false;
13901            final boolean instantApp =
13902                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13903            final boolean fullApp =
13904                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13905
13906            // writer
13907            synchronized (mPackages) {
13908                pkgSetting = mSettings.mPackages.get(packageName);
13909                if (pkgSetting == null) {
13910                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13911                }
13912                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13913                    // only allow the existing package to be used if it's installed as a full
13914                    // application for at least one user
13915                    boolean installAllowed = false;
13916                    for (int checkUserId : sUserManager.getUserIds()) {
13917                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13918                        if (installAllowed) {
13919                            break;
13920                        }
13921                    }
13922                    if (!installAllowed) {
13923                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13924                    }
13925                }
13926                if (!pkgSetting.getInstalled(userId)) {
13927                    pkgSetting.setInstalled(true, userId);
13928                    pkgSetting.setHidden(false, userId);
13929                    pkgSetting.setInstallReason(installReason, userId);
13930                    mSettings.writePackageRestrictionsLPr(userId);
13931                    mSettings.writeKernelMappingLPr(pkgSetting);
13932                    installed = true;
13933                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13934                    // upgrade app from instant to full; we don't allow app downgrade
13935                    installed = true;
13936                }
13937                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13938            }
13939
13940            if (installed) {
13941                if (pkgSetting.pkg != null) {
13942                    synchronized (mInstallLock) {
13943                        // We don't need to freeze for a brand new install
13944                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13945                    }
13946                }
13947                sendPackageAddedForUser(packageName, pkgSetting, userId);
13948                synchronized (mPackages) {
13949                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13950                }
13951            }
13952        } finally {
13953            Binder.restoreCallingIdentity(callingId);
13954        }
13955
13956        return PackageManager.INSTALL_SUCCEEDED;
13957    }
13958
13959    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13960            boolean instantApp, boolean fullApp) {
13961        // no state specified; do nothing
13962        if (!instantApp && !fullApp) {
13963            return;
13964        }
13965        if (userId != UserHandle.USER_ALL) {
13966            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13967                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13968            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13969                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13970            }
13971        } else {
13972            for (int currentUserId : sUserManager.getUserIds()) {
13973                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13974                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13975                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13976                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13977                }
13978            }
13979        }
13980    }
13981
13982    boolean isUserRestricted(int userId, String restrictionKey) {
13983        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13984        if (restrictions.getBoolean(restrictionKey, false)) {
13985            Log.w(TAG, "User is restricted: " + restrictionKey);
13986            return true;
13987        }
13988        return false;
13989    }
13990
13991    @Override
13992    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13993            int userId) {
13994        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13995        final int callingUid = Binder.getCallingUid();
13996        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13997                true /* requireFullPermission */, true /* checkShell */,
13998                "setPackagesSuspended for user " + userId);
13999
14000        if (ArrayUtils.isEmpty(packageNames)) {
14001            return packageNames;
14002        }
14003
14004        // List of package names for whom the suspended state has changed.
14005        List<String> changedPackages = new ArrayList<>(packageNames.length);
14006        // List of package names for whom the suspended state is not set as requested in this
14007        // method.
14008        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14009        long callingId = Binder.clearCallingIdentity();
14010        try {
14011            for (int i = 0; i < packageNames.length; i++) {
14012                String packageName = packageNames[i];
14013                boolean changed = false;
14014                final int appId;
14015                synchronized (mPackages) {
14016                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14017                    if (pkgSetting == null
14018                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14019                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14020                                + "\". Skipping suspending/un-suspending.");
14021                        unactionedPackages.add(packageName);
14022                        continue;
14023                    }
14024                    appId = pkgSetting.appId;
14025                    if (pkgSetting.getSuspended(userId) != suspended) {
14026                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14027                            unactionedPackages.add(packageName);
14028                            continue;
14029                        }
14030                        pkgSetting.setSuspended(suspended, userId);
14031                        mSettings.writePackageRestrictionsLPr(userId);
14032                        changed = true;
14033                        changedPackages.add(packageName);
14034                    }
14035                }
14036
14037                if (changed && suspended) {
14038                    killApplication(packageName, UserHandle.getUid(userId, appId),
14039                            "suspending package");
14040                }
14041            }
14042        } finally {
14043            Binder.restoreCallingIdentity(callingId);
14044        }
14045
14046        if (!changedPackages.isEmpty()) {
14047            sendPackagesSuspendedForUser(changedPackages.toArray(
14048                    new String[changedPackages.size()]), userId, suspended);
14049        }
14050
14051        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14052    }
14053
14054    @Override
14055    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14056        final int callingUid = Binder.getCallingUid();
14057        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14058                true /* requireFullPermission */, false /* checkShell */,
14059                "isPackageSuspendedForUser for user " + userId);
14060        synchronized (mPackages) {
14061            final PackageSetting ps = mSettings.mPackages.get(packageName);
14062            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14063                throw new IllegalArgumentException("Unknown target package: " + packageName);
14064            }
14065            return ps.getSuspended(userId);
14066        }
14067    }
14068
14069    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14070        if (isPackageDeviceAdmin(packageName, userId)) {
14071            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14072                    + "\": has an active device admin");
14073            return false;
14074        }
14075
14076        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14077        if (packageName.equals(activeLauncherPackageName)) {
14078            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14079                    + "\": contains the active launcher");
14080            return false;
14081        }
14082
14083        if (packageName.equals(mRequiredInstallerPackage)) {
14084            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14085                    + "\": required for package installation");
14086            return false;
14087        }
14088
14089        if (packageName.equals(mRequiredUninstallerPackage)) {
14090            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14091                    + "\": required for package uninstallation");
14092            return false;
14093        }
14094
14095        if (packageName.equals(mRequiredVerifierPackage)) {
14096            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14097                    + "\": required for package verification");
14098            return false;
14099        }
14100
14101        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14102            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14103                    + "\": is the default dialer");
14104            return false;
14105        }
14106
14107        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14108            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14109                    + "\": protected package");
14110            return false;
14111        }
14112
14113        // Cannot suspend static shared libs as they are considered
14114        // a part of the using app (emulating static linking). Also
14115        // static libs are installed always on internal storage.
14116        PackageParser.Package pkg = mPackages.get(packageName);
14117        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14118            Slog.w(TAG, "Cannot suspend package: " + packageName
14119                    + " providing static shared library: "
14120                    + pkg.staticSharedLibName);
14121            return false;
14122        }
14123
14124        return true;
14125    }
14126
14127    private String getActiveLauncherPackageName(int userId) {
14128        Intent intent = new Intent(Intent.ACTION_MAIN);
14129        intent.addCategory(Intent.CATEGORY_HOME);
14130        ResolveInfo resolveInfo = resolveIntent(
14131                intent,
14132                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14133                PackageManager.MATCH_DEFAULT_ONLY,
14134                userId);
14135
14136        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14137    }
14138
14139    private String getDefaultDialerPackageName(int userId) {
14140        synchronized (mPackages) {
14141            return mSettings.getDefaultDialerPackageNameLPw(userId);
14142        }
14143    }
14144
14145    @Override
14146    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14147        mContext.enforceCallingOrSelfPermission(
14148                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14149                "Only package verification agents can verify applications");
14150
14151        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14152        final PackageVerificationResponse response = new PackageVerificationResponse(
14153                verificationCode, Binder.getCallingUid());
14154        msg.arg1 = id;
14155        msg.obj = response;
14156        mHandler.sendMessage(msg);
14157    }
14158
14159    @Override
14160    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14161            long millisecondsToDelay) {
14162        mContext.enforceCallingOrSelfPermission(
14163                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14164                "Only package verification agents can extend verification timeouts");
14165
14166        final PackageVerificationState state = mPendingVerification.get(id);
14167        final PackageVerificationResponse response = new PackageVerificationResponse(
14168                verificationCodeAtTimeout, Binder.getCallingUid());
14169
14170        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14171            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14172        }
14173        if (millisecondsToDelay < 0) {
14174            millisecondsToDelay = 0;
14175        }
14176        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14177                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14178            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14179        }
14180
14181        if ((state != null) && !state.timeoutExtended()) {
14182            state.extendTimeout();
14183
14184            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14185            msg.arg1 = id;
14186            msg.obj = response;
14187            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14188        }
14189    }
14190
14191    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14192            int verificationCode, UserHandle user) {
14193        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14194        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14195        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14196        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14197        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14198
14199        mContext.sendBroadcastAsUser(intent, user,
14200                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14201    }
14202
14203    private ComponentName matchComponentForVerifier(String packageName,
14204            List<ResolveInfo> receivers) {
14205        ActivityInfo targetReceiver = null;
14206
14207        final int NR = receivers.size();
14208        for (int i = 0; i < NR; i++) {
14209            final ResolveInfo info = receivers.get(i);
14210            if (info.activityInfo == null) {
14211                continue;
14212            }
14213
14214            if (packageName.equals(info.activityInfo.packageName)) {
14215                targetReceiver = info.activityInfo;
14216                break;
14217            }
14218        }
14219
14220        if (targetReceiver == null) {
14221            return null;
14222        }
14223
14224        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14225    }
14226
14227    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14228            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14229        if (pkgInfo.verifiers.length == 0) {
14230            return null;
14231        }
14232
14233        final int N = pkgInfo.verifiers.length;
14234        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14235        for (int i = 0; i < N; i++) {
14236            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14237
14238            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14239                    receivers);
14240            if (comp == null) {
14241                continue;
14242            }
14243
14244            final int verifierUid = getUidForVerifier(verifierInfo);
14245            if (verifierUid == -1) {
14246                continue;
14247            }
14248
14249            if (DEBUG_VERIFY) {
14250                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14251                        + " with the correct signature");
14252            }
14253            sufficientVerifiers.add(comp);
14254            verificationState.addSufficientVerifier(verifierUid);
14255        }
14256
14257        return sufficientVerifiers;
14258    }
14259
14260    private int getUidForVerifier(VerifierInfo verifierInfo) {
14261        synchronized (mPackages) {
14262            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14263            if (pkg == null) {
14264                return -1;
14265            } else if (pkg.mSigningDetails.signatures.length != 1) {
14266                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14267                        + " has more than one signature; ignoring");
14268                return -1;
14269            }
14270
14271            /*
14272             * If the public key of the package's signature does not match
14273             * our expected public key, then this is a different package and
14274             * we should skip.
14275             */
14276
14277            final byte[] expectedPublicKey;
14278            try {
14279                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14280                final PublicKey publicKey = verifierSig.getPublicKey();
14281                expectedPublicKey = publicKey.getEncoded();
14282            } catch (CertificateException e) {
14283                return -1;
14284            }
14285
14286            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14287
14288            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14289                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14290                        + " does not have the expected public key; ignoring");
14291                return -1;
14292            }
14293
14294            return pkg.applicationInfo.uid;
14295        }
14296    }
14297
14298    @Override
14299    public void finishPackageInstall(int token, boolean didLaunch) {
14300        enforceSystemOrRoot("Only the system is allowed to finish installs");
14301
14302        if (DEBUG_INSTALL) {
14303            Slog.v(TAG, "BM finishing package install for " + token);
14304        }
14305        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14306
14307        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14308        mHandler.sendMessage(msg);
14309    }
14310
14311    /**
14312     * Get the verification agent timeout.  Used for both the APK verifier and the
14313     * intent filter verifier.
14314     *
14315     * @return verification timeout in milliseconds
14316     */
14317    private long getVerificationTimeout() {
14318        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14319                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14320                DEFAULT_VERIFICATION_TIMEOUT);
14321    }
14322
14323    /**
14324     * Get the default verification agent response code.
14325     *
14326     * @return default verification response code
14327     */
14328    private int getDefaultVerificationResponse(UserHandle user) {
14329        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14330            return PackageManager.VERIFICATION_REJECT;
14331        }
14332        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14333                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14334                DEFAULT_VERIFICATION_RESPONSE);
14335    }
14336
14337    /**
14338     * Check whether or not package verification has been enabled.
14339     *
14340     * @return true if verification should be performed
14341     */
14342    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14343        if (!DEFAULT_VERIFY_ENABLE) {
14344            return false;
14345        }
14346
14347        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14348
14349        // Check if installing from ADB
14350        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14351            // Do not run verification in a test harness environment
14352            if (ActivityManager.isRunningInTestHarness()) {
14353                return false;
14354            }
14355            if (ensureVerifyAppsEnabled) {
14356                return true;
14357            }
14358            // Check if the developer does not want package verification for ADB installs
14359            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14360                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14361                return false;
14362            }
14363        } else {
14364            // only when not installed from ADB, skip verification for instant apps when
14365            // the installer and verifier are the same.
14366            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14367                if (mInstantAppInstallerActivity != null
14368                        && mInstantAppInstallerActivity.packageName.equals(
14369                                mRequiredVerifierPackage)) {
14370                    try {
14371                        mContext.getSystemService(AppOpsManager.class)
14372                                .checkPackage(installerUid, mRequiredVerifierPackage);
14373                        if (DEBUG_VERIFY) {
14374                            Slog.i(TAG, "disable verification for instant app");
14375                        }
14376                        return false;
14377                    } catch (SecurityException ignore) { }
14378                }
14379            }
14380        }
14381
14382        if (ensureVerifyAppsEnabled) {
14383            return true;
14384        }
14385
14386        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14387                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14388    }
14389
14390    @Override
14391    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14392            throws RemoteException {
14393        mContext.enforceCallingOrSelfPermission(
14394                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14395                "Only intentfilter verification agents can verify applications");
14396
14397        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14398        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14399                Binder.getCallingUid(), verificationCode, failedDomains);
14400        msg.arg1 = id;
14401        msg.obj = response;
14402        mHandler.sendMessage(msg);
14403    }
14404
14405    @Override
14406    public int getIntentVerificationStatus(String packageName, int userId) {
14407        final int callingUid = Binder.getCallingUid();
14408        if (UserHandle.getUserId(callingUid) != userId) {
14409            mContext.enforceCallingOrSelfPermission(
14410                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14411                    "getIntentVerificationStatus" + userId);
14412        }
14413        if (getInstantAppPackageName(callingUid) != null) {
14414            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14415        }
14416        synchronized (mPackages) {
14417            final PackageSetting ps = mSettings.mPackages.get(packageName);
14418            if (ps == null
14419                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14420                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14421            }
14422            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14423        }
14424    }
14425
14426    @Override
14427    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14428        mContext.enforceCallingOrSelfPermission(
14429                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14430
14431        boolean result = false;
14432        synchronized (mPackages) {
14433            final PackageSetting ps = mSettings.mPackages.get(packageName);
14434            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14435                return false;
14436            }
14437            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14438        }
14439        if (result) {
14440            scheduleWritePackageRestrictionsLocked(userId);
14441        }
14442        return result;
14443    }
14444
14445    @Override
14446    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14447            String packageName) {
14448        final int callingUid = Binder.getCallingUid();
14449        if (getInstantAppPackageName(callingUid) != null) {
14450            return ParceledListSlice.emptyList();
14451        }
14452        synchronized (mPackages) {
14453            final PackageSetting ps = mSettings.mPackages.get(packageName);
14454            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14455                return ParceledListSlice.emptyList();
14456            }
14457            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14458        }
14459    }
14460
14461    @Override
14462    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14463        if (TextUtils.isEmpty(packageName)) {
14464            return ParceledListSlice.emptyList();
14465        }
14466        final int callingUid = Binder.getCallingUid();
14467        final int callingUserId = UserHandle.getUserId(callingUid);
14468        synchronized (mPackages) {
14469            PackageParser.Package pkg = mPackages.get(packageName);
14470            if (pkg == null || pkg.activities == null) {
14471                return ParceledListSlice.emptyList();
14472            }
14473            if (pkg.mExtras == null) {
14474                return ParceledListSlice.emptyList();
14475            }
14476            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14477            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14478                return ParceledListSlice.emptyList();
14479            }
14480            final int count = pkg.activities.size();
14481            ArrayList<IntentFilter> result = new ArrayList<>();
14482            for (int n=0; n<count; n++) {
14483                PackageParser.Activity activity = pkg.activities.get(n);
14484                if (activity.intents != null && activity.intents.size() > 0) {
14485                    result.addAll(activity.intents);
14486                }
14487            }
14488            return new ParceledListSlice<>(result);
14489        }
14490    }
14491
14492    @Override
14493    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14494        mContext.enforceCallingOrSelfPermission(
14495                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14496        if (UserHandle.getCallingUserId() != userId) {
14497            mContext.enforceCallingOrSelfPermission(
14498                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14499        }
14500
14501        synchronized (mPackages) {
14502            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14503            if (packageName != null) {
14504                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14505                        packageName, userId);
14506            }
14507            return result;
14508        }
14509    }
14510
14511    @Override
14512    public String getDefaultBrowserPackageName(int userId) {
14513        if (UserHandle.getCallingUserId() != userId) {
14514            mContext.enforceCallingOrSelfPermission(
14515                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14516        }
14517        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14518            return null;
14519        }
14520        synchronized (mPackages) {
14521            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14522        }
14523    }
14524
14525    /**
14526     * Get the "allow unknown sources" setting.
14527     *
14528     * @return the current "allow unknown sources" setting
14529     */
14530    private int getUnknownSourcesSettings() {
14531        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14532                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14533                -1);
14534    }
14535
14536    @Override
14537    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14538        final int callingUid = Binder.getCallingUid();
14539        if (getInstantAppPackageName(callingUid) != null) {
14540            return;
14541        }
14542        // writer
14543        synchronized (mPackages) {
14544            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14545            if (targetPackageSetting == null
14546                    || filterAppAccessLPr(
14547                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14548                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14549            }
14550
14551            PackageSetting installerPackageSetting;
14552            if (installerPackageName != null) {
14553                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14554                if (installerPackageSetting == null) {
14555                    throw new IllegalArgumentException("Unknown installer package: "
14556                            + installerPackageName);
14557                }
14558            } else {
14559                installerPackageSetting = null;
14560            }
14561
14562            Signature[] callerSignature;
14563            Object obj = mSettings.getUserIdLPr(callingUid);
14564            if (obj != null) {
14565                if (obj instanceof SharedUserSetting) {
14566                    callerSignature =
14567                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14568                } else if (obj instanceof PackageSetting) {
14569                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14570                } else {
14571                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14572                }
14573            } else {
14574                throw new SecurityException("Unknown calling UID: " + callingUid);
14575            }
14576
14577            // Verify: can't set installerPackageName to a package that is
14578            // not signed with the same cert as the caller.
14579            if (installerPackageSetting != null) {
14580                if (compareSignatures(callerSignature,
14581                        installerPackageSetting.signatures.mSigningDetails.signatures)
14582                        != PackageManager.SIGNATURE_MATCH) {
14583                    throw new SecurityException(
14584                            "Caller does not have same cert as new installer package "
14585                            + installerPackageName);
14586                }
14587            }
14588
14589            // Verify: if target already has an installer package, it must
14590            // be signed with the same cert as the caller.
14591            if (targetPackageSetting.installerPackageName != null) {
14592                PackageSetting setting = mSettings.mPackages.get(
14593                        targetPackageSetting.installerPackageName);
14594                // If the currently set package isn't valid, then it's always
14595                // okay to change it.
14596                if (setting != null) {
14597                    if (compareSignatures(callerSignature,
14598                            setting.signatures.mSigningDetails.signatures)
14599                            != PackageManager.SIGNATURE_MATCH) {
14600                        throw new SecurityException(
14601                                "Caller does not have same cert as old installer package "
14602                                + targetPackageSetting.installerPackageName);
14603                    }
14604                }
14605            }
14606
14607            // Okay!
14608            targetPackageSetting.installerPackageName = installerPackageName;
14609            if (installerPackageName != null) {
14610                mSettings.mInstallerPackages.add(installerPackageName);
14611            }
14612            scheduleWriteSettingsLocked();
14613        }
14614    }
14615
14616    @Override
14617    public void setApplicationCategoryHint(String packageName, int categoryHint,
14618            String callerPackageName) {
14619        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14620            throw new SecurityException("Instant applications don't have access to this method");
14621        }
14622        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14623                callerPackageName);
14624        synchronized (mPackages) {
14625            PackageSetting ps = mSettings.mPackages.get(packageName);
14626            if (ps == null) {
14627                throw new IllegalArgumentException("Unknown target package " + packageName);
14628            }
14629            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14630                throw new IllegalArgumentException("Unknown target package " + packageName);
14631            }
14632            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14633                throw new IllegalArgumentException("Calling package " + callerPackageName
14634                        + " is not installer for " + packageName);
14635            }
14636
14637            if (ps.categoryHint != categoryHint) {
14638                ps.categoryHint = categoryHint;
14639                scheduleWriteSettingsLocked();
14640            }
14641        }
14642    }
14643
14644    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14645        // Queue up an async operation since the package installation may take a little while.
14646        mHandler.post(new Runnable() {
14647            public void run() {
14648                mHandler.removeCallbacks(this);
14649                 // Result object to be returned
14650                PackageInstalledInfo res = new PackageInstalledInfo();
14651                res.setReturnCode(currentStatus);
14652                res.uid = -1;
14653                res.pkg = null;
14654                res.removedInfo = null;
14655                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14656                    args.doPreInstall(res.returnCode);
14657                    synchronized (mInstallLock) {
14658                        installPackageTracedLI(args, res);
14659                    }
14660                    args.doPostInstall(res.returnCode, res.uid);
14661                }
14662
14663                // A restore should be performed at this point if (a) the install
14664                // succeeded, (b) the operation is not an update, and (c) the new
14665                // package has not opted out of backup participation.
14666                final boolean update = res.removedInfo != null
14667                        && res.removedInfo.removedPackage != null;
14668                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14669                boolean doRestore = !update
14670                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14671
14672                // Set up the post-install work request bookkeeping.  This will be used
14673                // and cleaned up by the post-install event handling regardless of whether
14674                // there's a restore pass performed.  Token values are >= 1.
14675                int token;
14676                if (mNextInstallToken < 0) mNextInstallToken = 1;
14677                token = mNextInstallToken++;
14678
14679                PostInstallData data = new PostInstallData(args, res);
14680                mRunningInstalls.put(token, data);
14681                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14682
14683                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14684                    // Pass responsibility to the Backup Manager.  It will perform a
14685                    // restore if appropriate, then pass responsibility back to the
14686                    // Package Manager to run the post-install observer callbacks
14687                    // and broadcasts.
14688                    IBackupManager bm = IBackupManager.Stub.asInterface(
14689                            ServiceManager.getService(Context.BACKUP_SERVICE));
14690                    if (bm != null) {
14691                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14692                                + " to BM for possible restore");
14693                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14694                        try {
14695                            // TODO: http://b/22388012
14696                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14697                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14698                            } else {
14699                                doRestore = false;
14700                            }
14701                        } catch (RemoteException e) {
14702                            // can't happen; the backup manager is local
14703                        } catch (Exception e) {
14704                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14705                            doRestore = false;
14706                        }
14707                    } else {
14708                        Slog.e(TAG, "Backup Manager not found!");
14709                        doRestore = false;
14710                    }
14711                }
14712
14713                if (!doRestore) {
14714                    // No restore possible, or the Backup Manager was mysteriously not
14715                    // available -- just fire the post-install work request directly.
14716                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14717
14718                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14719
14720                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14721                    mHandler.sendMessage(msg);
14722                }
14723            }
14724        });
14725    }
14726
14727    /**
14728     * Callback from PackageSettings whenever an app is first transitioned out of the
14729     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14730     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14731     * here whether the app is the target of an ongoing install, and only send the
14732     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14733     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14734     * handling.
14735     */
14736    void notifyFirstLaunch(final String packageName, final String installerPackage,
14737            final int userId) {
14738        // Serialize this with the rest of the install-process message chain.  In the
14739        // restore-at-install case, this Runnable will necessarily run before the
14740        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14741        // are coherent.  In the non-restore case, the app has already completed install
14742        // and been launched through some other means, so it is not in a problematic
14743        // state for observers to see the FIRST_LAUNCH signal.
14744        mHandler.post(new Runnable() {
14745            @Override
14746            public void run() {
14747                for (int i = 0; i < mRunningInstalls.size(); i++) {
14748                    final PostInstallData data = mRunningInstalls.valueAt(i);
14749                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14750                        continue;
14751                    }
14752                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14753                        // right package; but is it for the right user?
14754                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14755                            if (userId == data.res.newUsers[uIndex]) {
14756                                if (DEBUG_BACKUP) {
14757                                    Slog.i(TAG, "Package " + packageName
14758                                            + " being restored so deferring FIRST_LAUNCH");
14759                                }
14760                                return;
14761                            }
14762                        }
14763                    }
14764                }
14765                // didn't find it, so not being restored
14766                if (DEBUG_BACKUP) {
14767                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14768                }
14769                final boolean isInstantApp = isInstantApp(packageName, userId);
14770                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14771                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14772                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14773            }
14774        });
14775    }
14776
14777    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14778            int[] userIds, int[] instantUserIds) {
14779        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14780                installerPkg, null, userIds, instantUserIds);
14781    }
14782
14783    private abstract class HandlerParams {
14784        private static final int MAX_RETRIES = 4;
14785
14786        /**
14787         * Number of times startCopy() has been attempted and had a non-fatal
14788         * error.
14789         */
14790        private int mRetries = 0;
14791
14792        /** User handle for the user requesting the information or installation. */
14793        private final UserHandle mUser;
14794        String traceMethod;
14795        int traceCookie;
14796
14797        HandlerParams(UserHandle user) {
14798            mUser = user;
14799        }
14800
14801        UserHandle getUser() {
14802            return mUser;
14803        }
14804
14805        HandlerParams setTraceMethod(String traceMethod) {
14806            this.traceMethod = traceMethod;
14807            return this;
14808        }
14809
14810        HandlerParams setTraceCookie(int traceCookie) {
14811            this.traceCookie = traceCookie;
14812            return this;
14813        }
14814
14815        final boolean startCopy() {
14816            boolean res;
14817            try {
14818                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14819
14820                if (++mRetries > MAX_RETRIES) {
14821                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14822                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14823                    handleServiceError();
14824                    return false;
14825                } else {
14826                    handleStartCopy();
14827                    res = true;
14828                }
14829            } catch (RemoteException e) {
14830                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14831                mHandler.sendEmptyMessage(MCS_RECONNECT);
14832                res = false;
14833            }
14834            handleReturnCode();
14835            return res;
14836        }
14837
14838        final void serviceError() {
14839            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14840            handleServiceError();
14841            handleReturnCode();
14842        }
14843
14844        abstract void handleStartCopy() throws RemoteException;
14845        abstract void handleServiceError();
14846        abstract void handleReturnCode();
14847    }
14848
14849    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14850        for (File path : paths) {
14851            try {
14852                mcs.clearDirectory(path.getAbsolutePath());
14853            } catch (RemoteException e) {
14854            }
14855        }
14856    }
14857
14858    static class OriginInfo {
14859        /**
14860         * Location where install is coming from, before it has been
14861         * copied/renamed into place. This could be a single monolithic APK
14862         * file, or a cluster directory. This location may be untrusted.
14863         */
14864        final File file;
14865
14866        /**
14867         * Flag indicating that {@link #file} or {@link #cid} has already been
14868         * staged, meaning downstream users don't need to defensively copy the
14869         * contents.
14870         */
14871        final boolean staged;
14872
14873        /**
14874         * Flag indicating that {@link #file} or {@link #cid} is an already
14875         * installed app that is being moved.
14876         */
14877        final boolean existing;
14878
14879        final String resolvedPath;
14880        final File resolvedFile;
14881
14882        static OriginInfo fromNothing() {
14883            return new OriginInfo(null, false, false);
14884        }
14885
14886        static OriginInfo fromUntrustedFile(File file) {
14887            return new OriginInfo(file, false, false);
14888        }
14889
14890        static OriginInfo fromExistingFile(File file) {
14891            return new OriginInfo(file, false, true);
14892        }
14893
14894        static OriginInfo fromStagedFile(File file) {
14895            return new OriginInfo(file, true, false);
14896        }
14897
14898        private OriginInfo(File file, boolean staged, boolean existing) {
14899            this.file = file;
14900            this.staged = staged;
14901            this.existing = existing;
14902
14903            if (file != null) {
14904                resolvedPath = file.getAbsolutePath();
14905                resolvedFile = file;
14906            } else {
14907                resolvedPath = null;
14908                resolvedFile = null;
14909            }
14910        }
14911    }
14912
14913    static class MoveInfo {
14914        final int moveId;
14915        final String fromUuid;
14916        final String toUuid;
14917        final String packageName;
14918        final String dataAppName;
14919        final int appId;
14920        final String seinfo;
14921        final int targetSdkVersion;
14922
14923        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14924                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14925            this.moveId = moveId;
14926            this.fromUuid = fromUuid;
14927            this.toUuid = toUuid;
14928            this.packageName = packageName;
14929            this.dataAppName = dataAppName;
14930            this.appId = appId;
14931            this.seinfo = seinfo;
14932            this.targetSdkVersion = targetSdkVersion;
14933        }
14934    }
14935
14936    static class VerificationInfo {
14937        /** A constant used to indicate that a uid value is not present. */
14938        public static final int NO_UID = -1;
14939
14940        /** URI referencing where the package was downloaded from. */
14941        final Uri originatingUri;
14942
14943        /** HTTP referrer URI associated with the originatingURI. */
14944        final Uri referrer;
14945
14946        /** UID of the application that the install request originated from. */
14947        final int originatingUid;
14948
14949        /** UID of application requesting the install */
14950        final int installerUid;
14951
14952        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14953            this.originatingUri = originatingUri;
14954            this.referrer = referrer;
14955            this.originatingUid = originatingUid;
14956            this.installerUid = installerUid;
14957        }
14958    }
14959
14960    class InstallParams extends HandlerParams {
14961        final OriginInfo origin;
14962        final MoveInfo move;
14963        final IPackageInstallObserver2 observer;
14964        int installFlags;
14965        final String installerPackageName;
14966        final String volumeUuid;
14967        private InstallArgs mArgs;
14968        private int mRet;
14969        final String packageAbiOverride;
14970        final String[] grantedRuntimePermissions;
14971        final VerificationInfo verificationInfo;
14972        final PackageParser.SigningDetails signingDetails;
14973        final int installReason;
14974
14975        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14976                int installFlags, String installerPackageName, String volumeUuid,
14977                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14978                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14979            super(user);
14980            this.origin = origin;
14981            this.move = move;
14982            this.observer = observer;
14983            this.installFlags = installFlags;
14984            this.installerPackageName = installerPackageName;
14985            this.volumeUuid = volumeUuid;
14986            this.verificationInfo = verificationInfo;
14987            this.packageAbiOverride = packageAbiOverride;
14988            this.grantedRuntimePermissions = grantedPermissions;
14989            this.signingDetails = signingDetails;
14990            this.installReason = installReason;
14991        }
14992
14993        @Override
14994        public String toString() {
14995            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14996                    + " file=" + origin.file + "}";
14997        }
14998
14999        private int installLocationPolicy(PackageInfoLite pkgLite) {
15000            String packageName = pkgLite.packageName;
15001            int installLocation = pkgLite.installLocation;
15002            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15003            // reader
15004            synchronized (mPackages) {
15005                // Currently installed package which the new package is attempting to replace or
15006                // null if no such package is installed.
15007                PackageParser.Package installedPkg = mPackages.get(packageName);
15008                // Package which currently owns the data which the new package will own if installed.
15009                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15010                // will be null whereas dataOwnerPkg will contain information about the package
15011                // which was uninstalled while keeping its data.
15012                PackageParser.Package dataOwnerPkg = installedPkg;
15013                if (dataOwnerPkg  == null) {
15014                    PackageSetting ps = mSettings.mPackages.get(packageName);
15015                    if (ps != null) {
15016                        dataOwnerPkg = ps.pkg;
15017                    }
15018                }
15019
15020                if (dataOwnerPkg != null) {
15021                    // If installed, the package will get access to data left on the device by its
15022                    // predecessor. As a security measure, this is permited only if this is not a
15023                    // version downgrade or if the predecessor package is marked as debuggable and
15024                    // a downgrade is explicitly requested.
15025                    //
15026                    // On debuggable platform builds, downgrades are permitted even for
15027                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15028                    // not offer security guarantees and thus it's OK to disable some security
15029                    // mechanisms to make debugging/testing easier on those builds. However, even on
15030                    // debuggable builds downgrades of packages are permitted only if requested via
15031                    // installFlags. This is because we aim to keep the behavior of debuggable
15032                    // platform builds as close as possible to the behavior of non-debuggable
15033                    // platform builds.
15034                    final boolean downgradeRequested =
15035                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15036                    final boolean packageDebuggable =
15037                                (dataOwnerPkg.applicationInfo.flags
15038                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15039                    final boolean downgradePermitted =
15040                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15041                    if (!downgradePermitted) {
15042                        try {
15043                            checkDowngrade(dataOwnerPkg, pkgLite);
15044                        } catch (PackageManagerException e) {
15045                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15046                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15047                        }
15048                    }
15049                }
15050
15051                if (installedPkg != null) {
15052                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15053                        // Check for updated system application.
15054                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15055                            if (onSd) {
15056                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15057                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15058                            }
15059                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15060                        } else {
15061                            if (onSd) {
15062                                // Install flag overrides everything.
15063                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15064                            }
15065                            // If current upgrade specifies particular preference
15066                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15067                                // Application explicitly specified internal.
15068                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15069                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15070                                // App explictly prefers external. Let policy decide
15071                            } else {
15072                                // Prefer previous location
15073                                if (isExternal(installedPkg)) {
15074                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15075                                }
15076                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15077                            }
15078                        }
15079                    } else {
15080                        // Invalid install. Return error code
15081                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15082                    }
15083                }
15084            }
15085            // All the special cases have been taken care of.
15086            // Return result based on recommended install location.
15087            if (onSd) {
15088                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15089            }
15090            return pkgLite.recommendedInstallLocation;
15091        }
15092
15093        /*
15094         * Invoke remote method to get package information and install
15095         * location values. Override install location based on default
15096         * policy if needed and then create install arguments based
15097         * on the install location.
15098         */
15099        public void handleStartCopy() throws RemoteException {
15100            int ret = PackageManager.INSTALL_SUCCEEDED;
15101
15102            // If we're already staged, we've firmly committed to an install location
15103            if (origin.staged) {
15104                if (origin.file != null) {
15105                    installFlags |= PackageManager.INSTALL_INTERNAL;
15106                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15107                } else {
15108                    throw new IllegalStateException("Invalid stage location");
15109                }
15110            }
15111
15112            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15113            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15114            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15115            PackageInfoLite pkgLite = null;
15116
15117            if (onInt && onSd) {
15118                // Check if both bits are set.
15119                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15120                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15121            } else if (onSd && ephemeral) {
15122                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15123                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15124            } else {
15125                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15126                        packageAbiOverride);
15127
15128                if (DEBUG_INSTANT && ephemeral) {
15129                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15130                }
15131
15132                /*
15133                 * If we have too little free space, try to free cache
15134                 * before giving up.
15135                 */
15136                if (!origin.staged && pkgLite.recommendedInstallLocation
15137                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15138                    // TODO: focus freeing disk space on the target device
15139                    final StorageManager storage = StorageManager.from(mContext);
15140                    final long lowThreshold = storage.getStorageLowBytes(
15141                            Environment.getDataDirectory());
15142
15143                    final long sizeBytes = mContainerService.calculateInstalledSize(
15144                            origin.resolvedPath, packageAbiOverride);
15145
15146                    try {
15147                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15148                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15149                                installFlags, packageAbiOverride);
15150                    } catch (InstallerException e) {
15151                        Slog.w(TAG, "Failed to free cache", e);
15152                    }
15153
15154                    /*
15155                     * The cache free must have deleted the file we
15156                     * downloaded to install.
15157                     *
15158                     * TODO: fix the "freeCache" call to not delete
15159                     *       the file we care about.
15160                     */
15161                    if (pkgLite.recommendedInstallLocation
15162                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15163                        pkgLite.recommendedInstallLocation
15164                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15165                    }
15166                }
15167            }
15168
15169            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15170                int loc = pkgLite.recommendedInstallLocation;
15171                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15172                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15173                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15174                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15175                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15176                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15177                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15178                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15179                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15180                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15181                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15182                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15183                } else {
15184                    // Override with defaults if needed.
15185                    loc = installLocationPolicy(pkgLite);
15186                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15187                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15188                    } else if (!onSd && !onInt) {
15189                        // Override install location with flags
15190                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15191                            // Set the flag to install on external media.
15192                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15193                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15194                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15195                            if (DEBUG_INSTANT) {
15196                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15197                            }
15198                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15199                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15200                                    |PackageManager.INSTALL_INTERNAL);
15201                        } else {
15202                            // Make sure the flag for installing on external
15203                            // media is unset
15204                            installFlags |= PackageManager.INSTALL_INTERNAL;
15205                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15206                        }
15207                    }
15208                }
15209            }
15210
15211            final InstallArgs args = createInstallArgs(this);
15212            mArgs = args;
15213
15214            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15215                // TODO: http://b/22976637
15216                // Apps installed for "all" users use the device owner to verify the app
15217                UserHandle verifierUser = getUser();
15218                if (verifierUser == UserHandle.ALL) {
15219                    verifierUser = UserHandle.SYSTEM;
15220                }
15221
15222                /*
15223                 * Determine if we have any installed package verifiers. If we
15224                 * do, then we'll defer to them to verify the packages.
15225                 */
15226                final int requiredUid = mRequiredVerifierPackage == null ? -1
15227                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15228                                verifierUser.getIdentifier());
15229                final int installerUid =
15230                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15231                if (!origin.existing && requiredUid != -1
15232                        && isVerificationEnabled(
15233                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15234                    final Intent verification = new Intent(
15235                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15236                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15237                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15238                            PACKAGE_MIME_TYPE);
15239                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15240
15241                    // Query all live verifiers based on current user state
15242                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15243                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15244                            false /*allowDynamicSplits*/);
15245
15246                    if (DEBUG_VERIFY) {
15247                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15248                                + verification.toString() + " with " + pkgLite.verifiers.length
15249                                + " optional verifiers");
15250                    }
15251
15252                    final int verificationId = mPendingVerificationToken++;
15253
15254                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15255
15256                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15257                            installerPackageName);
15258
15259                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15260                            installFlags);
15261
15262                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15263                            pkgLite.packageName);
15264
15265                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15266                            pkgLite.versionCode);
15267
15268                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15269                            pkgLite.getLongVersionCode());
15270
15271                    if (verificationInfo != null) {
15272                        if (verificationInfo.originatingUri != null) {
15273                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15274                                    verificationInfo.originatingUri);
15275                        }
15276                        if (verificationInfo.referrer != null) {
15277                            verification.putExtra(Intent.EXTRA_REFERRER,
15278                                    verificationInfo.referrer);
15279                        }
15280                        if (verificationInfo.originatingUid >= 0) {
15281                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15282                                    verificationInfo.originatingUid);
15283                        }
15284                        if (verificationInfo.installerUid >= 0) {
15285                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15286                                    verificationInfo.installerUid);
15287                        }
15288                    }
15289
15290                    final PackageVerificationState verificationState = new PackageVerificationState(
15291                            requiredUid, args);
15292
15293                    mPendingVerification.append(verificationId, verificationState);
15294
15295                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15296                            receivers, verificationState);
15297
15298                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15299                    final long idleDuration = getVerificationTimeout();
15300
15301                    /*
15302                     * If any sufficient verifiers were listed in the package
15303                     * manifest, attempt to ask them.
15304                     */
15305                    if (sufficientVerifiers != null) {
15306                        final int N = sufficientVerifiers.size();
15307                        if (N == 0) {
15308                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15309                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15310                        } else {
15311                            for (int i = 0; i < N; i++) {
15312                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15313                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15314                                        verifierComponent.getPackageName(), idleDuration,
15315                                        verifierUser.getIdentifier(), false, "package verifier");
15316
15317                                final Intent sufficientIntent = new Intent(verification);
15318                                sufficientIntent.setComponent(verifierComponent);
15319                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15320                            }
15321                        }
15322                    }
15323
15324                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15325                            mRequiredVerifierPackage, receivers);
15326                    if (ret == PackageManager.INSTALL_SUCCEEDED
15327                            && mRequiredVerifierPackage != null) {
15328                        Trace.asyncTraceBegin(
15329                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15330                        /*
15331                         * Send the intent to the required verification agent,
15332                         * but only start the verification timeout after the
15333                         * target BroadcastReceivers have run.
15334                         */
15335                        verification.setComponent(requiredVerifierComponent);
15336                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15337                                mRequiredVerifierPackage, idleDuration,
15338                                verifierUser.getIdentifier(), false, "package verifier");
15339                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15340                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15341                                new BroadcastReceiver() {
15342                                    @Override
15343                                    public void onReceive(Context context, Intent intent) {
15344                                        final Message msg = mHandler
15345                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15346                                        msg.arg1 = verificationId;
15347                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15348                                    }
15349                                }, null, 0, null, null);
15350
15351                        /*
15352                         * We don't want the copy to proceed until verification
15353                         * succeeds, so null out this field.
15354                         */
15355                        mArgs = null;
15356                    }
15357                } else {
15358                    /*
15359                     * No package verification is enabled, so immediately start
15360                     * the remote call to initiate copy using temporary file.
15361                     */
15362                    ret = args.copyApk(mContainerService, true);
15363                }
15364            }
15365
15366            mRet = ret;
15367        }
15368
15369        @Override
15370        void handleReturnCode() {
15371            // If mArgs is null, then MCS couldn't be reached. When it
15372            // reconnects, it will try again to install. At that point, this
15373            // will succeed.
15374            if (mArgs != null) {
15375                processPendingInstall(mArgs, mRet);
15376            }
15377        }
15378
15379        @Override
15380        void handleServiceError() {
15381            mArgs = createInstallArgs(this);
15382            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15383        }
15384    }
15385
15386    private InstallArgs createInstallArgs(InstallParams params) {
15387        if (params.move != null) {
15388            return new MoveInstallArgs(params);
15389        } else {
15390            return new FileInstallArgs(params);
15391        }
15392    }
15393
15394    /**
15395     * Create args that describe an existing installed package. Typically used
15396     * when cleaning up old installs, or used as a move source.
15397     */
15398    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15399            String resourcePath, String[] instructionSets) {
15400        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15401    }
15402
15403    static abstract class InstallArgs {
15404        /** @see InstallParams#origin */
15405        final OriginInfo origin;
15406        /** @see InstallParams#move */
15407        final MoveInfo move;
15408
15409        final IPackageInstallObserver2 observer;
15410        // Always refers to PackageManager flags only
15411        final int installFlags;
15412        final String installerPackageName;
15413        final String volumeUuid;
15414        final UserHandle user;
15415        final String abiOverride;
15416        final String[] installGrantPermissions;
15417        /** If non-null, drop an async trace when the install completes */
15418        final String traceMethod;
15419        final int traceCookie;
15420        final PackageParser.SigningDetails signingDetails;
15421        final int installReason;
15422
15423        // The list of instruction sets supported by this app. This is currently
15424        // only used during the rmdex() phase to clean up resources. We can get rid of this
15425        // if we move dex files under the common app path.
15426        /* nullable */ String[] instructionSets;
15427
15428        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15429                int installFlags, String installerPackageName, String volumeUuid,
15430                UserHandle user, String[] instructionSets,
15431                String abiOverride, String[] installGrantPermissions,
15432                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15433                int installReason) {
15434            this.origin = origin;
15435            this.move = move;
15436            this.installFlags = installFlags;
15437            this.observer = observer;
15438            this.installerPackageName = installerPackageName;
15439            this.volumeUuid = volumeUuid;
15440            this.user = user;
15441            this.instructionSets = instructionSets;
15442            this.abiOverride = abiOverride;
15443            this.installGrantPermissions = installGrantPermissions;
15444            this.traceMethod = traceMethod;
15445            this.traceCookie = traceCookie;
15446            this.signingDetails = signingDetails;
15447            this.installReason = installReason;
15448        }
15449
15450        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15451        abstract int doPreInstall(int status);
15452
15453        /**
15454         * Rename package into final resting place. All paths on the given
15455         * scanned package should be updated to reflect the rename.
15456         */
15457        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15458        abstract int doPostInstall(int status, int uid);
15459
15460        /** @see PackageSettingBase#codePathString */
15461        abstract String getCodePath();
15462        /** @see PackageSettingBase#resourcePathString */
15463        abstract String getResourcePath();
15464
15465        // Need installer lock especially for dex file removal.
15466        abstract void cleanUpResourcesLI();
15467        abstract boolean doPostDeleteLI(boolean delete);
15468
15469        /**
15470         * Called before the source arguments are copied. This is used mostly
15471         * for MoveParams when it needs to read the source file to put it in the
15472         * destination.
15473         */
15474        int doPreCopy() {
15475            return PackageManager.INSTALL_SUCCEEDED;
15476        }
15477
15478        /**
15479         * Called after the source arguments are copied. This is used mostly for
15480         * MoveParams when it needs to read the source file to put it in the
15481         * destination.
15482         */
15483        int doPostCopy(int uid) {
15484            return PackageManager.INSTALL_SUCCEEDED;
15485        }
15486
15487        protected boolean isFwdLocked() {
15488            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15489        }
15490
15491        protected boolean isExternalAsec() {
15492            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15493        }
15494
15495        protected boolean isEphemeral() {
15496            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15497        }
15498
15499        UserHandle getUser() {
15500            return user;
15501        }
15502    }
15503
15504    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15505        if (!allCodePaths.isEmpty()) {
15506            if (instructionSets == null) {
15507                throw new IllegalStateException("instructionSet == null");
15508            }
15509            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15510            for (String codePath : allCodePaths) {
15511                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15512                    try {
15513                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15514                    } catch (InstallerException ignored) {
15515                    }
15516                }
15517            }
15518        }
15519    }
15520
15521    /**
15522     * Logic to handle installation of non-ASEC applications, including copying
15523     * and renaming logic.
15524     */
15525    class FileInstallArgs extends InstallArgs {
15526        private File codeFile;
15527        private File resourceFile;
15528
15529        // Example topology:
15530        // /data/app/com.example/base.apk
15531        // /data/app/com.example/split_foo.apk
15532        // /data/app/com.example/lib/arm/libfoo.so
15533        // /data/app/com.example/lib/arm64/libfoo.so
15534        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15535
15536        /** New install */
15537        FileInstallArgs(InstallParams params) {
15538            super(params.origin, params.move, params.observer, params.installFlags,
15539                    params.installerPackageName, params.volumeUuid,
15540                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15541                    params.grantedRuntimePermissions,
15542                    params.traceMethod, params.traceCookie, params.signingDetails,
15543                    params.installReason);
15544            if (isFwdLocked()) {
15545                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15546            }
15547        }
15548
15549        /** Existing install */
15550        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15551            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15552                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15553                    PackageManager.INSTALL_REASON_UNKNOWN);
15554            this.codeFile = (codePath != null) ? new File(codePath) : null;
15555            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15556        }
15557
15558        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15559            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15560            try {
15561                return doCopyApk(imcs, temp);
15562            } finally {
15563                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15564            }
15565        }
15566
15567        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15568            if (origin.staged) {
15569                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15570                codeFile = origin.file;
15571                resourceFile = origin.file;
15572                return PackageManager.INSTALL_SUCCEEDED;
15573            }
15574
15575            try {
15576                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15577                final File tempDir =
15578                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15579                codeFile = tempDir;
15580                resourceFile = tempDir;
15581            } catch (IOException e) {
15582                Slog.w(TAG, "Failed to create copy file: " + e);
15583                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15584            }
15585
15586            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15587                @Override
15588                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15589                    if (!FileUtils.isValidExtFilename(name)) {
15590                        throw new IllegalArgumentException("Invalid filename: " + name);
15591                    }
15592                    try {
15593                        final File file = new File(codeFile, name);
15594                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15595                                O_RDWR | O_CREAT, 0644);
15596                        Os.chmod(file.getAbsolutePath(), 0644);
15597                        return new ParcelFileDescriptor(fd);
15598                    } catch (ErrnoException e) {
15599                        throw new RemoteException("Failed to open: " + e.getMessage());
15600                    }
15601                }
15602            };
15603
15604            int ret = PackageManager.INSTALL_SUCCEEDED;
15605            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15606            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15607                Slog.e(TAG, "Failed to copy package");
15608                return ret;
15609            }
15610
15611            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15612            NativeLibraryHelper.Handle handle = null;
15613            try {
15614                handle = NativeLibraryHelper.Handle.create(codeFile);
15615                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15616                        abiOverride);
15617            } catch (IOException e) {
15618                Slog.e(TAG, "Copying native libraries failed", e);
15619                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15620            } finally {
15621                IoUtils.closeQuietly(handle);
15622            }
15623
15624            return ret;
15625        }
15626
15627        int doPreInstall(int status) {
15628            if (status != PackageManager.INSTALL_SUCCEEDED) {
15629                cleanUp();
15630            }
15631            return status;
15632        }
15633
15634        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15635            if (status != PackageManager.INSTALL_SUCCEEDED) {
15636                cleanUp();
15637                return false;
15638            }
15639
15640            final File targetDir = codeFile.getParentFile();
15641            final File beforeCodeFile = codeFile;
15642            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15643
15644            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15645            try {
15646                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15647            } catch (ErrnoException e) {
15648                Slog.w(TAG, "Failed to rename", e);
15649                return false;
15650            }
15651
15652            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15653                Slog.w(TAG, "Failed to restorecon");
15654                return false;
15655            }
15656
15657            // Reflect the rename internally
15658            codeFile = afterCodeFile;
15659            resourceFile = afterCodeFile;
15660
15661            // Reflect the rename in scanned details
15662            try {
15663                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15664            } catch (IOException e) {
15665                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15666                return false;
15667            }
15668            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15669                    afterCodeFile, pkg.baseCodePath));
15670            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15671                    afterCodeFile, pkg.splitCodePaths));
15672
15673            // Reflect the rename in app info
15674            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15675            pkg.setApplicationInfoCodePath(pkg.codePath);
15676            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15677            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15678            pkg.setApplicationInfoResourcePath(pkg.codePath);
15679            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15680            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15681
15682            return true;
15683        }
15684
15685        int doPostInstall(int status, int uid) {
15686            if (status != PackageManager.INSTALL_SUCCEEDED) {
15687                cleanUp();
15688            }
15689            return status;
15690        }
15691
15692        @Override
15693        String getCodePath() {
15694            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15695        }
15696
15697        @Override
15698        String getResourcePath() {
15699            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15700        }
15701
15702        private boolean cleanUp() {
15703            if (codeFile == null || !codeFile.exists()) {
15704                return false;
15705            }
15706
15707            removeCodePathLI(codeFile);
15708
15709            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15710                resourceFile.delete();
15711            }
15712
15713            return true;
15714        }
15715
15716        void cleanUpResourcesLI() {
15717            // Try enumerating all code paths before deleting
15718            List<String> allCodePaths = Collections.EMPTY_LIST;
15719            if (codeFile != null && codeFile.exists()) {
15720                try {
15721                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15722                    allCodePaths = pkg.getAllCodePaths();
15723                } catch (PackageParserException e) {
15724                    // Ignored; we tried our best
15725                }
15726            }
15727
15728            cleanUp();
15729            removeDexFiles(allCodePaths, instructionSets);
15730        }
15731
15732        boolean doPostDeleteLI(boolean delete) {
15733            // XXX err, shouldn't we respect the delete flag?
15734            cleanUpResourcesLI();
15735            return true;
15736        }
15737    }
15738
15739    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15740            PackageManagerException {
15741        if (copyRet < 0) {
15742            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15743                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15744                throw new PackageManagerException(copyRet, message);
15745            }
15746        }
15747    }
15748
15749    /**
15750     * Extract the StorageManagerService "container ID" from the full code path of an
15751     * .apk.
15752     */
15753    static String cidFromCodePath(String fullCodePath) {
15754        int eidx = fullCodePath.lastIndexOf("/");
15755        String subStr1 = fullCodePath.substring(0, eidx);
15756        int sidx = subStr1.lastIndexOf("/");
15757        return subStr1.substring(sidx+1, eidx);
15758    }
15759
15760    /**
15761     * Logic to handle movement of existing installed applications.
15762     */
15763    class MoveInstallArgs extends InstallArgs {
15764        private File codeFile;
15765        private File resourceFile;
15766
15767        /** New install */
15768        MoveInstallArgs(InstallParams params) {
15769            super(params.origin, params.move, params.observer, params.installFlags,
15770                    params.installerPackageName, params.volumeUuid,
15771                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15772                    params.grantedRuntimePermissions,
15773                    params.traceMethod, params.traceCookie, params.signingDetails,
15774                    params.installReason);
15775        }
15776
15777        int copyApk(IMediaContainerService imcs, boolean temp) {
15778            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15779                    + move.fromUuid + " to " + move.toUuid);
15780            synchronized (mInstaller) {
15781                try {
15782                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15783                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15784                } catch (InstallerException e) {
15785                    Slog.w(TAG, "Failed to move app", e);
15786                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15787                }
15788            }
15789
15790            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15791            resourceFile = codeFile;
15792            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15793
15794            return PackageManager.INSTALL_SUCCEEDED;
15795        }
15796
15797        int doPreInstall(int status) {
15798            if (status != PackageManager.INSTALL_SUCCEEDED) {
15799                cleanUp(move.toUuid);
15800            }
15801            return status;
15802        }
15803
15804        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15805            if (status != PackageManager.INSTALL_SUCCEEDED) {
15806                cleanUp(move.toUuid);
15807                return false;
15808            }
15809
15810            // Reflect the move in app info
15811            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15812            pkg.setApplicationInfoCodePath(pkg.codePath);
15813            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15814            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15815            pkg.setApplicationInfoResourcePath(pkg.codePath);
15816            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15817            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15818
15819            return true;
15820        }
15821
15822        int doPostInstall(int status, int uid) {
15823            if (status == PackageManager.INSTALL_SUCCEEDED) {
15824                cleanUp(move.fromUuid);
15825            } else {
15826                cleanUp(move.toUuid);
15827            }
15828            return status;
15829        }
15830
15831        @Override
15832        String getCodePath() {
15833            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15834        }
15835
15836        @Override
15837        String getResourcePath() {
15838            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15839        }
15840
15841        private boolean cleanUp(String volumeUuid) {
15842            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15843                    move.dataAppName);
15844            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15845            final int[] userIds = sUserManager.getUserIds();
15846            synchronized (mInstallLock) {
15847                // Clean up both app data and code
15848                // All package moves are frozen until finished
15849                for (int userId : userIds) {
15850                    try {
15851                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15852                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15853                    } catch (InstallerException e) {
15854                        Slog.w(TAG, String.valueOf(e));
15855                    }
15856                }
15857                removeCodePathLI(codeFile);
15858            }
15859            return true;
15860        }
15861
15862        void cleanUpResourcesLI() {
15863            throw new UnsupportedOperationException();
15864        }
15865
15866        boolean doPostDeleteLI(boolean delete) {
15867            throw new UnsupportedOperationException();
15868        }
15869    }
15870
15871    static String getAsecPackageName(String packageCid) {
15872        int idx = packageCid.lastIndexOf("-");
15873        if (idx == -1) {
15874            return packageCid;
15875        }
15876        return packageCid.substring(0, idx);
15877    }
15878
15879    // Utility method used to create code paths based on package name and available index.
15880    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15881        String idxStr = "";
15882        int idx = 1;
15883        // Fall back to default value of idx=1 if prefix is not
15884        // part of oldCodePath
15885        if (oldCodePath != null) {
15886            String subStr = oldCodePath;
15887            // Drop the suffix right away
15888            if (suffix != null && subStr.endsWith(suffix)) {
15889                subStr = subStr.substring(0, subStr.length() - suffix.length());
15890            }
15891            // If oldCodePath already contains prefix find out the
15892            // ending index to either increment or decrement.
15893            int sidx = subStr.lastIndexOf(prefix);
15894            if (sidx != -1) {
15895                subStr = subStr.substring(sidx + prefix.length());
15896                if (subStr != null) {
15897                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15898                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15899                    }
15900                    try {
15901                        idx = Integer.parseInt(subStr);
15902                        if (idx <= 1) {
15903                            idx++;
15904                        } else {
15905                            idx--;
15906                        }
15907                    } catch(NumberFormatException e) {
15908                    }
15909                }
15910            }
15911        }
15912        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15913        return prefix + idxStr;
15914    }
15915
15916    private File getNextCodePath(File targetDir, String packageName) {
15917        File result;
15918        SecureRandom random = new SecureRandom();
15919        byte[] bytes = new byte[16];
15920        do {
15921            random.nextBytes(bytes);
15922            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15923            result = new File(targetDir, packageName + "-" + suffix);
15924        } while (result.exists());
15925        return result;
15926    }
15927
15928    // Utility method that returns the relative package path with respect
15929    // to the installation directory. Like say for /data/data/com.test-1.apk
15930    // string com.test-1 is returned.
15931    static String deriveCodePathName(String codePath) {
15932        if (codePath == null) {
15933            return null;
15934        }
15935        final File codeFile = new File(codePath);
15936        final String name = codeFile.getName();
15937        if (codeFile.isDirectory()) {
15938            return name;
15939        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15940            final int lastDot = name.lastIndexOf('.');
15941            return name.substring(0, lastDot);
15942        } else {
15943            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15944            return null;
15945        }
15946    }
15947
15948    static class PackageInstalledInfo {
15949        String name;
15950        int uid;
15951        // The set of users that originally had this package installed.
15952        int[] origUsers;
15953        // The set of users that now have this package installed.
15954        int[] newUsers;
15955        PackageParser.Package pkg;
15956        int returnCode;
15957        String returnMsg;
15958        String installerPackageName;
15959        PackageRemovedInfo removedInfo;
15960        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15961
15962        public void setError(int code, String msg) {
15963            setReturnCode(code);
15964            setReturnMessage(msg);
15965            Slog.w(TAG, msg);
15966        }
15967
15968        public void setError(String msg, PackageParserException e) {
15969            setReturnCode(e.error);
15970            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15971            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15972            for (int i = 0; i < childCount; i++) {
15973                addedChildPackages.valueAt(i).setError(msg, e);
15974            }
15975            Slog.w(TAG, msg, e);
15976        }
15977
15978        public void setError(String msg, PackageManagerException e) {
15979            returnCode = e.error;
15980            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15981            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15982            for (int i = 0; i < childCount; i++) {
15983                addedChildPackages.valueAt(i).setError(msg, e);
15984            }
15985            Slog.w(TAG, msg, e);
15986        }
15987
15988        public void setReturnCode(int returnCode) {
15989            this.returnCode = returnCode;
15990            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15991            for (int i = 0; i < childCount; i++) {
15992                addedChildPackages.valueAt(i).returnCode = returnCode;
15993            }
15994        }
15995
15996        private void setReturnMessage(String returnMsg) {
15997            this.returnMsg = returnMsg;
15998            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15999            for (int i = 0; i < childCount; i++) {
16000                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16001            }
16002        }
16003
16004        // In some error cases we want to convey more info back to the observer
16005        String origPackage;
16006        String origPermission;
16007    }
16008
16009    /*
16010     * Install a non-existing package.
16011     */
16012    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16013            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16014            String volumeUuid, PackageInstalledInfo res, int installReason) {
16015        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16016
16017        // Remember this for later, in case we need to rollback this install
16018        String pkgName = pkg.packageName;
16019
16020        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16021
16022        synchronized(mPackages) {
16023            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16024            if (renamedPackage != null) {
16025                // A package with the same name is already installed, though
16026                // it has been renamed to an older name.  The package we
16027                // are trying to install should be installed as an update to
16028                // the existing one, but that has not been requested, so bail.
16029                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16030                        + " without first uninstalling package running as "
16031                        + renamedPackage);
16032                return;
16033            }
16034            if (mPackages.containsKey(pkgName)) {
16035                // Don't allow installation over an existing package with the same name.
16036                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16037                        + " without first uninstalling.");
16038                return;
16039            }
16040        }
16041
16042        try {
16043            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16044                    System.currentTimeMillis(), user);
16045
16046            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16047
16048            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16049                prepareAppDataAfterInstallLIF(newPackage);
16050
16051            } else {
16052                // Remove package from internal structures, but keep around any
16053                // data that might have already existed
16054                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16055                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16056            }
16057        } catch (PackageManagerException e) {
16058            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16059        }
16060
16061        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16062    }
16063
16064    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16065        try (DigestInputStream digestStream =
16066                new DigestInputStream(new FileInputStream(file), digest)) {
16067            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16068        }
16069    }
16070
16071    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16072            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16073            PackageInstalledInfo res, int installReason) {
16074        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16075
16076        final PackageParser.Package oldPackage;
16077        final PackageSetting ps;
16078        final String pkgName = pkg.packageName;
16079        final int[] allUsers;
16080        final int[] installedUsers;
16081
16082        synchronized(mPackages) {
16083            oldPackage = mPackages.get(pkgName);
16084            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16085
16086            // don't allow upgrade to target a release SDK from a pre-release SDK
16087            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16088                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16089            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16090                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16091            if (oldTargetsPreRelease
16092                    && !newTargetsPreRelease
16093                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16094                Slog.w(TAG, "Can't install package targeting released sdk");
16095                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16096                return;
16097            }
16098
16099            ps = mSettings.mPackages.get(pkgName);
16100
16101            // verify signatures are valid
16102            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16103            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16104                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16105                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16106                            "New package not signed by keys specified by upgrade-keysets: "
16107                                    + pkgName);
16108                    return;
16109                }
16110            } else {
16111
16112                // default to original signature matching
16113                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16114                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16115                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16116                            "New package has a different signature: " + pkgName);
16117                    return;
16118                }
16119            }
16120
16121            // don't allow a system upgrade unless the upgrade hash matches
16122            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16123                byte[] digestBytes = null;
16124                try {
16125                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16126                    updateDigest(digest, new File(pkg.baseCodePath));
16127                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16128                        for (String path : pkg.splitCodePaths) {
16129                            updateDigest(digest, new File(path));
16130                        }
16131                    }
16132                    digestBytes = digest.digest();
16133                } catch (NoSuchAlgorithmException | IOException e) {
16134                    res.setError(INSTALL_FAILED_INVALID_APK,
16135                            "Could not compute hash: " + pkgName);
16136                    return;
16137                }
16138                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16139                    res.setError(INSTALL_FAILED_INVALID_APK,
16140                            "New package fails restrict-update check: " + pkgName);
16141                    return;
16142                }
16143                // retain upgrade restriction
16144                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16145            }
16146
16147            // Check for shared user id changes
16148            String invalidPackageName =
16149                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16150            if (invalidPackageName != null) {
16151                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16152                        "Package " + invalidPackageName + " tried to change user "
16153                                + oldPackage.mSharedUserId);
16154                return;
16155            }
16156
16157            // check if the new package supports all of the abis which the old package supports
16158            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16159            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16160            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16161                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16162                        "Update to package " + pkgName + " doesn't support multi arch");
16163                return;
16164            }
16165
16166            // In case of rollback, remember per-user/profile install state
16167            allUsers = sUserManager.getUserIds();
16168            installedUsers = ps.queryInstalledUsers(allUsers, true);
16169
16170            // don't allow an upgrade from full to ephemeral
16171            if (isInstantApp) {
16172                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16173                    for (int currentUser : allUsers) {
16174                        if (!ps.getInstantApp(currentUser)) {
16175                            // can't downgrade from full to instant
16176                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16177                                    + " for user: " + currentUser);
16178                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16179                            return;
16180                        }
16181                    }
16182                } else if (!ps.getInstantApp(user.getIdentifier())) {
16183                    // can't downgrade from full to instant
16184                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16185                            + " for user: " + user.getIdentifier());
16186                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16187                    return;
16188                }
16189            }
16190        }
16191
16192        // Update what is removed
16193        res.removedInfo = new PackageRemovedInfo(this);
16194        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16195        res.removedInfo.removedPackage = oldPackage.packageName;
16196        res.removedInfo.installerPackageName = ps.installerPackageName;
16197        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16198        res.removedInfo.isUpdate = true;
16199        res.removedInfo.origUsers = installedUsers;
16200        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16201        for (int i = 0; i < installedUsers.length; i++) {
16202            final int userId = installedUsers[i];
16203            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16204        }
16205
16206        final int childCount = (oldPackage.childPackages != null)
16207                ? oldPackage.childPackages.size() : 0;
16208        for (int i = 0; i < childCount; i++) {
16209            boolean childPackageUpdated = false;
16210            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16211            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16212            if (res.addedChildPackages != null) {
16213                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16214                if (childRes != null) {
16215                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16216                    childRes.removedInfo.removedPackage = childPkg.packageName;
16217                    if (childPs != null) {
16218                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16219                    }
16220                    childRes.removedInfo.isUpdate = true;
16221                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16222                    childPackageUpdated = true;
16223                }
16224            }
16225            if (!childPackageUpdated) {
16226                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16227                childRemovedRes.removedPackage = childPkg.packageName;
16228                if (childPs != null) {
16229                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16230                }
16231                childRemovedRes.isUpdate = false;
16232                childRemovedRes.dataRemoved = true;
16233                synchronized (mPackages) {
16234                    if (childPs != null) {
16235                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16236                    }
16237                }
16238                if (res.removedInfo.removedChildPackages == null) {
16239                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16240                }
16241                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16242            }
16243        }
16244
16245        boolean sysPkg = (isSystemApp(oldPackage));
16246        if (sysPkg) {
16247            // Set the system/privileged/oem/vendor/product flags as needed
16248            final boolean privileged =
16249                    (oldPackage.applicationInfo.privateFlags
16250                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16251            final boolean oem =
16252                    (oldPackage.applicationInfo.privateFlags
16253                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16254            final boolean vendor =
16255                    (oldPackage.applicationInfo.privateFlags
16256                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16257            final boolean product =
16258                    (oldPackage.applicationInfo.privateFlags
16259                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16260            final @ParseFlags int systemParseFlags = parseFlags;
16261            final @ScanFlags int systemScanFlags = scanFlags
16262                    | SCAN_AS_SYSTEM
16263                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16264                    | (oem ? SCAN_AS_OEM : 0)
16265                    | (vendor ? SCAN_AS_VENDOR : 0)
16266                    | (product ? SCAN_AS_PRODUCT : 0);
16267
16268            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16269                    user, allUsers, installerPackageName, res, installReason);
16270        } else {
16271            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16272                    user, allUsers, installerPackageName, res, installReason);
16273        }
16274    }
16275
16276    @Override
16277    public List<String> getPreviousCodePaths(String packageName) {
16278        final int callingUid = Binder.getCallingUid();
16279        final List<String> result = new ArrayList<>();
16280        if (getInstantAppPackageName(callingUid) != null) {
16281            return result;
16282        }
16283        final PackageSetting ps = mSettings.mPackages.get(packageName);
16284        if (ps != null
16285                && ps.oldCodePaths != null
16286                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16287            result.addAll(ps.oldCodePaths);
16288        }
16289        return result;
16290    }
16291
16292    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16293            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16294            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16295            String installerPackageName, PackageInstalledInfo res, int installReason) {
16296        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16297                + deletedPackage);
16298
16299        String pkgName = deletedPackage.packageName;
16300        boolean deletedPkg = true;
16301        boolean addedPkg = false;
16302        boolean updatedSettings = false;
16303        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16304        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16305                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16306
16307        final long origUpdateTime = (pkg.mExtras != null)
16308                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16309
16310        // First delete the existing package while retaining the data directory
16311        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16312                res.removedInfo, true, pkg)) {
16313            // If the existing package wasn't successfully deleted
16314            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16315            deletedPkg = false;
16316        } else {
16317            // Successfully deleted the old package; proceed with replace.
16318
16319            // If deleted package lived in a container, give users a chance to
16320            // relinquish resources before killing.
16321            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16322                if (DEBUG_INSTALL) {
16323                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16324                }
16325                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16326                final ArrayList<String> pkgList = new ArrayList<String>(1);
16327                pkgList.add(deletedPackage.applicationInfo.packageName);
16328                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16329            }
16330
16331            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16332                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16333
16334            try {
16335                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16336                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16337                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16338                        installReason);
16339
16340                // Update the in-memory copy of the previous code paths.
16341                PackageSetting ps = mSettings.mPackages.get(pkgName);
16342                if (!killApp) {
16343                    if (ps.oldCodePaths == null) {
16344                        ps.oldCodePaths = new ArraySet<>();
16345                    }
16346                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16347                    if (deletedPackage.splitCodePaths != null) {
16348                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16349                    }
16350                } else {
16351                    ps.oldCodePaths = null;
16352                }
16353                if (ps.childPackageNames != null) {
16354                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16355                        final String childPkgName = ps.childPackageNames.get(i);
16356                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16357                        childPs.oldCodePaths = ps.oldCodePaths;
16358                    }
16359                }
16360                // set instant app status, but, only if it's explicitly specified
16361                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16362                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16363                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16364                prepareAppDataAfterInstallLIF(newPackage);
16365                addedPkg = true;
16366                mDexManager.notifyPackageUpdated(newPackage.packageName,
16367                        newPackage.baseCodePath, newPackage.splitCodePaths);
16368            } catch (PackageManagerException e) {
16369                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16370            }
16371        }
16372
16373        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16374            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16375
16376            // Revert all internal state mutations and added folders for the failed install
16377            if (addedPkg) {
16378                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16379                        res.removedInfo, true, null);
16380            }
16381
16382            // Restore the old package
16383            if (deletedPkg) {
16384                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16385                File restoreFile = new File(deletedPackage.codePath);
16386                // Parse old package
16387                boolean oldExternal = isExternal(deletedPackage);
16388                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16389                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16390                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16391                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16392                try {
16393                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16394                            null);
16395                } catch (PackageManagerException e) {
16396                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16397                            + e.getMessage());
16398                    return;
16399                }
16400
16401                synchronized (mPackages) {
16402                    // Ensure the installer package name up to date
16403                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16404
16405                    // Update permissions for restored package
16406                    mPermissionManager.updatePermissions(
16407                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16408                            mPermissionCallback);
16409
16410                    mSettings.writeLPr();
16411                }
16412
16413                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16414            }
16415        } else {
16416            synchronized (mPackages) {
16417                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16418                if (ps != null) {
16419                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16420                    if (res.removedInfo.removedChildPackages != null) {
16421                        final int childCount = res.removedInfo.removedChildPackages.size();
16422                        // Iterate in reverse as we may modify the collection
16423                        for (int i = childCount - 1; i >= 0; i--) {
16424                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16425                            if (res.addedChildPackages.containsKey(childPackageName)) {
16426                                res.removedInfo.removedChildPackages.removeAt(i);
16427                            } else {
16428                                PackageRemovedInfo childInfo = res.removedInfo
16429                                        .removedChildPackages.valueAt(i);
16430                                childInfo.removedForAllUsers = mPackages.get(
16431                                        childInfo.removedPackage) == null;
16432                            }
16433                        }
16434                    }
16435                }
16436            }
16437        }
16438    }
16439
16440    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16441            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16442            final @ScanFlags int scanFlags, UserHandle user,
16443            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16444            int installReason) {
16445        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16446                + ", old=" + deletedPackage);
16447
16448        final boolean disabledSystem;
16449
16450        // Remove existing system package
16451        removePackageLI(deletedPackage, true);
16452
16453        synchronized (mPackages) {
16454            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16455        }
16456        if (!disabledSystem) {
16457            // We didn't need to disable the .apk as a current system package,
16458            // which means we are replacing another update that is already
16459            // installed.  We need to make sure to delete the older one's .apk.
16460            res.removedInfo.args = createInstallArgsForExisting(0,
16461                    deletedPackage.applicationInfo.getCodePath(),
16462                    deletedPackage.applicationInfo.getResourcePath(),
16463                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16464        } else {
16465            res.removedInfo.args = null;
16466        }
16467
16468        // Successfully disabled the old package. Now proceed with re-installation
16469        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16470                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16471
16472        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16473        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16474                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16475
16476        PackageParser.Package newPackage = null;
16477        try {
16478            // Add the package to the internal data structures
16479            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16480
16481            // Set the update and install times
16482            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16483            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16484                    System.currentTimeMillis());
16485
16486            // Update the package dynamic state if succeeded
16487            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16488                // Now that the install succeeded make sure we remove data
16489                // directories for any child package the update removed.
16490                final int deletedChildCount = (deletedPackage.childPackages != null)
16491                        ? deletedPackage.childPackages.size() : 0;
16492                final int newChildCount = (newPackage.childPackages != null)
16493                        ? newPackage.childPackages.size() : 0;
16494                for (int i = 0; i < deletedChildCount; i++) {
16495                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16496                    boolean childPackageDeleted = true;
16497                    for (int j = 0; j < newChildCount; j++) {
16498                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16499                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16500                            childPackageDeleted = false;
16501                            break;
16502                        }
16503                    }
16504                    if (childPackageDeleted) {
16505                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16506                                deletedChildPkg.packageName);
16507                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16508                            PackageRemovedInfo removedChildRes = res.removedInfo
16509                                    .removedChildPackages.get(deletedChildPkg.packageName);
16510                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16511                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16512                        }
16513                    }
16514                }
16515
16516                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16517                        installReason);
16518                prepareAppDataAfterInstallLIF(newPackage);
16519
16520                mDexManager.notifyPackageUpdated(newPackage.packageName,
16521                            newPackage.baseCodePath, newPackage.splitCodePaths);
16522            }
16523        } catch (PackageManagerException e) {
16524            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16525            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16526        }
16527
16528        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16529            // Re installation failed. Restore old information
16530            // Remove new pkg information
16531            if (newPackage != null) {
16532                removeInstalledPackageLI(newPackage, true);
16533            }
16534            // Add back the old system package
16535            try {
16536                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16537            } catch (PackageManagerException e) {
16538                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16539            }
16540
16541            synchronized (mPackages) {
16542                if (disabledSystem) {
16543                    enableSystemPackageLPw(deletedPackage);
16544                }
16545
16546                // Ensure the installer package name up to date
16547                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16548
16549                // Update permissions for restored package
16550                mPermissionManager.updatePermissions(
16551                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16552                        mPermissionCallback);
16553
16554                mSettings.writeLPr();
16555            }
16556
16557            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16558                    + " after failed upgrade");
16559        }
16560    }
16561
16562    /**
16563     * Checks whether the parent or any of the child packages have a change shared
16564     * user. For a package to be a valid update the shred users of the parent and
16565     * the children should match. We may later support changing child shared users.
16566     * @param oldPkg The updated package.
16567     * @param newPkg The update package.
16568     * @return The shared user that change between the versions.
16569     */
16570    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16571            PackageParser.Package newPkg) {
16572        // Check parent shared user
16573        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16574            return newPkg.packageName;
16575        }
16576        // Check child shared users
16577        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16578        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16579        for (int i = 0; i < newChildCount; i++) {
16580            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16581            // If this child was present, did it have the same shared user?
16582            for (int j = 0; j < oldChildCount; j++) {
16583                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16584                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16585                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16586                    return newChildPkg.packageName;
16587                }
16588            }
16589        }
16590        return null;
16591    }
16592
16593    private void removeNativeBinariesLI(PackageSetting ps) {
16594        // Remove the lib path for the parent package
16595        if (ps != null) {
16596            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16597            // Remove the lib path for the child packages
16598            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16599            for (int i = 0; i < childCount; i++) {
16600                PackageSetting childPs = null;
16601                synchronized (mPackages) {
16602                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16603                }
16604                if (childPs != null) {
16605                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16606                            .legacyNativeLibraryPathString);
16607                }
16608            }
16609        }
16610    }
16611
16612    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16613        // Enable the parent package
16614        mSettings.enableSystemPackageLPw(pkg.packageName);
16615        // Enable the child packages
16616        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16617        for (int i = 0; i < childCount; i++) {
16618            PackageParser.Package childPkg = pkg.childPackages.get(i);
16619            mSettings.enableSystemPackageLPw(childPkg.packageName);
16620        }
16621    }
16622
16623    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16624            PackageParser.Package newPkg) {
16625        // Disable the parent package (parent always replaced)
16626        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16627        // Disable the child packages
16628        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16629        for (int i = 0; i < childCount; i++) {
16630            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16631            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16632            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16633        }
16634        return disabled;
16635    }
16636
16637    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16638            String installerPackageName) {
16639        // Enable the parent package
16640        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16641        // Enable the child packages
16642        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16643        for (int i = 0; i < childCount; i++) {
16644            PackageParser.Package childPkg = pkg.childPackages.get(i);
16645            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16646        }
16647    }
16648
16649    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16650            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16651        // Update the parent package setting
16652        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16653                res, user, installReason);
16654        // Update the child packages setting
16655        final int childCount = (newPackage.childPackages != null)
16656                ? newPackage.childPackages.size() : 0;
16657        for (int i = 0; i < childCount; i++) {
16658            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16659            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16660            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16661                    childRes.origUsers, childRes, user, installReason);
16662        }
16663    }
16664
16665    private void updateSettingsInternalLI(PackageParser.Package pkg,
16666            String installerPackageName, int[] allUsers, int[] installedForUsers,
16667            PackageInstalledInfo res, UserHandle user, int installReason) {
16668        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16669
16670        String pkgName = pkg.packageName;
16671        synchronized (mPackages) {
16672            //write settings. the installStatus will be incomplete at this stage.
16673            //note that the new package setting would have already been
16674            //added to mPackages. It hasn't been persisted yet.
16675            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16676            // TODO: Remove this write? It's also written at the end of this method
16677            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16678            mSettings.writeLPr();
16679            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16680        }
16681
16682        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16683        synchronized (mPackages) {
16684// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16685            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16686                    mPermissionCallback);
16687            // For system-bundled packages, we assume that installing an upgraded version
16688            // of the package implies that the user actually wants to run that new code,
16689            // so we enable the package.
16690            PackageSetting ps = mSettings.mPackages.get(pkgName);
16691            final int userId = user.getIdentifier();
16692            if (ps != null) {
16693                if (isSystemApp(pkg)) {
16694                    if (DEBUG_INSTALL) {
16695                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16696                    }
16697                    // Enable system package for requested users
16698                    if (res.origUsers != null) {
16699                        for (int origUserId : res.origUsers) {
16700                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16701                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16702                                        origUserId, installerPackageName);
16703                            }
16704                        }
16705                    }
16706                    // Also convey the prior install/uninstall state
16707                    if (allUsers != null && installedForUsers != null) {
16708                        for (int currentUserId : allUsers) {
16709                            final boolean installed = ArrayUtils.contains(
16710                                    installedForUsers, currentUserId);
16711                            if (DEBUG_INSTALL) {
16712                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16713                            }
16714                            ps.setInstalled(installed, currentUserId);
16715                        }
16716                        // these install state changes will be persisted in the
16717                        // upcoming call to mSettings.writeLPr().
16718                    }
16719                }
16720                // It's implied that when a user requests installation, they want the app to be
16721                // installed and enabled.
16722                if (userId != UserHandle.USER_ALL) {
16723                    ps.setInstalled(true, userId);
16724                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16725                }
16726
16727                // When replacing an existing package, preserve the original install reason for all
16728                // users that had the package installed before.
16729                final Set<Integer> previousUserIds = new ArraySet<>();
16730                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16731                    final int installReasonCount = res.removedInfo.installReasons.size();
16732                    for (int i = 0; i < installReasonCount; i++) {
16733                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16734                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16735                        ps.setInstallReason(previousInstallReason, previousUserId);
16736                        previousUserIds.add(previousUserId);
16737                    }
16738                }
16739
16740                // Set install reason for users that are having the package newly installed.
16741                if (userId == UserHandle.USER_ALL) {
16742                    for (int currentUserId : sUserManager.getUserIds()) {
16743                        if (!previousUserIds.contains(currentUserId)) {
16744                            ps.setInstallReason(installReason, currentUserId);
16745                        }
16746                    }
16747                } else if (!previousUserIds.contains(userId)) {
16748                    ps.setInstallReason(installReason, userId);
16749                }
16750                mSettings.writeKernelMappingLPr(ps);
16751            }
16752            res.name = pkgName;
16753            res.uid = pkg.applicationInfo.uid;
16754            res.pkg = pkg;
16755            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16756            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16757            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16758            //to update install status
16759            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16760            mSettings.writeLPr();
16761            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16762        }
16763
16764        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16765    }
16766
16767    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16768        try {
16769            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16770            installPackageLI(args, res);
16771        } finally {
16772            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16773        }
16774    }
16775
16776    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16777        final int installFlags = args.installFlags;
16778        final String installerPackageName = args.installerPackageName;
16779        final String volumeUuid = args.volumeUuid;
16780        final File tmpPackageFile = new File(args.getCodePath());
16781        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16782        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16783                || (args.volumeUuid != null));
16784        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16785        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16786        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16787        final boolean virtualPreload =
16788                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16789        boolean replace = false;
16790        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16791        if (args.move != null) {
16792            // moving a complete application; perform an initial scan on the new install location
16793            scanFlags |= SCAN_INITIAL;
16794        }
16795        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16796            scanFlags |= SCAN_DONT_KILL_APP;
16797        }
16798        if (instantApp) {
16799            scanFlags |= SCAN_AS_INSTANT_APP;
16800        }
16801        if (fullApp) {
16802            scanFlags |= SCAN_AS_FULL_APP;
16803        }
16804        if (virtualPreload) {
16805            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16806        }
16807
16808        // Result object to be returned
16809        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16810        res.installerPackageName = installerPackageName;
16811
16812        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16813
16814        // Sanity check
16815        if (instantApp && (forwardLocked || onExternal)) {
16816            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16817                    + " external=" + onExternal);
16818            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16819            return;
16820        }
16821
16822        // Retrieve PackageSettings and parse package
16823        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16824                | PackageParser.PARSE_ENFORCE_CODE
16825                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16826                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16827                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16828        PackageParser pp = new PackageParser();
16829        pp.setSeparateProcesses(mSeparateProcesses);
16830        pp.setDisplayMetrics(mMetrics);
16831        pp.setCallback(mPackageParserCallback);
16832
16833        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16834        final PackageParser.Package pkg;
16835        try {
16836            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16837            DexMetadataHelper.validatePackageDexMetadata(pkg);
16838        } catch (PackageParserException e) {
16839            res.setError("Failed parse during installPackageLI", e);
16840            return;
16841        } finally {
16842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16843        }
16844
16845        // Instant apps have several additional install-time checks.
16846        if (instantApp) {
16847            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16848                Slog.w(TAG,
16849                        "Instant app package " + pkg.packageName + " does not target at least O");
16850                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16851                        "Instant app package must target at least O");
16852                return;
16853            }
16854            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16855                Slog.w(TAG, "Instant app package " + pkg.packageName
16856                        + " does not target targetSandboxVersion 2");
16857                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16858                        "Instant app package must use targetSandboxVersion 2");
16859                return;
16860            }
16861            if (pkg.mSharedUserId != null) {
16862                Slog.w(TAG, "Instant app package " + pkg.packageName
16863                        + " may not declare sharedUserId.");
16864                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16865                        "Instant app package may not declare a sharedUserId");
16866                return;
16867            }
16868        }
16869
16870        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16871            // Static shared libraries have synthetic package names
16872            renameStaticSharedLibraryPackage(pkg);
16873
16874            // No static shared libs on external storage
16875            if (onExternal) {
16876                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16877                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16878                        "Packages declaring static-shared libs cannot be updated");
16879                return;
16880            }
16881        }
16882
16883        // If we are installing a clustered package add results for the children
16884        if (pkg.childPackages != null) {
16885            synchronized (mPackages) {
16886                final int childCount = pkg.childPackages.size();
16887                for (int i = 0; i < childCount; i++) {
16888                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16889                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16890                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16891                    childRes.pkg = childPkg;
16892                    childRes.name = childPkg.packageName;
16893                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16894                    if (childPs != null) {
16895                        childRes.origUsers = childPs.queryInstalledUsers(
16896                                sUserManager.getUserIds(), true);
16897                    }
16898                    if ((mPackages.containsKey(childPkg.packageName))) {
16899                        childRes.removedInfo = new PackageRemovedInfo(this);
16900                        childRes.removedInfo.removedPackage = childPkg.packageName;
16901                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16902                    }
16903                    if (res.addedChildPackages == null) {
16904                        res.addedChildPackages = new ArrayMap<>();
16905                    }
16906                    res.addedChildPackages.put(childPkg.packageName, childRes);
16907                }
16908            }
16909        }
16910
16911        // If package doesn't declare API override, mark that we have an install
16912        // time CPU ABI override.
16913        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16914            pkg.cpuAbiOverride = args.abiOverride;
16915        }
16916
16917        String pkgName = res.name = pkg.packageName;
16918        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16919            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16920                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16921                return;
16922            }
16923        }
16924
16925        try {
16926            // either use what we've been given or parse directly from the APK
16927            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16928                pkg.setSigningDetails(args.signingDetails);
16929            } else {
16930                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16931            }
16932        } catch (PackageParserException e) {
16933            res.setError("Failed collect during installPackageLI", e);
16934            return;
16935        }
16936
16937        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16938                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16939            Slog.w(TAG, "Instant app package " + pkg.packageName
16940                    + " is not signed with at least APK Signature Scheme v2");
16941            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16942                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16943            return;
16944        }
16945
16946        // Get rid of all references to package scan path via parser.
16947        pp = null;
16948        String oldCodePath = null;
16949        boolean systemApp = false;
16950        synchronized (mPackages) {
16951            // Check if installing already existing package
16952            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16953                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16954                if (pkg.mOriginalPackages != null
16955                        && pkg.mOriginalPackages.contains(oldName)
16956                        && mPackages.containsKey(oldName)) {
16957                    // This package is derived from an original package,
16958                    // and this device has been updating from that original
16959                    // name.  We must continue using the original name, so
16960                    // rename the new package here.
16961                    pkg.setPackageName(oldName);
16962                    pkgName = pkg.packageName;
16963                    replace = true;
16964                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16965                            + oldName + " pkgName=" + pkgName);
16966                } else if (mPackages.containsKey(pkgName)) {
16967                    // This package, under its official name, already exists
16968                    // on the device; we should replace it.
16969                    replace = true;
16970                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16971                }
16972
16973                // Child packages are installed through the parent package
16974                if (pkg.parentPackage != null) {
16975                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16976                            "Package " + pkg.packageName + " is child of package "
16977                                    + pkg.parentPackage.parentPackage + ". Child packages "
16978                                    + "can be updated only through the parent package.");
16979                    return;
16980                }
16981
16982                if (replace) {
16983                    // Prevent apps opting out from runtime permissions
16984                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16985                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16986                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16987                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16988                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16989                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16990                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16991                                        + " doesn't support runtime permissions but the old"
16992                                        + " target SDK " + oldTargetSdk + " does.");
16993                        return;
16994                    }
16995                    // Prevent persistent apps from being updated
16996                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16997                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16998                                "Package " + oldPackage.packageName + " is a persistent app. "
16999                                        + "Persistent apps are not updateable.");
17000                        return;
17001                    }
17002                    // Prevent apps from downgrading their targetSandbox.
17003                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17004                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17005                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17006                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17007                                "Package " + pkg.packageName + " new target sandbox "
17008                                + newTargetSandbox + " is incompatible with the previous value of"
17009                                + oldTargetSandbox + ".");
17010                        return;
17011                    }
17012
17013                    // Prevent installing of child packages
17014                    if (oldPackage.parentPackage != null) {
17015                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17016                                "Package " + pkg.packageName + " is child of package "
17017                                        + oldPackage.parentPackage + ". Child packages "
17018                                        + "can be updated only through the parent package.");
17019                        return;
17020                    }
17021                }
17022            }
17023
17024            PackageSetting ps = mSettings.mPackages.get(pkgName);
17025            if (ps != null) {
17026                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17027
17028                // Static shared libs have same package with different versions where
17029                // we internally use a synthetic package name to allow multiple versions
17030                // of the same package, therefore we need to compare signatures against
17031                // the package setting for the latest library version.
17032                PackageSetting signatureCheckPs = ps;
17033                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17034                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17035                    if (libraryEntry != null) {
17036                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17037                    }
17038                }
17039
17040                // Quick sanity check that we're signed correctly if updating;
17041                // we'll check this again later when scanning, but we want to
17042                // bail early here before tripping over redefined permissions.
17043                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17044                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17045                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17046                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17047                                + pkg.packageName + " upgrade keys do not match the "
17048                                + "previously installed version");
17049                        return;
17050                    }
17051                } else {
17052                    try {
17053                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17054                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17055                        // We don't care about disabledPkgSetting on install for now.
17056                        final boolean compatMatch = verifySignatures(
17057                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17058                                compareRecover);
17059                        // The new KeySets will be re-added later in the scanning process.
17060                        if (compatMatch) {
17061                            synchronized (mPackages) {
17062                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17063                            }
17064                        }
17065                    } catch (PackageManagerException e) {
17066                        res.setError(e.error, e.getMessage());
17067                        return;
17068                    }
17069                }
17070
17071                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17072                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17073                    systemApp = (ps.pkg.applicationInfo.flags &
17074                            ApplicationInfo.FLAG_SYSTEM) != 0;
17075                }
17076                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17077            }
17078
17079            int N = pkg.permissions.size();
17080            for (int i = N-1; i >= 0; i--) {
17081                final PackageParser.Permission perm = pkg.permissions.get(i);
17082                final BasePermission bp =
17083                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17084
17085                // Don't allow anyone but the system to define ephemeral permissions.
17086                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17087                        && !systemApp) {
17088                    Slog.w(TAG, "Non-System package " + pkg.packageName
17089                            + " attempting to delcare ephemeral permission "
17090                            + perm.info.name + "; Removing ephemeral.");
17091                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17092                }
17093
17094                // Check whether the newly-scanned package wants to define an already-defined perm
17095                if (bp != null) {
17096                    // If the defining package is signed with our cert, it's okay.  This
17097                    // also includes the "updating the same package" case, of course.
17098                    // "updating same package" could also involve key-rotation.
17099                    final boolean sigsOk;
17100                    final String sourcePackageName = bp.getSourcePackageName();
17101                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17102                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17103                    if (sourcePackageName.equals(pkg.packageName)
17104                            && (ksms.shouldCheckUpgradeKeySetLocked(
17105                                    sourcePackageSetting, scanFlags))) {
17106                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17107                    } else {
17108
17109                        // in the event of signing certificate rotation, we need to see if the
17110                        // package's certificate has rotated from the current one, or if it is an
17111                        // older certificate with which the current is ok with sharing permissions
17112                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17113                                        pkg.mSigningDetails,
17114                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17115                            sigsOk = true;
17116                        } else if (pkg.mSigningDetails.checkCapability(
17117                                        sourcePackageSetting.signatures.mSigningDetails,
17118                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17119
17120                            // the scanned package checks out, has signing certificate rotation
17121                            // history, and is newer; bring it over
17122                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17123                            sigsOk = true;
17124                        } else {
17125                            sigsOk = false;
17126                        }
17127                    }
17128                    if (!sigsOk) {
17129                        // If the owning package is the system itself, we log but allow
17130                        // install to proceed; we fail the install on all other permission
17131                        // redefinitions.
17132                        if (!sourcePackageName.equals("android")) {
17133                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17134                                    + pkg.packageName + " attempting to redeclare permission "
17135                                    + perm.info.name + " already owned by " + sourcePackageName);
17136                            res.origPermission = perm.info.name;
17137                            res.origPackage = sourcePackageName;
17138                            return;
17139                        } else {
17140                            Slog.w(TAG, "Package " + pkg.packageName
17141                                    + " attempting to redeclare system permission "
17142                                    + perm.info.name + "; ignoring new declaration");
17143                            pkg.permissions.remove(i);
17144                        }
17145                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17146                        // Prevent apps to change protection level to dangerous from any other
17147                        // type as this would allow a privilege escalation where an app adds a
17148                        // normal/signature permission in other app's group and later redefines
17149                        // it as dangerous leading to the group auto-grant.
17150                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17151                                == PermissionInfo.PROTECTION_DANGEROUS) {
17152                            if (bp != null && !bp.isRuntime()) {
17153                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17154                                        + "non-runtime permission " + perm.info.name
17155                                        + " to runtime; keeping old protection level");
17156                                perm.info.protectionLevel = bp.getProtectionLevel();
17157                            }
17158                        }
17159                    }
17160                }
17161            }
17162        }
17163
17164        if (systemApp) {
17165            if (onExternal) {
17166                // Abort update; system app can't be replaced with app on sdcard
17167                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17168                        "Cannot install updates to system apps on sdcard");
17169                return;
17170            } else if (instantApp) {
17171                // Abort update; system app can't be replaced with an instant app
17172                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17173                        "Cannot update a system app with an instant app");
17174                return;
17175            }
17176        }
17177
17178        if (args.move != null) {
17179            // We did an in-place move, so dex is ready to roll
17180            scanFlags |= SCAN_NO_DEX;
17181            scanFlags |= SCAN_MOVE;
17182
17183            synchronized (mPackages) {
17184                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17185                if (ps == null) {
17186                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17187                            "Missing settings for moved package " + pkgName);
17188                }
17189
17190                // We moved the entire application as-is, so bring over the
17191                // previously derived ABI information.
17192                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17193                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17194            }
17195
17196        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17197            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17198            scanFlags |= SCAN_NO_DEX;
17199
17200            try {
17201                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17202                    args.abiOverride : pkg.cpuAbiOverride);
17203                final boolean extractNativeLibs = !pkg.isLibrary();
17204                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17205            } catch (PackageManagerException pme) {
17206                Slog.e(TAG, "Error deriving application ABI", pme);
17207                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17208                return;
17209            }
17210
17211            // Shared libraries for the package need to be updated.
17212            synchronized (mPackages) {
17213                try {
17214                    updateSharedLibrariesLPr(pkg, null);
17215                } catch (PackageManagerException e) {
17216                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17217                }
17218            }
17219        }
17220
17221        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17222            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17223            return;
17224        }
17225
17226        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17227            String apkPath = null;
17228            synchronized (mPackages) {
17229                // Note that if the attacker managed to skip verify setup, for example by tampering
17230                // with the package settings, upon reboot we will do full apk verification when
17231                // verity is not detected.
17232                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17233                if (ps != null && ps.isPrivileged()) {
17234                    apkPath = pkg.baseCodePath;
17235                }
17236            }
17237
17238            if (apkPath != null) {
17239                final VerityUtils.SetupResult result =
17240                        VerityUtils.generateApkVeritySetupData(apkPath);
17241                if (result.isOk()) {
17242                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17243                    FileDescriptor fd = result.getUnownedFileDescriptor();
17244                    try {
17245                        mInstaller.installApkVerity(apkPath, fd);
17246                    } catch (InstallerException e) {
17247                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17248                                "Failed to set up verity: " + e);
17249                        return;
17250                    } finally {
17251                        IoUtils.closeQuietly(fd);
17252                    }
17253                } else if (result.isFailed()) {
17254                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17255                    return;
17256                } else {
17257                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17258                    // reboot.
17259                }
17260            }
17261        }
17262
17263        if (!instantApp) {
17264            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17265        } else {
17266            if (DEBUG_DOMAIN_VERIFICATION) {
17267                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17268            }
17269        }
17270
17271        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17272                "installPackageLI")) {
17273            if (replace) {
17274                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17275                    // Static libs have a synthetic package name containing the version
17276                    // and cannot be updated as an update would get a new package name,
17277                    // unless this is the exact same version code which is useful for
17278                    // development.
17279                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17280                    if (existingPkg != null &&
17281                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17282                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17283                                + "static-shared libs cannot be updated");
17284                        return;
17285                    }
17286                }
17287                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17288                        installerPackageName, res, args.installReason);
17289            } else {
17290                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17291                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17292            }
17293        }
17294
17295        // Prepare the application profiles for the new code paths.
17296        // This needs to be done before invoking dexopt so that any install-time profile
17297        // can be used for optimizations.
17298        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17299
17300        // Check whether we need to dexopt the app.
17301        //
17302        // NOTE: it is IMPORTANT to call dexopt:
17303        //   - after doRename which will sync the package data from PackageParser.Package and its
17304        //     corresponding ApplicationInfo.
17305        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17306        //     uid of the application (pkg.applicationInfo.uid).
17307        //     This update happens in place!
17308        //
17309        // We only need to dexopt if the package meets ALL of the following conditions:
17310        //   1) it is not forward locked.
17311        //   2) it is not on on an external ASEC container.
17312        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17313        //
17314        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17315        // complete, so we skip this step during installation. Instead, we'll take extra time
17316        // the first time the instant app starts. It's preferred to do it this way to provide
17317        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17318        // middle of running an instant app. The default behaviour can be overridden
17319        // via gservices.
17320        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17321                && !forwardLocked
17322                && !pkg.applicationInfo.isExternalAsec()
17323                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17324                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17325
17326        if (performDexopt) {
17327            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17328            // Do not run PackageDexOptimizer through the local performDexOpt
17329            // method because `pkg` may not be in `mPackages` yet.
17330            //
17331            // Also, don't fail application installs if the dexopt step fails.
17332            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17333                    REASON_INSTALL,
17334                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17335                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17336            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17337                    null /* instructionSets */,
17338                    getOrCreateCompilerPackageStats(pkg),
17339                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17340                    dexoptOptions);
17341            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17342        }
17343
17344        // Notify BackgroundDexOptService that the package has been changed.
17345        // If this is an update of a package which used to fail to compile,
17346        // BackgroundDexOptService will remove it from its blacklist.
17347        // TODO: Layering violation
17348        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17349
17350        synchronized (mPackages) {
17351            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17352            if (ps != null) {
17353                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17354                ps.setUpdateAvailable(false /*updateAvailable*/);
17355            }
17356
17357            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17358            for (int i = 0; i < childCount; i++) {
17359                PackageParser.Package childPkg = pkg.childPackages.get(i);
17360                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17361                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17362                if (childPs != null) {
17363                    childRes.newUsers = childPs.queryInstalledUsers(
17364                            sUserManager.getUserIds(), true);
17365                }
17366            }
17367
17368            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17369                updateSequenceNumberLP(ps, res.newUsers);
17370                updateInstantAppInstallerLocked(pkgName);
17371            }
17372        }
17373    }
17374
17375    private void startIntentFilterVerifications(int userId, boolean replacing,
17376            PackageParser.Package pkg) {
17377        if (mIntentFilterVerifierComponent == null) {
17378            Slog.w(TAG, "No IntentFilter verification will not be done as "
17379                    + "there is no IntentFilterVerifier available!");
17380            return;
17381        }
17382
17383        final int verifierUid = getPackageUid(
17384                mIntentFilterVerifierComponent.getPackageName(),
17385                MATCH_DEBUG_TRIAGED_MISSING,
17386                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17387
17388        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17389        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17390        mHandler.sendMessage(msg);
17391
17392        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17393        for (int i = 0; i < childCount; i++) {
17394            PackageParser.Package childPkg = pkg.childPackages.get(i);
17395            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17396            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17397            mHandler.sendMessage(msg);
17398        }
17399    }
17400
17401    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17402            PackageParser.Package pkg) {
17403        int size = pkg.activities.size();
17404        if (size == 0) {
17405            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17406                    "No activity, so no need to verify any IntentFilter!");
17407            return;
17408        }
17409
17410        final boolean hasDomainURLs = hasDomainURLs(pkg);
17411        if (!hasDomainURLs) {
17412            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17413                    "No domain URLs, so no need to verify any IntentFilter!");
17414            return;
17415        }
17416
17417        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17418                + " if any IntentFilter from the " + size
17419                + " Activities needs verification ...");
17420
17421        int count = 0;
17422        final String packageName = pkg.packageName;
17423
17424        synchronized (mPackages) {
17425            // If this is a new install and we see that we've already run verification for this
17426            // package, we have nothing to do: it means the state was restored from backup.
17427            if (!replacing) {
17428                IntentFilterVerificationInfo ivi =
17429                        mSettings.getIntentFilterVerificationLPr(packageName);
17430                if (ivi != null) {
17431                    if (DEBUG_DOMAIN_VERIFICATION) {
17432                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17433                                + ivi.getStatusString());
17434                    }
17435                    return;
17436                }
17437            }
17438
17439            // If any filters need to be verified, then all need to be.
17440            boolean needToVerify = false;
17441            for (PackageParser.Activity a : pkg.activities) {
17442                for (ActivityIntentInfo filter : a.intents) {
17443                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17444                        if (DEBUG_DOMAIN_VERIFICATION) {
17445                            Slog.d(TAG,
17446                                    "Intent filter needs verification, so processing all filters");
17447                        }
17448                        needToVerify = true;
17449                        break;
17450                    }
17451                }
17452            }
17453
17454            if (needToVerify) {
17455                final int verificationId = mIntentFilterVerificationToken++;
17456                for (PackageParser.Activity a : pkg.activities) {
17457                    for (ActivityIntentInfo filter : a.intents) {
17458                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17459                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17460                                    "Verification needed for IntentFilter:" + filter.toString());
17461                            mIntentFilterVerifier.addOneIntentFilterVerification(
17462                                    verifierUid, userId, verificationId, filter, packageName);
17463                            count++;
17464                        }
17465                    }
17466                }
17467            }
17468        }
17469
17470        if (count > 0) {
17471            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17472                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17473                    +  " for userId:" + userId);
17474            mIntentFilterVerifier.startVerifications(userId);
17475        } else {
17476            if (DEBUG_DOMAIN_VERIFICATION) {
17477                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17478            }
17479        }
17480    }
17481
17482    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17483        final ComponentName cn  = filter.activity.getComponentName();
17484        final String packageName = cn.getPackageName();
17485
17486        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17487                packageName);
17488        if (ivi == null) {
17489            return true;
17490        }
17491        int status = ivi.getStatus();
17492        switch (status) {
17493            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17494            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17495                return true;
17496
17497            default:
17498                // Nothing to do
17499                return false;
17500        }
17501    }
17502
17503    private static boolean isMultiArch(ApplicationInfo info) {
17504        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17505    }
17506
17507    private static boolean isExternal(PackageParser.Package pkg) {
17508        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17509    }
17510
17511    private static boolean isExternal(PackageSetting ps) {
17512        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17513    }
17514
17515    private static boolean isSystemApp(PackageParser.Package pkg) {
17516        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17517    }
17518
17519    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17520        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17521    }
17522
17523    private static boolean isOemApp(PackageParser.Package pkg) {
17524        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17525    }
17526
17527    private static boolean isVendorApp(PackageParser.Package pkg) {
17528        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17529    }
17530
17531    private static boolean isProductApp(PackageParser.Package pkg) {
17532        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17533    }
17534
17535    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17536        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17537    }
17538
17539    private static boolean isSystemApp(PackageSetting ps) {
17540        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17541    }
17542
17543    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17544        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17545    }
17546
17547    private int packageFlagsToInstallFlags(PackageSetting ps) {
17548        int installFlags = 0;
17549        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17550            // This existing package was an external ASEC install when we have
17551            // the external flag without a UUID
17552            installFlags |= PackageManager.INSTALL_EXTERNAL;
17553        }
17554        if (ps.isForwardLocked()) {
17555            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17556        }
17557        return installFlags;
17558    }
17559
17560    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17561        if (isExternal(pkg)) {
17562            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17563                return mSettings.getExternalVersion();
17564            } else {
17565                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17566            }
17567        } else {
17568            return mSettings.getInternalVersion();
17569        }
17570    }
17571
17572    private void deleteTempPackageFiles() {
17573        final FilenameFilter filter = new FilenameFilter() {
17574            public boolean accept(File dir, String name) {
17575                return name.startsWith("vmdl") && name.endsWith(".tmp");
17576            }
17577        };
17578        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17579            file.delete();
17580        }
17581    }
17582
17583    @Override
17584    public void deletePackageAsUser(String packageName, int versionCode,
17585            IPackageDeleteObserver observer, int userId, int flags) {
17586        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17587                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17588    }
17589
17590    @Override
17591    public void deletePackageVersioned(VersionedPackage versionedPackage,
17592            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17593        final int callingUid = Binder.getCallingUid();
17594        mContext.enforceCallingOrSelfPermission(
17595                android.Manifest.permission.DELETE_PACKAGES, null);
17596        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17597        Preconditions.checkNotNull(versionedPackage);
17598        Preconditions.checkNotNull(observer);
17599        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17600                PackageManager.VERSION_CODE_HIGHEST,
17601                Long.MAX_VALUE, "versionCode must be >= -1");
17602
17603        final String packageName = versionedPackage.getPackageName();
17604        final long versionCode = versionedPackage.getLongVersionCode();
17605        final String internalPackageName;
17606        synchronized (mPackages) {
17607            // Normalize package name to handle renamed packages and static libs
17608            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17609        }
17610
17611        final int uid = Binder.getCallingUid();
17612        if (!isOrphaned(internalPackageName)
17613                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17614            try {
17615                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17616                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17617                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17618                observer.onUserActionRequired(intent);
17619            } catch (RemoteException re) {
17620            }
17621            return;
17622        }
17623        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17624        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17625        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17626            mContext.enforceCallingOrSelfPermission(
17627                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17628                    "deletePackage for user " + userId);
17629        }
17630
17631        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17632            try {
17633                observer.onPackageDeleted(packageName,
17634                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17635            } catch (RemoteException re) {
17636            }
17637            return;
17638        }
17639
17640        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17641            try {
17642                observer.onPackageDeleted(packageName,
17643                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17644            } catch (RemoteException re) {
17645            }
17646            return;
17647        }
17648
17649        if (DEBUG_REMOVE) {
17650            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17651                    + " deleteAllUsers: " + deleteAllUsers + " version="
17652                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17653                    ? "VERSION_CODE_HIGHEST" : versionCode));
17654        }
17655        // Queue up an async operation since the package deletion may take a little while.
17656        mHandler.post(new Runnable() {
17657            public void run() {
17658                mHandler.removeCallbacks(this);
17659                int returnCode;
17660                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17661                boolean doDeletePackage = true;
17662                if (ps != null) {
17663                    final boolean targetIsInstantApp =
17664                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17665                    doDeletePackage = !targetIsInstantApp
17666                            || canViewInstantApps;
17667                }
17668                if (doDeletePackage) {
17669                    if (!deleteAllUsers) {
17670                        returnCode = deletePackageX(internalPackageName, versionCode,
17671                                userId, deleteFlags);
17672                    } else {
17673                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17674                                internalPackageName, users);
17675                        // If nobody is blocking uninstall, proceed with delete for all users
17676                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17677                            returnCode = deletePackageX(internalPackageName, versionCode,
17678                                    userId, deleteFlags);
17679                        } else {
17680                            // Otherwise uninstall individually for users with blockUninstalls=false
17681                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17682                            for (int userId : users) {
17683                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17684                                    returnCode = deletePackageX(internalPackageName, versionCode,
17685                                            userId, userFlags);
17686                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17687                                        Slog.w(TAG, "Package delete failed for user " + userId
17688                                                + ", returnCode " + returnCode);
17689                                    }
17690                                }
17691                            }
17692                            // The app has only been marked uninstalled for certain users.
17693                            // We still need to report that delete was blocked
17694                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17695                        }
17696                    }
17697                } else {
17698                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17699                }
17700                try {
17701                    observer.onPackageDeleted(packageName, returnCode, null);
17702                } catch (RemoteException e) {
17703                    Log.i(TAG, "Observer no longer exists.");
17704                } //end catch
17705            } //end run
17706        });
17707    }
17708
17709    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17710        if (pkg.staticSharedLibName != null) {
17711            return pkg.manifestPackageName;
17712        }
17713        return pkg.packageName;
17714    }
17715
17716    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17717        // Handle renamed packages
17718        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17719        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17720
17721        // Is this a static library?
17722        LongSparseArray<SharedLibraryEntry> versionedLib =
17723                mStaticLibsByDeclaringPackage.get(packageName);
17724        if (versionedLib == null || versionedLib.size() <= 0) {
17725            return packageName;
17726        }
17727
17728        // Figure out which lib versions the caller can see
17729        LongSparseLongArray versionsCallerCanSee = null;
17730        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17731        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17732                && callingAppId != Process.ROOT_UID) {
17733            versionsCallerCanSee = new LongSparseLongArray();
17734            String libName = versionedLib.valueAt(0).info.getName();
17735            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17736            if (uidPackages != null) {
17737                for (String uidPackage : uidPackages) {
17738                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17739                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17740                    if (libIdx >= 0) {
17741                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17742                        versionsCallerCanSee.append(libVersion, libVersion);
17743                    }
17744                }
17745            }
17746        }
17747
17748        // Caller can see nothing - done
17749        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17750            return packageName;
17751        }
17752
17753        // Find the version the caller can see and the app version code
17754        SharedLibraryEntry highestVersion = null;
17755        final int versionCount = versionedLib.size();
17756        for (int i = 0; i < versionCount; i++) {
17757            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17758            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17759                    libEntry.info.getLongVersion()) < 0) {
17760                continue;
17761            }
17762            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17763            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17764                if (libVersionCode == versionCode) {
17765                    return libEntry.apk;
17766                }
17767            } else if (highestVersion == null) {
17768                highestVersion = libEntry;
17769            } else if (libVersionCode  > highestVersion.info
17770                    .getDeclaringPackage().getLongVersionCode()) {
17771                highestVersion = libEntry;
17772            }
17773        }
17774
17775        if (highestVersion != null) {
17776            return highestVersion.apk;
17777        }
17778
17779        return packageName;
17780    }
17781
17782    boolean isCallerVerifier(int callingUid) {
17783        final int callingUserId = UserHandle.getUserId(callingUid);
17784        return mRequiredVerifierPackage != null &&
17785                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17786    }
17787
17788    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17789        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17790              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17791            return true;
17792        }
17793        final int callingUserId = UserHandle.getUserId(callingUid);
17794        // If the caller installed the pkgName, then allow it to silently uninstall.
17795        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17796            return true;
17797        }
17798
17799        // Allow package verifier to silently uninstall.
17800        if (mRequiredVerifierPackage != null &&
17801                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17802            return true;
17803        }
17804
17805        // Allow package uninstaller to silently uninstall.
17806        if (mRequiredUninstallerPackage != null &&
17807                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17808            return true;
17809        }
17810
17811        // Allow storage manager to silently uninstall.
17812        if (mStorageManagerPackage != null &&
17813                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17814            return true;
17815        }
17816
17817        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17818        // uninstall for device owner provisioning.
17819        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17820                == PERMISSION_GRANTED) {
17821            return true;
17822        }
17823
17824        return false;
17825    }
17826
17827    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17828        int[] result = EMPTY_INT_ARRAY;
17829        for (int userId : userIds) {
17830            if (getBlockUninstallForUser(packageName, userId)) {
17831                result = ArrayUtils.appendInt(result, userId);
17832            }
17833        }
17834        return result;
17835    }
17836
17837    @Override
17838    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17839        final int callingUid = Binder.getCallingUid();
17840        if (getInstantAppPackageName(callingUid) != null
17841                && !isCallerSameApp(packageName, callingUid)) {
17842            return false;
17843        }
17844        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17845    }
17846
17847    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17848        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17849                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17850        try {
17851            if (dpm != null) {
17852                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17853                        /* callingUserOnly =*/ false);
17854                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17855                        : deviceOwnerComponentName.getPackageName();
17856                // Does the package contains the device owner?
17857                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17858                // this check is probably not needed, since DO should be registered as a device
17859                // admin on some user too. (Original bug for this: b/17657954)
17860                if (packageName.equals(deviceOwnerPackageName)) {
17861                    return true;
17862                }
17863                // Does it contain a device admin for any user?
17864                int[] users;
17865                if (userId == UserHandle.USER_ALL) {
17866                    users = sUserManager.getUserIds();
17867                } else {
17868                    users = new int[]{userId};
17869                }
17870                for (int i = 0; i < users.length; ++i) {
17871                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17872                        return true;
17873                    }
17874                }
17875            }
17876        } catch (RemoteException e) {
17877        }
17878        return false;
17879    }
17880
17881    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17882        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17883    }
17884
17885    /**
17886     *  This method is an internal method that could be get invoked either
17887     *  to delete an installed package or to clean up a failed installation.
17888     *  After deleting an installed package, a broadcast is sent to notify any
17889     *  listeners that the package has been removed. For cleaning up a failed
17890     *  installation, the broadcast is not necessary since the package's
17891     *  installation wouldn't have sent the initial broadcast either
17892     *  The key steps in deleting a package are
17893     *  deleting the package information in internal structures like mPackages,
17894     *  deleting the packages base directories through installd
17895     *  updating mSettings to reflect current status
17896     *  persisting settings for later use
17897     *  sending a broadcast if necessary
17898     */
17899    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17900        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17901        final boolean res;
17902
17903        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17904                ? UserHandle.USER_ALL : userId;
17905
17906        if (isPackageDeviceAdmin(packageName, removeUser)) {
17907            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17908            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17909        }
17910
17911        PackageSetting uninstalledPs = null;
17912        PackageParser.Package pkg = null;
17913
17914        // for the uninstall-updates case and restricted profiles, remember the per-
17915        // user handle installed state
17916        int[] allUsers;
17917        synchronized (mPackages) {
17918            uninstalledPs = mSettings.mPackages.get(packageName);
17919            if (uninstalledPs == null) {
17920                Slog.w(TAG, "Not removing non-existent package " + packageName);
17921                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17922            }
17923
17924            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17925                    && uninstalledPs.versionCode != versionCode) {
17926                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17927                        + uninstalledPs.versionCode + " != " + versionCode);
17928                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17929            }
17930
17931            // Static shared libs can be declared by any package, so let us not
17932            // allow removing a package if it provides a lib others depend on.
17933            pkg = mPackages.get(packageName);
17934
17935            allUsers = sUserManager.getUserIds();
17936
17937            if (pkg != null && pkg.staticSharedLibName != null) {
17938                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17939                        pkg.staticSharedLibVersion);
17940                if (libEntry != null) {
17941                    for (int currUserId : allUsers) {
17942                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17943                            continue;
17944                        }
17945                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17946                                libEntry.info, 0, currUserId);
17947                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17948                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17949                                    + " hosting lib " + libEntry.info.getName() + " version "
17950                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17951                                    + " for user " + currUserId);
17952                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17953                        }
17954                    }
17955                }
17956            }
17957
17958            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17959        }
17960
17961        final int freezeUser;
17962        if (isUpdatedSystemApp(uninstalledPs)
17963                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17964            // We're downgrading a system app, which will apply to all users, so
17965            // freeze them all during the downgrade
17966            freezeUser = UserHandle.USER_ALL;
17967        } else {
17968            freezeUser = removeUser;
17969        }
17970
17971        synchronized (mInstallLock) {
17972            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17973            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17974                    deleteFlags, "deletePackageX")) {
17975                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17976                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17977            }
17978            synchronized (mPackages) {
17979                if (res) {
17980                    if (pkg != null) {
17981                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17982                    }
17983                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17984                    updateInstantAppInstallerLocked(packageName);
17985                }
17986            }
17987        }
17988
17989        if (res) {
17990            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17991            info.sendPackageRemovedBroadcasts(killApp);
17992            info.sendSystemPackageUpdatedBroadcasts();
17993            info.sendSystemPackageAppearedBroadcasts();
17994        }
17995        // Force a gc here.
17996        Runtime.getRuntime().gc();
17997        // Delete the resources here after sending the broadcast to let
17998        // other processes clean up before deleting resources.
17999        if (info.args != null) {
18000            synchronized (mInstallLock) {
18001                info.args.doPostDeleteLI(true);
18002            }
18003        }
18004
18005        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18006    }
18007
18008    static class PackageRemovedInfo {
18009        final PackageSender packageSender;
18010        String removedPackage;
18011        String installerPackageName;
18012        int uid = -1;
18013        int removedAppId = -1;
18014        int[] origUsers;
18015        int[] removedUsers = null;
18016        int[] broadcastUsers = null;
18017        int[] instantUserIds = null;
18018        SparseArray<Integer> installReasons;
18019        boolean isRemovedPackageSystemUpdate = false;
18020        boolean isUpdate;
18021        boolean dataRemoved;
18022        boolean removedForAllUsers;
18023        boolean isStaticSharedLib;
18024        // Clean up resources deleted packages.
18025        InstallArgs args = null;
18026        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18027        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18028
18029        PackageRemovedInfo(PackageSender packageSender) {
18030            this.packageSender = packageSender;
18031        }
18032
18033        void sendPackageRemovedBroadcasts(boolean killApp) {
18034            sendPackageRemovedBroadcastInternal(killApp);
18035            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18036            for (int i = 0; i < childCount; i++) {
18037                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18038                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18039            }
18040        }
18041
18042        void sendSystemPackageUpdatedBroadcasts() {
18043            if (isRemovedPackageSystemUpdate) {
18044                sendSystemPackageUpdatedBroadcastsInternal();
18045                final int childCount = (removedChildPackages != null)
18046                        ? removedChildPackages.size() : 0;
18047                for (int i = 0; i < childCount; i++) {
18048                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18049                    if (childInfo.isRemovedPackageSystemUpdate) {
18050                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18051                    }
18052                }
18053            }
18054        }
18055
18056        void sendSystemPackageAppearedBroadcasts() {
18057            final int packageCount = (appearedChildPackages != null)
18058                    ? appearedChildPackages.size() : 0;
18059            for (int i = 0; i < packageCount; i++) {
18060                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18061                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18062                    true /*sendBootCompleted*/, false /*startReceiver*/,
18063                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18064            }
18065        }
18066
18067        private void sendSystemPackageUpdatedBroadcastsInternal() {
18068            Bundle extras = new Bundle(2);
18069            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18070            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18071            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18072                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18073            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18074                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18075            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18076                null, null, 0, removedPackage, null, null, null);
18077            if (installerPackageName != null) {
18078                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18079                        removedPackage, extras, 0 /*flags*/,
18080                        installerPackageName, null, null, null);
18081                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18082                        removedPackage, extras, 0 /*flags*/,
18083                        installerPackageName, null, null, null);
18084            }
18085        }
18086
18087        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18088            // Don't send static shared library removal broadcasts as these
18089            // libs are visible only the the apps that depend on them an one
18090            // cannot remove the library if it has a dependency.
18091            if (isStaticSharedLib) {
18092                return;
18093            }
18094            Bundle extras = new Bundle(2);
18095            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18096            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18097            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18098            if (isUpdate || isRemovedPackageSystemUpdate) {
18099                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18100            }
18101            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18102            if (removedPackage != null) {
18103                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18104                    removedPackage, extras, 0, null /*targetPackage*/, null,
18105                    broadcastUsers, instantUserIds);
18106                if (installerPackageName != null) {
18107                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18108                            removedPackage, extras, 0 /*flags*/,
18109                            installerPackageName, null, broadcastUsers, instantUserIds);
18110                }
18111                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18112                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18113                        removedPackage, extras,
18114                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18115                        null, null, broadcastUsers, instantUserIds);
18116                    packageSender.notifyPackageRemoved(removedPackage);
18117                }
18118            }
18119            if (removedAppId >= 0) {
18120                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18121                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18122                    null, null, broadcastUsers, instantUserIds);
18123            }
18124        }
18125
18126        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18127            removedUsers = userIds;
18128            if (removedUsers == null) {
18129                broadcastUsers = null;
18130                return;
18131            }
18132
18133            broadcastUsers = EMPTY_INT_ARRAY;
18134            instantUserIds = EMPTY_INT_ARRAY;
18135            for (int i = userIds.length - 1; i >= 0; --i) {
18136                final int userId = userIds[i];
18137                if (deletedPackageSetting.getInstantApp(userId)) {
18138                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18139                } else {
18140                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18141                }
18142            }
18143        }
18144    }
18145
18146    /*
18147     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18148     * flag is not set, the data directory is removed as well.
18149     * make sure this flag is set for partially installed apps. If not its meaningless to
18150     * delete a partially installed application.
18151     */
18152    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18153            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18154        String packageName = ps.name;
18155        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18156        // Retrieve object to delete permissions for shared user later on
18157        final PackageParser.Package deletedPkg;
18158        final PackageSetting deletedPs;
18159        // reader
18160        synchronized (mPackages) {
18161            deletedPkg = mPackages.get(packageName);
18162            deletedPs = mSettings.mPackages.get(packageName);
18163            if (outInfo != null) {
18164                outInfo.removedPackage = packageName;
18165                outInfo.installerPackageName = ps.installerPackageName;
18166                outInfo.isStaticSharedLib = deletedPkg != null
18167                        && deletedPkg.staticSharedLibName != null;
18168                outInfo.populateUsers(deletedPs == null ? null
18169                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18170            }
18171        }
18172
18173        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18174
18175        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18176            final PackageParser.Package resolvedPkg;
18177            if (deletedPkg != null) {
18178                resolvedPkg = deletedPkg;
18179            } else {
18180                // We don't have a parsed package when it lives on an ejected
18181                // adopted storage device, so fake something together
18182                resolvedPkg = new PackageParser.Package(ps.name);
18183                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18184            }
18185            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18186                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18187            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18188            if (outInfo != null) {
18189                outInfo.dataRemoved = true;
18190            }
18191            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18192        }
18193
18194        int removedAppId = -1;
18195
18196        // writer
18197        synchronized (mPackages) {
18198            boolean installedStateChanged = false;
18199            if (deletedPs != null) {
18200                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18201                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18202                    clearDefaultBrowserIfNeeded(packageName);
18203                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18204                    removedAppId = mSettings.removePackageLPw(packageName);
18205                    if (outInfo != null) {
18206                        outInfo.removedAppId = removedAppId;
18207                    }
18208                    mPermissionManager.updatePermissions(
18209                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18210                    if (deletedPs.sharedUser != null) {
18211                        // Remove permissions associated with package. Since runtime
18212                        // permissions are per user we have to kill the removed package
18213                        // or packages running under the shared user of the removed
18214                        // package if revoking the permissions requested only by the removed
18215                        // package is successful and this causes a change in gids.
18216                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18217                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18218                                    userId);
18219                            if (userIdToKill == UserHandle.USER_ALL
18220                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18221                                // If gids changed for this user, kill all affected packages.
18222                                mHandler.post(new Runnable() {
18223                                    @Override
18224                                    public void run() {
18225                                        // This has to happen with no lock held.
18226                                        killApplication(deletedPs.name, deletedPs.appId,
18227                                                KILL_APP_REASON_GIDS_CHANGED);
18228                                    }
18229                                });
18230                                break;
18231                            }
18232                        }
18233                    }
18234                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18235                }
18236                // make sure to preserve per-user disabled state if this removal was just
18237                // a downgrade of a system app to the factory package
18238                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18239                    if (DEBUG_REMOVE) {
18240                        Slog.d(TAG, "Propagating install state across downgrade");
18241                    }
18242                    for (int userId : allUserHandles) {
18243                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18244                        if (DEBUG_REMOVE) {
18245                            Slog.d(TAG, "    user " + userId + " => " + installed);
18246                        }
18247                        if (installed != ps.getInstalled(userId)) {
18248                            installedStateChanged = true;
18249                        }
18250                        ps.setInstalled(installed, userId);
18251                    }
18252                }
18253            }
18254            // can downgrade to reader
18255            if (writeSettings) {
18256                // Save settings now
18257                mSettings.writeLPr();
18258            }
18259            if (installedStateChanged) {
18260                mSettings.writeKernelMappingLPr(ps);
18261            }
18262        }
18263        if (removedAppId != -1) {
18264            // A user ID was deleted here. Go through all users and remove it
18265            // from KeyStore.
18266            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18267        }
18268    }
18269
18270    static boolean locationIsPrivileged(String path) {
18271        try {
18272            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18273            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18274            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18275            return path.startsWith(privilegedAppDir.getCanonicalPath())
18276                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18277                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18278        } catch (IOException e) {
18279            Slog.e(TAG, "Unable to access code path " + path);
18280        }
18281        return false;
18282    }
18283
18284    static boolean locationIsOem(String path) {
18285        try {
18286            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18287        } catch (IOException e) {
18288            Slog.e(TAG, "Unable to access code path " + path);
18289        }
18290        return false;
18291    }
18292
18293    static boolean locationIsVendor(String path) {
18294        try {
18295            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18296        } catch (IOException e) {
18297            Slog.e(TAG, "Unable to access code path " + path);
18298        }
18299        return false;
18300    }
18301
18302    static boolean locationIsProduct(String path) {
18303        try {
18304            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18305        } catch (IOException e) {
18306            Slog.e(TAG, "Unable to access code path " + path);
18307        }
18308        return false;
18309    }
18310
18311    /*
18312     * Tries to delete system package.
18313     */
18314    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18315            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18316            boolean writeSettings) {
18317        if (deletedPs.parentPackageName != null) {
18318            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18319            return false;
18320        }
18321
18322        final boolean applyUserRestrictions
18323                = (allUserHandles != null) && (outInfo.origUsers != null);
18324        final PackageSetting disabledPs;
18325        // Confirm if the system package has been updated
18326        // An updated system app can be deleted. This will also have to restore
18327        // the system pkg from system partition
18328        // reader
18329        synchronized (mPackages) {
18330            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18331        }
18332
18333        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18334                + " disabledPs=" + disabledPs);
18335
18336        if (disabledPs == null) {
18337            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18338            return false;
18339        } else if (DEBUG_REMOVE) {
18340            Slog.d(TAG, "Deleting system pkg from data partition");
18341        }
18342
18343        if (DEBUG_REMOVE) {
18344            if (applyUserRestrictions) {
18345                Slog.d(TAG, "Remembering install states:");
18346                for (int userId : allUserHandles) {
18347                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18348                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18349                }
18350            }
18351        }
18352
18353        // Delete the updated package
18354        outInfo.isRemovedPackageSystemUpdate = true;
18355        if (outInfo.removedChildPackages != null) {
18356            final int childCount = (deletedPs.childPackageNames != null)
18357                    ? deletedPs.childPackageNames.size() : 0;
18358            for (int i = 0; i < childCount; i++) {
18359                String childPackageName = deletedPs.childPackageNames.get(i);
18360                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18361                        .contains(childPackageName)) {
18362                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18363                            childPackageName);
18364                    if (childInfo != null) {
18365                        childInfo.isRemovedPackageSystemUpdate = true;
18366                    }
18367                }
18368            }
18369        }
18370
18371        if (disabledPs.versionCode < deletedPs.versionCode) {
18372            // Delete data for downgrades
18373            flags &= ~PackageManager.DELETE_KEEP_DATA;
18374        } else {
18375            // Preserve data by setting flag
18376            flags |= PackageManager.DELETE_KEEP_DATA;
18377        }
18378
18379        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18380                outInfo, writeSettings, disabledPs.pkg);
18381        if (!ret) {
18382            return false;
18383        }
18384
18385        // writer
18386        synchronized (mPackages) {
18387            // NOTE: The system package always needs to be enabled; even if it's for
18388            // a compressed stub. If we don't, installing the system package fails
18389            // during scan [scanning checks the disabled packages]. We will reverse
18390            // this later, after we've "installed" the stub.
18391            // Reinstate the old system package
18392            enableSystemPackageLPw(disabledPs.pkg);
18393            // Remove any native libraries from the upgraded package.
18394            removeNativeBinariesLI(deletedPs);
18395        }
18396
18397        // Install the system package
18398        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18399        try {
18400            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18401                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18402        } catch (PackageManagerException e) {
18403            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18404                    + e.getMessage());
18405            return false;
18406        } finally {
18407            if (disabledPs.pkg.isStub) {
18408                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18409            }
18410        }
18411        return true;
18412    }
18413
18414    /**
18415     * Installs a package that's already on the system partition.
18416     */
18417    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18418            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18419            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18420                    throws PackageManagerException {
18421        @ParseFlags int parseFlags =
18422                mDefParseFlags
18423                | PackageParser.PARSE_MUST_BE_APK
18424                | PackageParser.PARSE_IS_SYSTEM_DIR;
18425        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18426        if (isPrivileged || locationIsPrivileged(codePathString)) {
18427            scanFlags |= SCAN_AS_PRIVILEGED;
18428        }
18429        if (locationIsOem(codePathString)) {
18430            scanFlags |= SCAN_AS_OEM;
18431        }
18432        if (locationIsVendor(codePathString)) {
18433            scanFlags |= SCAN_AS_VENDOR;
18434        }
18435        if (locationIsProduct(codePathString)) {
18436            scanFlags |= SCAN_AS_PRODUCT;
18437        }
18438
18439        final File codePath = new File(codePathString);
18440        final PackageParser.Package pkg =
18441                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18442
18443        try {
18444            // update shared libraries for the newly re-installed system package
18445            updateSharedLibrariesLPr(pkg, null);
18446        } catch (PackageManagerException e) {
18447            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18448        }
18449
18450        prepareAppDataAfterInstallLIF(pkg);
18451
18452        // writer
18453        synchronized (mPackages) {
18454            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18455
18456            // Propagate the permissions state as we do not want to drop on the floor
18457            // runtime permissions. The update permissions method below will take
18458            // care of removing obsolete permissions and grant install permissions.
18459            if (origPermissionState != null) {
18460                ps.getPermissionsState().copyFrom(origPermissionState);
18461            }
18462            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18463                    mPermissionCallback);
18464
18465            final boolean applyUserRestrictions
18466                    = (allUserHandles != null) && (origUserHandles != null);
18467            if (applyUserRestrictions) {
18468                boolean installedStateChanged = false;
18469                if (DEBUG_REMOVE) {
18470                    Slog.d(TAG, "Propagating install state across reinstall");
18471                }
18472                for (int userId : allUserHandles) {
18473                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18474                    if (DEBUG_REMOVE) {
18475                        Slog.d(TAG, "    user " + userId + " => " + installed);
18476                    }
18477                    if (installed != ps.getInstalled(userId)) {
18478                        installedStateChanged = true;
18479                    }
18480                    ps.setInstalled(installed, userId);
18481
18482                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18483                }
18484                // Regardless of writeSettings we need to ensure that this restriction
18485                // state propagation is persisted
18486                mSettings.writeAllUsersPackageRestrictionsLPr();
18487                if (installedStateChanged) {
18488                    mSettings.writeKernelMappingLPr(ps);
18489                }
18490            }
18491            // can downgrade to reader here
18492            if (writeSettings) {
18493                mSettings.writeLPr();
18494            }
18495        }
18496        return pkg;
18497    }
18498
18499    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18500            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18501            PackageRemovedInfo outInfo, boolean writeSettings,
18502            PackageParser.Package replacingPackage) {
18503        synchronized (mPackages) {
18504            if (outInfo != null) {
18505                outInfo.uid = ps.appId;
18506            }
18507
18508            if (outInfo != null && outInfo.removedChildPackages != null) {
18509                final int childCount = (ps.childPackageNames != null)
18510                        ? ps.childPackageNames.size() : 0;
18511                for (int i = 0; i < childCount; i++) {
18512                    String childPackageName = ps.childPackageNames.get(i);
18513                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18514                    if (childPs == null) {
18515                        return false;
18516                    }
18517                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18518                            childPackageName);
18519                    if (childInfo != null) {
18520                        childInfo.uid = childPs.appId;
18521                    }
18522                }
18523            }
18524        }
18525
18526        // Delete package data from internal structures and also remove data if flag is set
18527        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18528
18529        // Delete the child packages data
18530        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18531        for (int i = 0; i < childCount; i++) {
18532            PackageSetting childPs;
18533            synchronized (mPackages) {
18534                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18535            }
18536            if (childPs != null) {
18537                PackageRemovedInfo childOutInfo = (outInfo != null
18538                        && outInfo.removedChildPackages != null)
18539                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18540                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18541                        && (replacingPackage != null
18542                        && !replacingPackage.hasChildPackage(childPs.name))
18543                        ? flags & ~DELETE_KEEP_DATA : flags;
18544                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18545                        deleteFlags, writeSettings);
18546            }
18547        }
18548
18549        // Delete application code and resources only for parent packages
18550        if (ps.parentPackageName == null) {
18551            if (deleteCodeAndResources && (outInfo != null)) {
18552                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18553                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18554                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18555            }
18556        }
18557
18558        return true;
18559    }
18560
18561    @Override
18562    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18563            int userId) {
18564        mContext.enforceCallingOrSelfPermission(
18565                android.Manifest.permission.DELETE_PACKAGES, null);
18566        synchronized (mPackages) {
18567            // Cannot block uninstall of static shared libs as they are
18568            // considered a part of the using app (emulating static linking).
18569            // Also static libs are installed always on internal storage.
18570            PackageParser.Package pkg = mPackages.get(packageName);
18571            if (pkg != null && pkg.staticSharedLibName != null) {
18572                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18573                        + " providing static shared library: " + pkg.staticSharedLibName);
18574                return false;
18575            }
18576            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18577            mSettings.writePackageRestrictionsLPr(userId);
18578        }
18579        return true;
18580    }
18581
18582    @Override
18583    public boolean getBlockUninstallForUser(String packageName, int userId) {
18584        synchronized (mPackages) {
18585            final PackageSetting ps = mSettings.mPackages.get(packageName);
18586            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18587                return false;
18588            }
18589            return mSettings.getBlockUninstallLPr(userId, packageName);
18590        }
18591    }
18592
18593    @Override
18594    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18595        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18596        synchronized (mPackages) {
18597            PackageSetting ps = mSettings.mPackages.get(packageName);
18598            if (ps == null) {
18599                Log.w(TAG, "Package doesn't exist: " + packageName);
18600                return false;
18601            }
18602            if (systemUserApp) {
18603                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18604            } else {
18605                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18606            }
18607            mSettings.writeLPr();
18608        }
18609        return true;
18610    }
18611
18612    /*
18613     * This method handles package deletion in general
18614     */
18615    private boolean deletePackageLIF(String packageName, UserHandle user,
18616            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18617            PackageRemovedInfo outInfo, boolean writeSettings,
18618            PackageParser.Package replacingPackage) {
18619        if (packageName == null) {
18620            Slog.w(TAG, "Attempt to delete null packageName.");
18621            return false;
18622        }
18623
18624        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18625
18626        PackageSetting ps;
18627        synchronized (mPackages) {
18628            ps = mSettings.mPackages.get(packageName);
18629            if (ps == null) {
18630                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18631                return false;
18632            }
18633
18634            if (ps.parentPackageName != null && (!isSystemApp(ps)
18635                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18636                if (DEBUG_REMOVE) {
18637                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18638                            + ((user == null) ? UserHandle.USER_ALL : user));
18639                }
18640                final int removedUserId = (user != null) ? user.getIdentifier()
18641                        : UserHandle.USER_ALL;
18642                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18643                    return false;
18644                }
18645                markPackageUninstalledForUserLPw(ps, user);
18646                scheduleWritePackageRestrictionsLocked(user);
18647                return true;
18648            }
18649        }
18650
18651        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18652                && user.getIdentifier() != UserHandle.USER_ALL)) {
18653            // The caller is asking that the package only be deleted for a single
18654            // user.  To do this, we just mark its uninstalled state and delete
18655            // its data. If this is a system app, we only allow this to happen if
18656            // they have set the special DELETE_SYSTEM_APP which requests different
18657            // semantics than normal for uninstalling system apps.
18658            markPackageUninstalledForUserLPw(ps, user);
18659
18660            if (!isSystemApp(ps)) {
18661                // Do not uninstall the APK if an app should be cached
18662                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18663                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18664                    // Other user still have this package installed, so all
18665                    // we need to do is clear this user's data and save that
18666                    // it is uninstalled.
18667                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18668                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18669                        return false;
18670                    }
18671                    scheduleWritePackageRestrictionsLocked(user);
18672                    return true;
18673                } else {
18674                    // We need to set it back to 'installed' so the uninstall
18675                    // broadcasts will be sent correctly.
18676                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18677                    ps.setInstalled(true, user.getIdentifier());
18678                    mSettings.writeKernelMappingLPr(ps);
18679                }
18680            } else {
18681                // This is a system app, so we assume that the
18682                // other users still have this package installed, so all
18683                // we need to do is clear this user's data and save that
18684                // it is uninstalled.
18685                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18686                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18687                    return false;
18688                }
18689                scheduleWritePackageRestrictionsLocked(user);
18690                return true;
18691            }
18692        }
18693
18694        // If we are deleting a composite package for all users, keep track
18695        // of result for each child.
18696        if (ps.childPackageNames != null && outInfo != null) {
18697            synchronized (mPackages) {
18698                final int childCount = ps.childPackageNames.size();
18699                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18700                for (int i = 0; i < childCount; i++) {
18701                    String childPackageName = ps.childPackageNames.get(i);
18702                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18703                    childInfo.removedPackage = childPackageName;
18704                    childInfo.installerPackageName = ps.installerPackageName;
18705                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18706                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18707                    if (childPs != null) {
18708                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18709                    }
18710                }
18711            }
18712        }
18713
18714        boolean ret = false;
18715        if (isSystemApp(ps)) {
18716            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18717            // When an updated system application is deleted we delete the existing resources
18718            // as well and fall back to existing code in system partition
18719            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18720        } else {
18721            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18722            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18723                    outInfo, writeSettings, replacingPackage);
18724        }
18725
18726        // Take a note whether we deleted the package for all users
18727        if (outInfo != null) {
18728            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18729            if (outInfo.removedChildPackages != null) {
18730                synchronized (mPackages) {
18731                    final int childCount = outInfo.removedChildPackages.size();
18732                    for (int i = 0; i < childCount; i++) {
18733                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18734                        if (childInfo != null) {
18735                            childInfo.removedForAllUsers = mPackages.get(
18736                                    childInfo.removedPackage) == null;
18737                        }
18738                    }
18739                }
18740            }
18741            // If we uninstalled an update to a system app there may be some
18742            // child packages that appeared as they are declared in the system
18743            // app but were not declared in the update.
18744            if (isSystemApp(ps)) {
18745                synchronized (mPackages) {
18746                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18747                    final int childCount = (updatedPs.childPackageNames != null)
18748                            ? updatedPs.childPackageNames.size() : 0;
18749                    for (int i = 0; i < childCount; i++) {
18750                        String childPackageName = updatedPs.childPackageNames.get(i);
18751                        if (outInfo.removedChildPackages == null
18752                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18753                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18754                            if (childPs == null) {
18755                                continue;
18756                            }
18757                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18758                            installRes.name = childPackageName;
18759                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18760                            installRes.pkg = mPackages.get(childPackageName);
18761                            installRes.uid = childPs.pkg.applicationInfo.uid;
18762                            if (outInfo.appearedChildPackages == null) {
18763                                outInfo.appearedChildPackages = new ArrayMap<>();
18764                            }
18765                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18766                        }
18767                    }
18768                }
18769            }
18770        }
18771
18772        return ret;
18773    }
18774
18775    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18776        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18777                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18778        for (int nextUserId : userIds) {
18779            if (DEBUG_REMOVE) {
18780                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18781            }
18782            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18783                    false /*installed*/,
18784                    true /*stopped*/,
18785                    true /*notLaunched*/,
18786                    false /*hidden*/,
18787                    false /*suspended*/,
18788                    false /*instantApp*/,
18789                    false /*virtualPreload*/,
18790                    null /*lastDisableAppCaller*/,
18791                    null /*enabledComponents*/,
18792                    null /*disabledComponents*/,
18793                    ps.readUserState(nextUserId).domainVerificationStatus,
18794                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18795                    null /*harmfulAppWarning*/);
18796        }
18797        mSettings.writeKernelMappingLPr(ps);
18798    }
18799
18800    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18801            PackageRemovedInfo outInfo) {
18802        final PackageParser.Package pkg;
18803        synchronized (mPackages) {
18804            pkg = mPackages.get(ps.name);
18805        }
18806
18807        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18808                : new int[] {userId};
18809        for (int nextUserId : userIds) {
18810            if (DEBUG_REMOVE) {
18811                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18812                        + nextUserId);
18813            }
18814
18815            destroyAppDataLIF(pkg, userId,
18816                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18817            destroyAppProfilesLIF(pkg, userId);
18818            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18819            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18820            schedulePackageCleaning(ps.name, nextUserId, false);
18821            synchronized (mPackages) {
18822                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18823                    scheduleWritePackageRestrictionsLocked(nextUserId);
18824                }
18825                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18826            }
18827        }
18828
18829        if (outInfo != null) {
18830            outInfo.removedPackage = ps.name;
18831            outInfo.installerPackageName = ps.installerPackageName;
18832            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18833            outInfo.removedAppId = ps.appId;
18834            outInfo.removedUsers = userIds;
18835            outInfo.broadcastUsers = userIds;
18836        }
18837
18838        return true;
18839    }
18840
18841    private final class ClearStorageConnection implements ServiceConnection {
18842        IMediaContainerService mContainerService;
18843
18844        @Override
18845        public void onServiceConnected(ComponentName name, IBinder service) {
18846            synchronized (this) {
18847                mContainerService = IMediaContainerService.Stub
18848                        .asInterface(Binder.allowBlocking(service));
18849                notifyAll();
18850            }
18851        }
18852
18853        @Override
18854        public void onServiceDisconnected(ComponentName name) {
18855        }
18856    }
18857
18858    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18859        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18860
18861        final boolean mounted;
18862        if (Environment.isExternalStorageEmulated()) {
18863            mounted = true;
18864        } else {
18865            final String status = Environment.getExternalStorageState();
18866
18867            mounted = status.equals(Environment.MEDIA_MOUNTED)
18868                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18869        }
18870
18871        if (!mounted) {
18872            return;
18873        }
18874
18875        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18876        int[] users;
18877        if (userId == UserHandle.USER_ALL) {
18878            users = sUserManager.getUserIds();
18879        } else {
18880            users = new int[] { userId };
18881        }
18882        final ClearStorageConnection conn = new ClearStorageConnection();
18883        if (mContext.bindServiceAsUser(
18884                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18885            try {
18886                for (int curUser : users) {
18887                    long timeout = SystemClock.uptimeMillis() + 5000;
18888                    synchronized (conn) {
18889                        long now;
18890                        while (conn.mContainerService == null &&
18891                                (now = SystemClock.uptimeMillis()) < timeout) {
18892                            try {
18893                                conn.wait(timeout - now);
18894                            } catch (InterruptedException e) {
18895                            }
18896                        }
18897                    }
18898                    if (conn.mContainerService == null) {
18899                        return;
18900                    }
18901
18902                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18903                    clearDirectory(conn.mContainerService,
18904                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18905                    if (allData) {
18906                        clearDirectory(conn.mContainerService,
18907                                userEnv.buildExternalStorageAppDataDirs(packageName));
18908                        clearDirectory(conn.mContainerService,
18909                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18910                    }
18911                }
18912            } finally {
18913                mContext.unbindService(conn);
18914            }
18915        }
18916    }
18917
18918    @Override
18919    public void clearApplicationProfileData(String packageName) {
18920        enforceSystemOrRoot("Only the system can clear all profile data");
18921
18922        final PackageParser.Package pkg;
18923        synchronized (mPackages) {
18924            pkg = mPackages.get(packageName);
18925        }
18926
18927        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18928            synchronized (mInstallLock) {
18929                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18930            }
18931        }
18932    }
18933
18934    @Override
18935    public void clearApplicationUserData(final String packageName,
18936            final IPackageDataObserver observer, final int userId) {
18937        mContext.enforceCallingOrSelfPermission(
18938                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18939
18940        final int callingUid = Binder.getCallingUid();
18941        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18942                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18943
18944        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18945        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18946        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18947            throw new SecurityException("Cannot clear data for a protected package: "
18948                    + packageName);
18949        }
18950        // Queue up an async operation since the package deletion may take a little while.
18951        mHandler.post(new Runnable() {
18952            public void run() {
18953                mHandler.removeCallbacks(this);
18954                final boolean succeeded;
18955                if (!filterApp) {
18956                    try (PackageFreezer freezer = freezePackage(packageName,
18957                            "clearApplicationUserData")) {
18958                        synchronized (mInstallLock) {
18959                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18960                        }
18961                        clearExternalStorageDataSync(packageName, userId, true);
18962                        synchronized (mPackages) {
18963                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18964                                    packageName, userId);
18965                        }
18966                    }
18967                    if (succeeded) {
18968                        // invoke DeviceStorageMonitor's update method to clear any notifications
18969                        DeviceStorageMonitorInternal dsm = LocalServices
18970                                .getService(DeviceStorageMonitorInternal.class);
18971                        if (dsm != null) {
18972                            dsm.checkMemory();
18973                        }
18974                    }
18975                } else {
18976                    succeeded = false;
18977                }
18978                if (observer != null) {
18979                    try {
18980                        observer.onRemoveCompleted(packageName, succeeded);
18981                    } catch (RemoteException e) {
18982                        Log.i(TAG, "Observer no longer exists.");
18983                    }
18984                } //end if observer
18985            } //end run
18986        });
18987    }
18988
18989    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18990        if (packageName == null) {
18991            Slog.w(TAG, "Attempt to delete null packageName.");
18992            return false;
18993        }
18994
18995        // Try finding details about the requested package
18996        PackageParser.Package pkg;
18997        synchronized (mPackages) {
18998            pkg = mPackages.get(packageName);
18999            if (pkg == null) {
19000                final PackageSetting ps = mSettings.mPackages.get(packageName);
19001                if (ps != null) {
19002                    pkg = ps.pkg;
19003                }
19004            }
19005
19006            if (pkg == null) {
19007                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19008                return false;
19009            }
19010
19011            PackageSetting ps = (PackageSetting) pkg.mExtras;
19012            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19013        }
19014
19015        clearAppDataLIF(pkg, userId,
19016                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19017
19018        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19019        removeKeystoreDataIfNeeded(userId, appId);
19020
19021        UserManagerInternal umInternal = getUserManagerInternal();
19022        final int flags;
19023        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19024            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19025        } else if (umInternal.isUserRunning(userId)) {
19026            flags = StorageManager.FLAG_STORAGE_DE;
19027        } else {
19028            flags = 0;
19029        }
19030        prepareAppDataContentsLIF(pkg, userId, flags);
19031
19032        return true;
19033    }
19034
19035    /**
19036     * Reverts user permission state changes (permissions and flags) in
19037     * all packages for a given user.
19038     *
19039     * @param userId The device user for which to do a reset.
19040     */
19041    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19042        final int packageCount = mPackages.size();
19043        for (int i = 0; i < packageCount; i++) {
19044            PackageParser.Package pkg = mPackages.valueAt(i);
19045            PackageSetting ps = (PackageSetting) pkg.mExtras;
19046            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19047        }
19048    }
19049
19050    private void resetNetworkPolicies(int userId) {
19051        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19052    }
19053
19054    /**
19055     * Reverts user permission state changes (permissions and flags).
19056     *
19057     * @param ps The package for which to reset.
19058     * @param userId The device user for which to do a reset.
19059     */
19060    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19061            final PackageSetting ps, final int userId) {
19062        if (ps.pkg == null) {
19063            return;
19064        }
19065
19066        // These are flags that can change base on user actions.
19067        final int userSettableMask = FLAG_PERMISSION_USER_SET
19068                | FLAG_PERMISSION_USER_FIXED
19069                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19070                | FLAG_PERMISSION_REVIEW_REQUIRED;
19071
19072        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19073                | FLAG_PERMISSION_POLICY_FIXED;
19074
19075        boolean writeInstallPermissions = false;
19076        boolean writeRuntimePermissions = false;
19077
19078        final int permissionCount = ps.pkg.requestedPermissions.size();
19079        for (int i = 0; i < permissionCount; i++) {
19080            final String permName = ps.pkg.requestedPermissions.get(i);
19081            final BasePermission bp =
19082                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19083            if (bp == null) {
19084                continue;
19085            }
19086
19087            // If shared user we just reset the state to which only this app contributed.
19088            if (ps.sharedUser != null) {
19089                boolean used = false;
19090                final int packageCount = ps.sharedUser.packages.size();
19091                for (int j = 0; j < packageCount; j++) {
19092                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19093                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19094                            && pkg.pkg.requestedPermissions.contains(permName)) {
19095                        used = true;
19096                        break;
19097                    }
19098                }
19099                if (used) {
19100                    continue;
19101                }
19102            }
19103
19104            final PermissionsState permissionsState = ps.getPermissionsState();
19105
19106            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19107
19108            // Always clear the user settable flags.
19109            final boolean hasInstallState =
19110                    permissionsState.getInstallPermissionState(permName) != null;
19111            // If permission review is enabled and this is a legacy app, mark the
19112            // permission as requiring a review as this is the initial state.
19113            int flags = 0;
19114            if (mSettings.mPermissions.mPermissionReviewRequired
19115                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19116                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19117            }
19118            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19119                if (hasInstallState) {
19120                    writeInstallPermissions = true;
19121                } else {
19122                    writeRuntimePermissions = true;
19123                }
19124            }
19125
19126            // Below is only runtime permission handling.
19127            if (!bp.isRuntime()) {
19128                continue;
19129            }
19130
19131            // Never clobber system or policy.
19132            if ((oldFlags & policyOrSystemFlags) != 0) {
19133                continue;
19134            }
19135
19136            // If this permission was granted by default, make sure it is.
19137            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19138                if (permissionsState.grantRuntimePermission(bp, userId)
19139                        != PERMISSION_OPERATION_FAILURE) {
19140                    writeRuntimePermissions = true;
19141                }
19142            // If permission review is enabled the permissions for a legacy apps
19143            // are represented as constantly granted runtime ones, so don't revoke.
19144            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19145                // Otherwise, reset the permission.
19146                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19147                switch (revokeResult) {
19148                    case PERMISSION_OPERATION_SUCCESS:
19149                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19150                        writeRuntimePermissions = true;
19151                        final int appId = ps.appId;
19152                        mHandler.post(new Runnable() {
19153                            @Override
19154                            public void run() {
19155                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19156                            }
19157                        });
19158                    } break;
19159                }
19160            }
19161        }
19162
19163        // Synchronously write as we are taking permissions away.
19164        if (writeRuntimePermissions) {
19165            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19166        }
19167
19168        // Synchronously write as we are taking permissions away.
19169        if (writeInstallPermissions) {
19170            mSettings.writeLPr();
19171        }
19172    }
19173
19174    /**
19175     * Remove entries from the keystore daemon. Will only remove it if the
19176     * {@code appId} is valid.
19177     */
19178    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19179        if (appId < 0) {
19180            return;
19181        }
19182
19183        final KeyStore keyStore = KeyStore.getInstance();
19184        if (keyStore != null) {
19185            if (userId == UserHandle.USER_ALL) {
19186                for (final int individual : sUserManager.getUserIds()) {
19187                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19188                }
19189            } else {
19190                keyStore.clearUid(UserHandle.getUid(userId, appId));
19191            }
19192        } else {
19193            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19194        }
19195    }
19196
19197    @Override
19198    public void deleteApplicationCacheFiles(final String packageName,
19199            final IPackageDataObserver observer) {
19200        final int userId = UserHandle.getCallingUserId();
19201        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19202    }
19203
19204    @Override
19205    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19206            final IPackageDataObserver observer) {
19207        final int callingUid = Binder.getCallingUid();
19208        mContext.enforceCallingOrSelfPermission(
19209                android.Manifest.permission.DELETE_CACHE_FILES, null);
19210        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19211                /* requireFullPermission= */ true, /* checkShell= */ false,
19212                "delete application cache files");
19213        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19214                android.Manifest.permission.ACCESS_INSTANT_APPS);
19215
19216        final PackageParser.Package pkg;
19217        synchronized (mPackages) {
19218            pkg = mPackages.get(packageName);
19219        }
19220
19221        // Queue up an async operation since the package deletion may take a little while.
19222        mHandler.post(new Runnable() {
19223            public void run() {
19224                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19225                boolean doClearData = true;
19226                if (ps != null) {
19227                    final boolean targetIsInstantApp =
19228                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19229                    doClearData = !targetIsInstantApp
19230                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19231                }
19232                if (doClearData) {
19233                    synchronized (mInstallLock) {
19234                        final int flags = StorageManager.FLAG_STORAGE_DE
19235                                | StorageManager.FLAG_STORAGE_CE;
19236                        // We're only clearing cache files, so we don't care if the
19237                        // app is unfrozen and still able to run
19238                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19239                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19240                    }
19241                    clearExternalStorageDataSync(packageName, userId, false);
19242                }
19243                if (observer != null) {
19244                    try {
19245                        observer.onRemoveCompleted(packageName, true);
19246                    } catch (RemoteException e) {
19247                        Log.i(TAG, "Observer no longer exists.");
19248                    }
19249                }
19250            }
19251        });
19252    }
19253
19254    @Override
19255    public void getPackageSizeInfo(final String packageName, int userHandle,
19256            final IPackageStatsObserver observer) {
19257        throw new UnsupportedOperationException(
19258                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19259    }
19260
19261    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19262        final PackageSetting ps;
19263        synchronized (mPackages) {
19264            ps = mSettings.mPackages.get(packageName);
19265            if (ps == null) {
19266                Slog.w(TAG, "Failed to find settings for " + packageName);
19267                return false;
19268            }
19269        }
19270
19271        final String[] packageNames = { packageName };
19272        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19273        final String[] codePaths = { ps.codePathString };
19274
19275        try {
19276            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19277                    ps.appId, ceDataInodes, codePaths, stats);
19278
19279            // For now, ignore code size of packages on system partition
19280            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19281                stats.codeSize = 0;
19282            }
19283
19284            // External clients expect these to be tracked separately
19285            stats.dataSize -= stats.cacheSize;
19286
19287        } catch (InstallerException e) {
19288            Slog.w(TAG, String.valueOf(e));
19289            return false;
19290        }
19291
19292        return true;
19293    }
19294
19295    private int getUidTargetSdkVersionLockedLPr(int uid) {
19296        Object obj = mSettings.getUserIdLPr(uid);
19297        if (obj instanceof SharedUserSetting) {
19298            final SharedUserSetting sus = (SharedUserSetting) obj;
19299            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19300            final Iterator<PackageSetting> it = sus.packages.iterator();
19301            while (it.hasNext()) {
19302                final PackageSetting ps = it.next();
19303                if (ps.pkg != null) {
19304                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19305                    if (v < vers) vers = v;
19306                }
19307            }
19308            return vers;
19309        } else if (obj instanceof PackageSetting) {
19310            final PackageSetting ps = (PackageSetting) obj;
19311            if (ps.pkg != null) {
19312                return ps.pkg.applicationInfo.targetSdkVersion;
19313            }
19314        }
19315        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19316    }
19317
19318    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19319        final PackageParser.Package p = mPackages.get(packageName);
19320        if (p != null) {
19321            return p.applicationInfo.targetSdkVersion;
19322        }
19323        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19324    }
19325
19326    @Override
19327    public void addPreferredActivity(IntentFilter filter, int match,
19328            ComponentName[] set, ComponentName activity, int userId) {
19329        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19330                "Adding preferred");
19331    }
19332
19333    private void addPreferredActivityInternal(IntentFilter filter, int match,
19334            ComponentName[] set, ComponentName activity, boolean always, int userId,
19335            String opname) {
19336        // writer
19337        int callingUid = Binder.getCallingUid();
19338        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19339                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19340        if (filter.countActions() == 0) {
19341            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19342            return;
19343        }
19344        synchronized (mPackages) {
19345            if (mContext.checkCallingOrSelfPermission(
19346                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19347                    != PackageManager.PERMISSION_GRANTED) {
19348                if (getUidTargetSdkVersionLockedLPr(callingUid)
19349                        < Build.VERSION_CODES.FROYO) {
19350                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19351                            + callingUid);
19352                    return;
19353                }
19354                mContext.enforceCallingOrSelfPermission(
19355                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19356            }
19357
19358            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19359            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19360                    + userId + ":");
19361            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19362            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19363            scheduleWritePackageRestrictionsLocked(userId);
19364            postPreferredActivityChangedBroadcast(userId);
19365        }
19366    }
19367
19368    private void postPreferredActivityChangedBroadcast(int userId) {
19369        mHandler.post(() -> {
19370            final IActivityManager am = ActivityManager.getService();
19371            if (am == null) {
19372                return;
19373            }
19374
19375            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19376            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19377            try {
19378                am.broadcastIntent(null, intent, null, null,
19379                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19380                        null, false, false, userId);
19381            } catch (RemoteException e) {
19382            }
19383        });
19384    }
19385
19386    @Override
19387    public void replacePreferredActivity(IntentFilter filter, int match,
19388            ComponentName[] set, ComponentName activity, int userId) {
19389        if (filter.countActions() != 1) {
19390            throw new IllegalArgumentException(
19391                    "replacePreferredActivity expects filter to have only 1 action.");
19392        }
19393        if (filter.countDataAuthorities() != 0
19394                || filter.countDataPaths() != 0
19395                || filter.countDataSchemes() > 1
19396                || filter.countDataTypes() != 0) {
19397            throw new IllegalArgumentException(
19398                    "replacePreferredActivity expects filter to have no data authorities, " +
19399                    "paths, or types; and at most one scheme.");
19400        }
19401
19402        final int callingUid = Binder.getCallingUid();
19403        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19404                true /* requireFullPermission */, false /* checkShell */,
19405                "replace preferred activity");
19406        synchronized (mPackages) {
19407            if (mContext.checkCallingOrSelfPermission(
19408                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19409                    != PackageManager.PERMISSION_GRANTED) {
19410                if (getUidTargetSdkVersionLockedLPr(callingUid)
19411                        < Build.VERSION_CODES.FROYO) {
19412                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19413                            + Binder.getCallingUid());
19414                    return;
19415                }
19416                mContext.enforceCallingOrSelfPermission(
19417                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19418            }
19419
19420            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19421            if (pir != null) {
19422                // Get all of the existing entries that exactly match this filter.
19423                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19424                if (existing != null && existing.size() == 1) {
19425                    PreferredActivity cur = existing.get(0);
19426                    if (DEBUG_PREFERRED) {
19427                        Slog.i(TAG, "Checking replace of preferred:");
19428                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19429                        if (!cur.mPref.mAlways) {
19430                            Slog.i(TAG, "  -- CUR; not mAlways!");
19431                        } else {
19432                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19433                            Slog.i(TAG, "  -- CUR: mSet="
19434                                    + Arrays.toString(cur.mPref.mSetComponents));
19435                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19436                            Slog.i(TAG, "  -- NEW: mMatch="
19437                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19438                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19439                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19440                        }
19441                    }
19442                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19443                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19444                            && cur.mPref.sameSet(set)) {
19445                        // Setting the preferred activity to what it happens to be already
19446                        if (DEBUG_PREFERRED) {
19447                            Slog.i(TAG, "Replacing with same preferred activity "
19448                                    + cur.mPref.mShortComponent + " for user "
19449                                    + userId + ":");
19450                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19451                        }
19452                        return;
19453                    }
19454                }
19455
19456                if (existing != null) {
19457                    if (DEBUG_PREFERRED) {
19458                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19459                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19460                    }
19461                    for (int i = 0; i < existing.size(); i++) {
19462                        PreferredActivity pa = existing.get(i);
19463                        if (DEBUG_PREFERRED) {
19464                            Slog.i(TAG, "Removing existing preferred activity "
19465                                    + pa.mPref.mComponent + ":");
19466                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19467                        }
19468                        pir.removeFilter(pa);
19469                    }
19470                }
19471            }
19472            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19473                    "Replacing preferred");
19474        }
19475    }
19476
19477    @Override
19478    public void clearPackagePreferredActivities(String packageName) {
19479        final int callingUid = Binder.getCallingUid();
19480        if (getInstantAppPackageName(callingUid) != null) {
19481            return;
19482        }
19483        // writer
19484        synchronized (mPackages) {
19485            PackageParser.Package pkg = mPackages.get(packageName);
19486            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19487                if (mContext.checkCallingOrSelfPermission(
19488                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19489                        != PackageManager.PERMISSION_GRANTED) {
19490                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19491                            < Build.VERSION_CODES.FROYO) {
19492                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19493                                + callingUid);
19494                        return;
19495                    }
19496                    mContext.enforceCallingOrSelfPermission(
19497                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19498                }
19499            }
19500            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19501            if (ps != null
19502                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19503                return;
19504            }
19505            int user = UserHandle.getCallingUserId();
19506            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19507                scheduleWritePackageRestrictionsLocked(user);
19508            }
19509        }
19510    }
19511
19512    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19513    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19514        ArrayList<PreferredActivity> removed = null;
19515        boolean changed = false;
19516        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19517            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19518            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19519            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19520                continue;
19521            }
19522            Iterator<PreferredActivity> it = pir.filterIterator();
19523            while (it.hasNext()) {
19524                PreferredActivity pa = it.next();
19525                // Mark entry for removal only if it matches the package name
19526                // and the entry is of type "always".
19527                if (packageName == null ||
19528                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19529                                && pa.mPref.mAlways)) {
19530                    if (removed == null) {
19531                        removed = new ArrayList<PreferredActivity>();
19532                    }
19533                    removed.add(pa);
19534                }
19535            }
19536            if (removed != null) {
19537                for (int j=0; j<removed.size(); j++) {
19538                    PreferredActivity pa = removed.get(j);
19539                    pir.removeFilter(pa);
19540                }
19541                changed = true;
19542            }
19543        }
19544        if (changed) {
19545            postPreferredActivityChangedBroadcast(userId);
19546        }
19547        return changed;
19548    }
19549
19550    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19551    private void clearIntentFilterVerificationsLPw(int userId) {
19552        final int packageCount = mPackages.size();
19553        for (int i = 0; i < packageCount; i++) {
19554            PackageParser.Package pkg = mPackages.valueAt(i);
19555            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19556        }
19557    }
19558
19559    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19560    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19561        if (userId == UserHandle.USER_ALL) {
19562            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19563                    sUserManager.getUserIds())) {
19564                for (int oneUserId : sUserManager.getUserIds()) {
19565                    scheduleWritePackageRestrictionsLocked(oneUserId);
19566                }
19567            }
19568        } else {
19569            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19570                scheduleWritePackageRestrictionsLocked(userId);
19571            }
19572        }
19573    }
19574
19575    /** Clears state for all users, and touches intent filter verification policy */
19576    void clearDefaultBrowserIfNeeded(String packageName) {
19577        for (int oneUserId : sUserManager.getUserIds()) {
19578            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19579        }
19580    }
19581
19582    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19583        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19584        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19585            if (packageName.equals(defaultBrowserPackageName)) {
19586                setDefaultBrowserPackageName(null, userId);
19587            }
19588        }
19589    }
19590
19591    @Override
19592    public void resetApplicationPreferences(int userId) {
19593        mContext.enforceCallingOrSelfPermission(
19594                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19595        final long identity = Binder.clearCallingIdentity();
19596        // writer
19597        try {
19598            synchronized (mPackages) {
19599                clearPackagePreferredActivitiesLPw(null, userId);
19600                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19601                // TODO: We have to reset the default SMS and Phone. This requires
19602                // significant refactoring to keep all default apps in the package
19603                // manager (cleaner but more work) or have the services provide
19604                // callbacks to the package manager to request a default app reset.
19605                applyFactoryDefaultBrowserLPw(userId);
19606                clearIntentFilterVerificationsLPw(userId);
19607                primeDomainVerificationsLPw(userId);
19608                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19609                scheduleWritePackageRestrictionsLocked(userId);
19610            }
19611            resetNetworkPolicies(userId);
19612        } finally {
19613            Binder.restoreCallingIdentity(identity);
19614        }
19615    }
19616
19617    @Override
19618    public int getPreferredActivities(List<IntentFilter> outFilters,
19619            List<ComponentName> outActivities, String packageName) {
19620        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19621            return 0;
19622        }
19623        int num = 0;
19624        final int userId = UserHandle.getCallingUserId();
19625        // reader
19626        synchronized (mPackages) {
19627            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19628            if (pir != null) {
19629                final Iterator<PreferredActivity> it = pir.filterIterator();
19630                while (it.hasNext()) {
19631                    final PreferredActivity pa = it.next();
19632                    if (packageName == null
19633                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19634                                    && pa.mPref.mAlways)) {
19635                        if (outFilters != null) {
19636                            outFilters.add(new IntentFilter(pa));
19637                        }
19638                        if (outActivities != null) {
19639                            outActivities.add(pa.mPref.mComponent);
19640                        }
19641                    }
19642                }
19643            }
19644        }
19645
19646        return num;
19647    }
19648
19649    @Override
19650    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19651            int userId) {
19652        int callingUid = Binder.getCallingUid();
19653        if (callingUid != Process.SYSTEM_UID) {
19654            throw new SecurityException(
19655                    "addPersistentPreferredActivity can only be run by the system");
19656        }
19657        if (filter.countActions() == 0) {
19658            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19659            return;
19660        }
19661        synchronized (mPackages) {
19662            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19663                    ":");
19664            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19665            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19666                    new PersistentPreferredActivity(filter, activity));
19667            scheduleWritePackageRestrictionsLocked(userId);
19668            postPreferredActivityChangedBroadcast(userId);
19669        }
19670    }
19671
19672    @Override
19673    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19674        int callingUid = Binder.getCallingUid();
19675        if (callingUid != Process.SYSTEM_UID) {
19676            throw new SecurityException(
19677                    "clearPackagePersistentPreferredActivities can only be run by the system");
19678        }
19679        ArrayList<PersistentPreferredActivity> removed = null;
19680        boolean changed = false;
19681        synchronized (mPackages) {
19682            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19683                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19684                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19685                        .valueAt(i);
19686                if (userId != thisUserId) {
19687                    continue;
19688                }
19689                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19690                while (it.hasNext()) {
19691                    PersistentPreferredActivity ppa = it.next();
19692                    // Mark entry for removal only if it matches the package name.
19693                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19694                        if (removed == null) {
19695                            removed = new ArrayList<PersistentPreferredActivity>();
19696                        }
19697                        removed.add(ppa);
19698                    }
19699                }
19700                if (removed != null) {
19701                    for (int j=0; j<removed.size(); j++) {
19702                        PersistentPreferredActivity ppa = removed.get(j);
19703                        ppir.removeFilter(ppa);
19704                    }
19705                    changed = true;
19706                }
19707            }
19708
19709            if (changed) {
19710                scheduleWritePackageRestrictionsLocked(userId);
19711                postPreferredActivityChangedBroadcast(userId);
19712            }
19713        }
19714    }
19715
19716    /**
19717     * Common machinery for picking apart a restored XML blob and passing
19718     * it to a caller-supplied functor to be applied to the running system.
19719     */
19720    private void restoreFromXml(XmlPullParser parser, int userId,
19721            String expectedStartTag, BlobXmlRestorer functor)
19722            throws IOException, XmlPullParserException {
19723        int type;
19724        while ((type = parser.next()) != XmlPullParser.START_TAG
19725                && type != XmlPullParser.END_DOCUMENT) {
19726        }
19727        if (type != XmlPullParser.START_TAG) {
19728            // oops didn't find a start tag?!
19729            if (DEBUG_BACKUP) {
19730                Slog.e(TAG, "Didn't find start tag during restore");
19731            }
19732            return;
19733        }
19734Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19735        // this is supposed to be TAG_PREFERRED_BACKUP
19736        if (!expectedStartTag.equals(parser.getName())) {
19737            if (DEBUG_BACKUP) {
19738                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19739            }
19740            return;
19741        }
19742
19743        // skip interfering stuff, then we're aligned with the backing implementation
19744        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19745Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19746        functor.apply(parser, userId);
19747    }
19748
19749    private interface BlobXmlRestorer {
19750        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19751    }
19752
19753    /**
19754     * Non-Binder method, support for the backup/restore mechanism: write the
19755     * full set of preferred activities in its canonical XML format.  Returns the
19756     * XML output as a byte array, or null if there is none.
19757     */
19758    @Override
19759    public byte[] getPreferredActivityBackup(int userId) {
19760        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19761            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19762        }
19763
19764        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19765        try {
19766            final XmlSerializer serializer = new FastXmlSerializer();
19767            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19768            serializer.startDocument(null, true);
19769            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19770
19771            synchronized (mPackages) {
19772                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19773            }
19774
19775            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19776            serializer.endDocument();
19777            serializer.flush();
19778        } catch (Exception e) {
19779            if (DEBUG_BACKUP) {
19780                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19781            }
19782            return null;
19783        }
19784
19785        return dataStream.toByteArray();
19786    }
19787
19788    @Override
19789    public void restorePreferredActivities(byte[] backup, int userId) {
19790        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19791            throw new SecurityException("Only the system may call restorePreferredActivities()");
19792        }
19793
19794        try {
19795            final XmlPullParser parser = Xml.newPullParser();
19796            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19797            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19798                    new BlobXmlRestorer() {
19799                        @Override
19800                        public void apply(XmlPullParser parser, int userId)
19801                                throws XmlPullParserException, IOException {
19802                            synchronized (mPackages) {
19803                                mSettings.readPreferredActivitiesLPw(parser, userId);
19804                            }
19805                        }
19806                    } );
19807        } catch (Exception e) {
19808            if (DEBUG_BACKUP) {
19809                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19810            }
19811        }
19812    }
19813
19814    /**
19815     * Non-Binder method, support for the backup/restore mechanism: write the
19816     * default browser (etc) settings in its canonical XML format.  Returns the default
19817     * browser XML representation as a byte array, or null if there is none.
19818     */
19819    @Override
19820    public byte[] getDefaultAppsBackup(int userId) {
19821        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19822            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19823        }
19824
19825        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19826        try {
19827            final XmlSerializer serializer = new FastXmlSerializer();
19828            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19829            serializer.startDocument(null, true);
19830            serializer.startTag(null, TAG_DEFAULT_APPS);
19831
19832            synchronized (mPackages) {
19833                mSettings.writeDefaultAppsLPr(serializer, userId);
19834            }
19835
19836            serializer.endTag(null, TAG_DEFAULT_APPS);
19837            serializer.endDocument();
19838            serializer.flush();
19839        } catch (Exception e) {
19840            if (DEBUG_BACKUP) {
19841                Slog.e(TAG, "Unable to write default apps for backup", e);
19842            }
19843            return null;
19844        }
19845
19846        return dataStream.toByteArray();
19847    }
19848
19849    @Override
19850    public void restoreDefaultApps(byte[] backup, int userId) {
19851        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19852            throw new SecurityException("Only the system may call restoreDefaultApps()");
19853        }
19854
19855        try {
19856            final XmlPullParser parser = Xml.newPullParser();
19857            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19858            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19859                    new BlobXmlRestorer() {
19860                        @Override
19861                        public void apply(XmlPullParser parser, int userId)
19862                                throws XmlPullParserException, IOException {
19863                            synchronized (mPackages) {
19864                                mSettings.readDefaultAppsLPw(parser, userId);
19865                            }
19866                        }
19867                    } );
19868        } catch (Exception e) {
19869            if (DEBUG_BACKUP) {
19870                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19871            }
19872        }
19873    }
19874
19875    @Override
19876    public byte[] getIntentFilterVerificationBackup(int userId) {
19877        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19878            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19879        }
19880
19881        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19882        try {
19883            final XmlSerializer serializer = new FastXmlSerializer();
19884            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19885            serializer.startDocument(null, true);
19886            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19887
19888            synchronized (mPackages) {
19889                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19890            }
19891
19892            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19893            serializer.endDocument();
19894            serializer.flush();
19895        } catch (Exception e) {
19896            if (DEBUG_BACKUP) {
19897                Slog.e(TAG, "Unable to write default apps for backup", e);
19898            }
19899            return null;
19900        }
19901
19902        return dataStream.toByteArray();
19903    }
19904
19905    @Override
19906    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19907        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19908            throw new SecurityException("Only the system may call restorePreferredActivities()");
19909        }
19910
19911        try {
19912            final XmlPullParser parser = Xml.newPullParser();
19913            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19914            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19915                    new BlobXmlRestorer() {
19916                        @Override
19917                        public void apply(XmlPullParser parser, int userId)
19918                                throws XmlPullParserException, IOException {
19919                            synchronized (mPackages) {
19920                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19921                                mSettings.writeLPr();
19922                            }
19923                        }
19924                    } );
19925        } catch (Exception e) {
19926            if (DEBUG_BACKUP) {
19927                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19928            }
19929        }
19930    }
19931
19932    @Override
19933    public byte[] getPermissionGrantBackup(int userId) {
19934        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19935            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19936        }
19937
19938        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19939        try {
19940            final XmlSerializer serializer = new FastXmlSerializer();
19941            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19942            serializer.startDocument(null, true);
19943            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19944
19945            synchronized (mPackages) {
19946                serializeRuntimePermissionGrantsLPr(serializer, userId);
19947            }
19948
19949            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19950            serializer.endDocument();
19951            serializer.flush();
19952        } catch (Exception e) {
19953            if (DEBUG_BACKUP) {
19954                Slog.e(TAG, "Unable to write default apps for backup", e);
19955            }
19956            return null;
19957        }
19958
19959        return dataStream.toByteArray();
19960    }
19961
19962    @Override
19963    public void restorePermissionGrants(byte[] backup, int userId) {
19964        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19965            throw new SecurityException("Only the system may call restorePermissionGrants()");
19966        }
19967
19968        try {
19969            final XmlPullParser parser = Xml.newPullParser();
19970            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19971            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19972                    new BlobXmlRestorer() {
19973                        @Override
19974                        public void apply(XmlPullParser parser, int userId)
19975                                throws XmlPullParserException, IOException {
19976                            synchronized (mPackages) {
19977                                processRestoredPermissionGrantsLPr(parser, userId);
19978                            }
19979                        }
19980                    } );
19981        } catch (Exception e) {
19982            if (DEBUG_BACKUP) {
19983                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19984            }
19985        }
19986    }
19987
19988    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19989            throws IOException {
19990        serializer.startTag(null, TAG_ALL_GRANTS);
19991
19992        final int N = mSettings.mPackages.size();
19993        for (int i = 0; i < N; i++) {
19994            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19995            boolean pkgGrantsKnown = false;
19996
19997            PermissionsState packagePerms = ps.getPermissionsState();
19998
19999            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20000                final int grantFlags = state.getFlags();
20001                // only look at grants that are not system/policy fixed
20002                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20003                    final boolean isGranted = state.isGranted();
20004                    // And only back up the user-twiddled state bits
20005                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20006                        final String packageName = mSettings.mPackages.keyAt(i);
20007                        if (!pkgGrantsKnown) {
20008                            serializer.startTag(null, TAG_GRANT);
20009                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20010                            pkgGrantsKnown = true;
20011                        }
20012
20013                        final boolean userSet =
20014                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20015                        final boolean userFixed =
20016                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20017                        final boolean revoke =
20018                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20019
20020                        serializer.startTag(null, TAG_PERMISSION);
20021                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20022                        if (isGranted) {
20023                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20024                        }
20025                        if (userSet) {
20026                            serializer.attribute(null, ATTR_USER_SET, "true");
20027                        }
20028                        if (userFixed) {
20029                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20030                        }
20031                        if (revoke) {
20032                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20033                        }
20034                        serializer.endTag(null, TAG_PERMISSION);
20035                    }
20036                }
20037            }
20038
20039            if (pkgGrantsKnown) {
20040                serializer.endTag(null, TAG_GRANT);
20041            }
20042        }
20043
20044        serializer.endTag(null, TAG_ALL_GRANTS);
20045    }
20046
20047    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20048            throws XmlPullParserException, IOException {
20049        String pkgName = null;
20050        int outerDepth = parser.getDepth();
20051        int type;
20052        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20053                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20054            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20055                continue;
20056            }
20057
20058            final String tagName = parser.getName();
20059            if (tagName.equals(TAG_GRANT)) {
20060                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20061                if (DEBUG_BACKUP) {
20062                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20063                }
20064            } else if (tagName.equals(TAG_PERMISSION)) {
20065
20066                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20067                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20068
20069                int newFlagSet = 0;
20070                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20071                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20072                }
20073                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20074                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20075                }
20076                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20077                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20078                }
20079                if (DEBUG_BACKUP) {
20080                    Slog.v(TAG, "  + Restoring grant:"
20081                            + " pkg=" + pkgName
20082                            + " perm=" + permName
20083                            + " granted=" + isGranted
20084                            + " bits=0x" + Integer.toHexString(newFlagSet));
20085                }
20086                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20087                if (ps != null) {
20088                    // Already installed so we apply the grant immediately
20089                    if (DEBUG_BACKUP) {
20090                        Slog.v(TAG, "        + already installed; applying");
20091                    }
20092                    PermissionsState perms = ps.getPermissionsState();
20093                    BasePermission bp =
20094                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20095                    if (bp != null) {
20096                        if (isGranted) {
20097                            perms.grantRuntimePermission(bp, userId);
20098                        }
20099                        if (newFlagSet != 0) {
20100                            perms.updatePermissionFlags(
20101                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20102                        }
20103                    }
20104                } else {
20105                    // Need to wait for post-restore install to apply the grant
20106                    if (DEBUG_BACKUP) {
20107                        Slog.v(TAG, "        - not yet installed; saving for later");
20108                    }
20109                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20110                            isGranted, newFlagSet, userId);
20111                }
20112            } else {
20113                PackageManagerService.reportSettingsProblem(Log.WARN,
20114                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20115                XmlUtils.skipCurrentTag(parser);
20116            }
20117        }
20118
20119        scheduleWriteSettingsLocked();
20120        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20121    }
20122
20123    @Override
20124    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20125            int sourceUserId, int targetUserId, int flags) {
20126        mContext.enforceCallingOrSelfPermission(
20127                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20128        int callingUid = Binder.getCallingUid();
20129        enforceOwnerRights(ownerPackage, callingUid);
20130        PackageManagerServiceUtils.enforceShellRestriction(
20131                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20132        if (intentFilter.countActions() == 0) {
20133            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20134            return;
20135        }
20136        synchronized (mPackages) {
20137            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20138                    ownerPackage, targetUserId, flags);
20139            CrossProfileIntentResolver resolver =
20140                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20141            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20142            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20143            if (existing != null) {
20144                int size = existing.size();
20145                for (int i = 0; i < size; i++) {
20146                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20147                        return;
20148                    }
20149                }
20150            }
20151            resolver.addFilter(newFilter);
20152            scheduleWritePackageRestrictionsLocked(sourceUserId);
20153        }
20154    }
20155
20156    @Override
20157    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20158        mContext.enforceCallingOrSelfPermission(
20159                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20160        final int callingUid = Binder.getCallingUid();
20161        enforceOwnerRights(ownerPackage, callingUid);
20162        PackageManagerServiceUtils.enforceShellRestriction(
20163                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20164        synchronized (mPackages) {
20165            CrossProfileIntentResolver resolver =
20166                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20167            ArraySet<CrossProfileIntentFilter> set =
20168                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20169            for (CrossProfileIntentFilter filter : set) {
20170                if (filter.getOwnerPackage().equals(ownerPackage)) {
20171                    resolver.removeFilter(filter);
20172                }
20173            }
20174            scheduleWritePackageRestrictionsLocked(sourceUserId);
20175        }
20176    }
20177
20178    // Enforcing that callingUid is owning pkg on userId
20179    private void enforceOwnerRights(String pkg, int callingUid) {
20180        // The system owns everything.
20181        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20182            return;
20183        }
20184        final int callingUserId = UserHandle.getUserId(callingUid);
20185        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20186        if (pi == null) {
20187            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20188                    + callingUserId);
20189        }
20190        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20191            throw new SecurityException("Calling uid " + callingUid
20192                    + " does not own package " + pkg);
20193        }
20194    }
20195
20196    @Override
20197    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20198        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20199            return null;
20200        }
20201        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20202    }
20203
20204    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20205        UserManagerService ums = UserManagerService.getInstance();
20206        if (ums != null) {
20207            final UserInfo parent = ums.getProfileParent(userId);
20208            final int launcherUid = (parent != null) ? parent.id : userId;
20209            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20210            if (launcherComponent != null) {
20211                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20212                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20213                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20214                        .setPackage(launcherComponent.getPackageName());
20215                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20216            }
20217        }
20218    }
20219
20220    /**
20221     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20222     * then reports the most likely home activity or null if there are more than one.
20223     */
20224    private ComponentName getDefaultHomeActivity(int userId) {
20225        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20226        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20227        if (cn != null) {
20228            return cn;
20229        }
20230
20231        // Find the launcher with the highest priority and return that component if there are no
20232        // other home activity with the same priority.
20233        int lastPriority = Integer.MIN_VALUE;
20234        ComponentName lastComponent = null;
20235        final int size = allHomeCandidates.size();
20236        for (int i = 0; i < size; i++) {
20237            final ResolveInfo ri = allHomeCandidates.get(i);
20238            if (ri.priority > lastPriority) {
20239                lastComponent = ri.activityInfo.getComponentName();
20240                lastPriority = ri.priority;
20241            } else if (ri.priority == lastPriority) {
20242                // Two components found with same priority.
20243                lastComponent = null;
20244            }
20245        }
20246        return lastComponent;
20247    }
20248
20249    private Intent getHomeIntent() {
20250        Intent intent = new Intent(Intent.ACTION_MAIN);
20251        intent.addCategory(Intent.CATEGORY_HOME);
20252        intent.addCategory(Intent.CATEGORY_DEFAULT);
20253        return intent;
20254    }
20255
20256    private IntentFilter getHomeFilter() {
20257        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20258        filter.addCategory(Intent.CATEGORY_HOME);
20259        filter.addCategory(Intent.CATEGORY_DEFAULT);
20260        return filter;
20261    }
20262
20263    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20264            int userId) {
20265        Intent intent  = getHomeIntent();
20266        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20267                PackageManager.GET_META_DATA, userId);
20268        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20269                true, false, false, userId);
20270
20271        allHomeCandidates.clear();
20272        if (list != null) {
20273            for (ResolveInfo ri : list) {
20274                allHomeCandidates.add(ri);
20275            }
20276        }
20277        return (preferred == null || preferred.activityInfo == null)
20278                ? null
20279                : new ComponentName(preferred.activityInfo.packageName,
20280                        preferred.activityInfo.name);
20281    }
20282
20283    @Override
20284    public void setHomeActivity(ComponentName comp, int userId) {
20285        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20286            return;
20287        }
20288        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20289        getHomeActivitiesAsUser(homeActivities, userId);
20290
20291        boolean found = false;
20292
20293        final int size = homeActivities.size();
20294        final ComponentName[] set = new ComponentName[size];
20295        for (int i = 0; i < size; i++) {
20296            final ResolveInfo candidate = homeActivities.get(i);
20297            final ActivityInfo info = candidate.activityInfo;
20298            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20299            set[i] = activityName;
20300            if (!found && activityName.equals(comp)) {
20301                found = true;
20302            }
20303        }
20304        if (!found) {
20305            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20306                    + userId);
20307        }
20308        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20309                set, comp, userId);
20310    }
20311
20312    private @Nullable String getSetupWizardPackageName() {
20313        final Intent intent = new Intent(Intent.ACTION_MAIN);
20314        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20315
20316        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20317                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20318                        | MATCH_DISABLED_COMPONENTS,
20319                UserHandle.myUserId());
20320        if (matches.size() == 1) {
20321            return matches.get(0).getComponentInfo().packageName;
20322        } else {
20323            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20324                    + ": matches=" + matches);
20325            return null;
20326        }
20327    }
20328
20329    private @Nullable String getStorageManagerPackageName() {
20330        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20331
20332        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20333                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20334                        | MATCH_DISABLED_COMPONENTS,
20335                UserHandle.myUserId());
20336        if (matches.size() == 1) {
20337            return matches.get(0).getComponentInfo().packageName;
20338        } else {
20339            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20340                    + matches.size() + ": matches=" + matches);
20341            return null;
20342        }
20343    }
20344
20345    @Override
20346    public void setApplicationEnabledSetting(String appPackageName,
20347            int newState, int flags, int userId, String callingPackage) {
20348        if (!sUserManager.exists(userId)) return;
20349        if (callingPackage == null) {
20350            callingPackage = Integer.toString(Binder.getCallingUid());
20351        }
20352        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20353    }
20354
20355    @Override
20356    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20357        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20358        synchronized (mPackages) {
20359            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20360            if (pkgSetting != null) {
20361                pkgSetting.setUpdateAvailable(updateAvailable);
20362            }
20363        }
20364    }
20365
20366    @Override
20367    public void setComponentEnabledSetting(ComponentName componentName,
20368            int newState, int flags, int userId) {
20369        if (!sUserManager.exists(userId)) return;
20370        setEnabledSetting(componentName.getPackageName(),
20371                componentName.getClassName(), newState, flags, userId, null);
20372    }
20373
20374    private void setEnabledSetting(final String packageName, String className, int newState,
20375            final int flags, int userId, String callingPackage) {
20376        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20377              || newState == COMPONENT_ENABLED_STATE_ENABLED
20378              || newState == COMPONENT_ENABLED_STATE_DISABLED
20379              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20380              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20381            throw new IllegalArgumentException("Invalid new component state: "
20382                    + newState);
20383        }
20384        PackageSetting pkgSetting;
20385        final int callingUid = Binder.getCallingUid();
20386        final int permission;
20387        if (callingUid == Process.SYSTEM_UID) {
20388            permission = PackageManager.PERMISSION_GRANTED;
20389        } else {
20390            permission = mContext.checkCallingOrSelfPermission(
20391                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20392        }
20393        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20394                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20395        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20396        boolean sendNow = false;
20397        boolean isApp = (className == null);
20398        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20399        String componentName = isApp ? packageName : className;
20400        int packageUid = -1;
20401        ArrayList<String> components;
20402
20403        // reader
20404        synchronized (mPackages) {
20405            pkgSetting = mSettings.mPackages.get(packageName);
20406            if (pkgSetting == null) {
20407                if (!isCallerInstantApp) {
20408                    if (className == null) {
20409                        throw new IllegalArgumentException("Unknown package: " + packageName);
20410                    }
20411                    throw new IllegalArgumentException(
20412                            "Unknown component: " + packageName + "/" + className);
20413                } else {
20414                    // throw SecurityException to prevent leaking package information
20415                    throw new SecurityException(
20416                            "Attempt to change component state; "
20417                            + "pid=" + Binder.getCallingPid()
20418                            + ", uid=" + callingUid
20419                            + (className == null
20420                                    ? ", package=" + packageName
20421                                    : ", component=" + packageName + "/" + className));
20422                }
20423            }
20424        }
20425
20426        // Limit who can change which apps
20427        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20428            // Don't allow apps that don't have permission to modify other apps
20429            if (!allowedByPermission
20430                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20431                throw new SecurityException(
20432                        "Attempt to change component state; "
20433                        + "pid=" + Binder.getCallingPid()
20434                        + ", uid=" + callingUid
20435                        + (className == null
20436                                ? ", package=" + packageName
20437                                : ", component=" + packageName + "/" + className));
20438            }
20439            // Don't allow changing protected packages.
20440            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20441                throw new SecurityException("Cannot disable a protected package: " + packageName);
20442            }
20443        }
20444
20445        synchronized (mPackages) {
20446            if (callingUid == Process.SHELL_UID
20447                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20448                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20449                // unless it is a test package.
20450                int oldState = pkgSetting.getEnabled(userId);
20451                if (className == null
20452                        &&
20453                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20454                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20455                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20456                        &&
20457                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20458                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20459                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20460                    // ok
20461                } else {
20462                    throw new SecurityException(
20463                            "Shell cannot change component state for " + packageName + "/"
20464                                    + className + " to " + newState);
20465                }
20466            }
20467        }
20468        if (className == null) {
20469            // We're dealing with an application/package level state change
20470            synchronized (mPackages) {
20471                if (pkgSetting.getEnabled(userId) == newState) {
20472                    // Nothing to do
20473                    return;
20474                }
20475            }
20476            // If we're enabling a system stub, there's a little more work to do.
20477            // Prior to enabling the package, we need to decompress the APK(s) to the
20478            // data partition and then replace the version on the system partition.
20479            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20480            final boolean isSystemStub = deletedPkg.isStub
20481                    && deletedPkg.isSystem();
20482            if (isSystemStub
20483                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20484                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20485                final File codePath = decompressPackage(deletedPkg);
20486                if (codePath == null) {
20487                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20488                    return;
20489                }
20490                // TODO remove direct parsing of the package object during internal cleanup
20491                // of scan package
20492                // We need to call parse directly here for no other reason than we need
20493                // the new package in order to disable the old one [we use the information
20494                // for some internal optimization to optionally create a new package setting
20495                // object on replace]. However, we can't get the package from the scan
20496                // because the scan modifies live structures and we need to remove the
20497                // old [system] package from the system before a scan can be attempted.
20498                // Once scan is indempotent we can remove this parse and use the package
20499                // object we scanned, prior to adding it to package settings.
20500                final PackageParser pp = new PackageParser();
20501                pp.setSeparateProcesses(mSeparateProcesses);
20502                pp.setDisplayMetrics(mMetrics);
20503                pp.setCallback(mPackageParserCallback);
20504                final PackageParser.Package tmpPkg;
20505                try {
20506                    final @ParseFlags int parseFlags = mDefParseFlags
20507                            | PackageParser.PARSE_MUST_BE_APK
20508                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20509                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20510                } catch (PackageParserException e) {
20511                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20512                    return;
20513                }
20514                synchronized (mInstallLock) {
20515                    // Disable the stub and remove any package entries
20516                    removePackageLI(deletedPkg, true);
20517                    synchronized (mPackages) {
20518                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20519                    }
20520                    final PackageParser.Package pkg;
20521                    try (PackageFreezer freezer =
20522                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20523                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20524                                | PackageParser.PARSE_ENFORCE_CODE;
20525                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20526                                0 /*currentTime*/, null /*user*/);
20527                        prepareAppDataAfterInstallLIF(pkg);
20528                        synchronized (mPackages) {
20529                            try {
20530                                updateSharedLibrariesLPr(pkg, null);
20531                            } catch (PackageManagerException e) {
20532                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20533                            }
20534                            mPermissionManager.updatePermissions(
20535                                    pkg.packageName, pkg, true, mPackages.values(),
20536                                    mPermissionCallback);
20537                            mSettings.writeLPr();
20538                        }
20539                    } catch (PackageManagerException e) {
20540                        // Whoops! Something went wrong; try to roll back to the stub
20541                        Slog.w(TAG, "Failed to install compressed system package:"
20542                                + pkgSetting.name, e);
20543                        // Remove the failed install
20544                        removeCodePathLI(codePath);
20545
20546                        // Install the system package
20547                        try (PackageFreezer freezer =
20548                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20549                            synchronized (mPackages) {
20550                                // NOTE: The system package always needs to be enabled; even
20551                                // if it's for a compressed stub. If we don't, installing the
20552                                // system package fails during scan [scanning checks the disabled
20553                                // packages]. We will reverse this later, after we've "installed"
20554                                // the stub.
20555                                // This leaves us in a fragile state; the stub should never be
20556                                // enabled, so, cross your fingers and hope nothing goes wrong
20557                                // until we can disable the package later.
20558                                enableSystemPackageLPw(deletedPkg);
20559                            }
20560                            installPackageFromSystemLIF(deletedPkg.codePath,
20561                                    false /*isPrivileged*/, null /*allUserHandles*/,
20562                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20563                                    true /*writeSettings*/);
20564                        } catch (PackageManagerException pme) {
20565                            Slog.w(TAG, "Failed to restore system package:"
20566                                    + deletedPkg.packageName, pme);
20567                        } finally {
20568                            synchronized (mPackages) {
20569                                mSettings.disableSystemPackageLPw(
20570                                        deletedPkg.packageName, true /*replaced*/);
20571                                mSettings.writeLPr();
20572                            }
20573                        }
20574                        return;
20575                    }
20576                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20577                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20578                    mDexManager.notifyPackageUpdated(pkg.packageName,
20579                            pkg.baseCodePath, pkg.splitCodePaths);
20580                }
20581            }
20582            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20583                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20584                // Don't care about who enables an app.
20585                callingPackage = null;
20586            }
20587            synchronized (mPackages) {
20588                pkgSetting.setEnabled(newState, userId, callingPackage);
20589            }
20590        } else {
20591            synchronized (mPackages) {
20592                // We're dealing with a component level state change
20593                // First, verify that this is a valid class name.
20594                PackageParser.Package pkg = pkgSetting.pkg;
20595                if (pkg == null || !pkg.hasComponentClassName(className)) {
20596                    if (pkg != null &&
20597                            pkg.applicationInfo.targetSdkVersion >=
20598                                    Build.VERSION_CODES.JELLY_BEAN) {
20599                        throw new IllegalArgumentException("Component class " + className
20600                                + " does not exist in " + packageName);
20601                    } else {
20602                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20603                                + className + " does not exist in " + packageName);
20604                    }
20605                }
20606                switch (newState) {
20607                    case COMPONENT_ENABLED_STATE_ENABLED:
20608                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20609                            return;
20610                        }
20611                        break;
20612                    case COMPONENT_ENABLED_STATE_DISABLED:
20613                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20614                            return;
20615                        }
20616                        break;
20617                    case COMPONENT_ENABLED_STATE_DEFAULT:
20618                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20619                            return;
20620                        }
20621                        break;
20622                    default:
20623                        Slog.e(TAG, "Invalid new component state: " + newState);
20624                        return;
20625                }
20626            }
20627        }
20628        synchronized (mPackages) {
20629            scheduleWritePackageRestrictionsLocked(userId);
20630            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20631            final long callingId = Binder.clearCallingIdentity();
20632            try {
20633                updateInstantAppInstallerLocked(packageName);
20634            } finally {
20635                Binder.restoreCallingIdentity(callingId);
20636            }
20637            components = mPendingBroadcasts.get(userId, packageName);
20638            final boolean newPackage = components == null;
20639            if (newPackage) {
20640                components = new ArrayList<String>();
20641            }
20642            if (!components.contains(componentName)) {
20643                components.add(componentName);
20644            }
20645            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20646                sendNow = true;
20647                // Purge entry from pending broadcast list if another one exists already
20648                // since we are sending one right away.
20649                mPendingBroadcasts.remove(userId, packageName);
20650            } else {
20651                if (newPackage) {
20652                    mPendingBroadcasts.put(userId, packageName, components);
20653                }
20654                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20655                    // Schedule a message
20656                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20657                }
20658            }
20659        }
20660
20661        long callingId = Binder.clearCallingIdentity();
20662        try {
20663            if (sendNow) {
20664                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20665                sendPackageChangedBroadcast(packageName,
20666                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20667            }
20668        } finally {
20669            Binder.restoreCallingIdentity(callingId);
20670        }
20671    }
20672
20673    @Override
20674    public void flushPackageRestrictionsAsUser(int userId) {
20675        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20676            return;
20677        }
20678        if (!sUserManager.exists(userId)) {
20679            return;
20680        }
20681        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20682                false /* checkShell */, "flushPackageRestrictions");
20683        synchronized (mPackages) {
20684            mSettings.writePackageRestrictionsLPr(userId);
20685            mDirtyUsers.remove(userId);
20686            if (mDirtyUsers.isEmpty()) {
20687                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20688            }
20689        }
20690    }
20691
20692    private void sendPackageChangedBroadcast(String packageName,
20693            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20694        if (DEBUG_INSTALL)
20695            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20696                    + componentNames);
20697        Bundle extras = new Bundle(4);
20698        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20699        String nameList[] = new String[componentNames.size()];
20700        componentNames.toArray(nameList);
20701        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20702        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20703        extras.putInt(Intent.EXTRA_UID, packageUid);
20704        // If this is not reporting a change of the overall package, then only send it
20705        // to registered receivers.  We don't want to launch a swath of apps for every
20706        // little component state change.
20707        final int flags = !componentNames.contains(packageName)
20708                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20709        final int userId = UserHandle.getUserId(packageUid);
20710        final boolean isInstantApp = isInstantApp(packageName, userId);
20711        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20712        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20713        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20714                userIds, instantUserIds);
20715    }
20716
20717    @Override
20718    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20719        if (!sUserManager.exists(userId)) return;
20720        final int callingUid = Binder.getCallingUid();
20721        if (getInstantAppPackageName(callingUid) != null) {
20722            return;
20723        }
20724        final int permission = mContext.checkCallingOrSelfPermission(
20725                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20726        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20727        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20728                true /* requireFullPermission */, true /* checkShell */, "stop package");
20729        // writer
20730        synchronized (mPackages) {
20731            final PackageSetting ps = mSettings.mPackages.get(packageName);
20732            if (!filterAppAccessLPr(ps, callingUid, userId)
20733                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20734                            allowedByPermission, callingUid, userId)) {
20735                scheduleWritePackageRestrictionsLocked(userId);
20736            }
20737        }
20738    }
20739
20740    @Override
20741    public String getInstallerPackageName(String packageName) {
20742        final int callingUid = Binder.getCallingUid();
20743        if (getInstantAppPackageName(callingUid) != null) {
20744            return null;
20745        }
20746        // reader
20747        synchronized (mPackages) {
20748            final PackageSetting ps = mSettings.mPackages.get(packageName);
20749            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20750                return null;
20751            }
20752            return mSettings.getInstallerPackageNameLPr(packageName);
20753        }
20754    }
20755
20756    public boolean isOrphaned(String packageName) {
20757        // reader
20758        synchronized (mPackages) {
20759            return mSettings.isOrphaned(packageName);
20760        }
20761    }
20762
20763    @Override
20764    public int getApplicationEnabledSetting(String packageName, int userId) {
20765        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20766        int callingUid = Binder.getCallingUid();
20767        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20768                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20769        // reader
20770        synchronized (mPackages) {
20771            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20772                return COMPONENT_ENABLED_STATE_DISABLED;
20773            }
20774            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20775        }
20776    }
20777
20778    @Override
20779    public int getComponentEnabledSetting(ComponentName component, int userId) {
20780        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20781        int callingUid = Binder.getCallingUid();
20782        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20783                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20784        synchronized (mPackages) {
20785            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20786                    component, TYPE_UNKNOWN, userId)) {
20787                return COMPONENT_ENABLED_STATE_DISABLED;
20788            }
20789            return mSettings.getComponentEnabledSettingLPr(component, userId);
20790        }
20791    }
20792
20793    @Override
20794    public void enterSafeMode() {
20795        enforceSystemOrRoot("Only the system can request entering safe mode");
20796
20797        if (!mSystemReady) {
20798            mSafeMode = true;
20799        }
20800    }
20801
20802    @Override
20803    public void systemReady() {
20804        enforceSystemOrRoot("Only the system can claim the system is ready");
20805
20806        mSystemReady = true;
20807        final ContentResolver resolver = mContext.getContentResolver();
20808        ContentObserver co = new ContentObserver(mHandler) {
20809            @Override
20810            public void onChange(boolean selfChange) {
20811                mEphemeralAppsDisabled =
20812                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20813                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20814            }
20815        };
20816        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20817                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20818                false, co, UserHandle.USER_SYSTEM);
20819        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20820                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20821        co.onChange(true);
20822
20823        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20824        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20825        // it is done.
20826        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20827            @Override
20828            public void onChange(boolean selfChange) {
20829                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20830                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20831                        oobEnabled == 1 ? "true" : "false");
20832            }
20833        };
20834        mContext.getContentResolver().registerContentObserver(
20835                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20836                UserHandle.USER_SYSTEM);
20837        // At boot, restore the value from the setting, which persists across reboot.
20838        privAppOobObserver.onChange(true);
20839
20840        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20841        // disabled after already being started.
20842        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20843                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20844
20845        // Read the compatibilty setting when the system is ready.
20846        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20847                mContext.getContentResolver(),
20848                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20849        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20850        if (DEBUG_SETTINGS) {
20851            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20852        }
20853
20854        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20855
20856        synchronized (mPackages) {
20857            // Verify that all of the preferred activity components actually
20858            // exist.  It is possible for applications to be updated and at
20859            // that point remove a previously declared activity component that
20860            // had been set as a preferred activity.  We try to clean this up
20861            // the next time we encounter that preferred activity, but it is
20862            // possible for the user flow to never be able to return to that
20863            // situation so here we do a sanity check to make sure we haven't
20864            // left any junk around.
20865            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20866            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20867                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20868                removed.clear();
20869                for (PreferredActivity pa : pir.filterSet()) {
20870                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20871                        removed.add(pa);
20872                    }
20873                }
20874                if (removed.size() > 0) {
20875                    for (int r=0; r<removed.size(); r++) {
20876                        PreferredActivity pa = removed.get(r);
20877                        Slog.w(TAG, "Removing dangling preferred activity: "
20878                                + pa.mPref.mComponent);
20879                        pir.removeFilter(pa);
20880                    }
20881                    mSettings.writePackageRestrictionsLPr(
20882                            mSettings.mPreferredActivities.keyAt(i));
20883                }
20884            }
20885
20886            for (int userId : UserManagerService.getInstance().getUserIds()) {
20887                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20888                    grantPermissionsUserIds = ArrayUtils.appendInt(
20889                            grantPermissionsUserIds, userId);
20890                }
20891            }
20892        }
20893        sUserManager.systemReady();
20894        // If we upgraded grant all default permissions before kicking off.
20895        for (int userId : grantPermissionsUserIds) {
20896            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20897        }
20898
20899        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20900            // If we did not grant default permissions, we preload from this the
20901            // default permission exceptions lazily to ensure we don't hit the
20902            // disk on a new user creation.
20903            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20904        }
20905
20906        // Now that we've scanned all packages, and granted any default
20907        // permissions, ensure permissions are updated. Beware of dragons if you
20908        // try optimizing this.
20909        synchronized (mPackages) {
20910            mPermissionManager.updateAllPermissions(
20911                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20912                    mPermissionCallback);
20913        }
20914
20915        // Kick off any messages waiting for system ready
20916        if (mPostSystemReadyMessages != null) {
20917            for (Message msg : mPostSystemReadyMessages) {
20918                msg.sendToTarget();
20919            }
20920            mPostSystemReadyMessages = null;
20921        }
20922
20923        // Watch for external volumes that come and go over time
20924        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20925        storage.registerListener(mStorageListener);
20926
20927        mInstallerService.systemReady();
20928        mPackageDexOptimizer.systemReady();
20929
20930        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20931                StorageManagerInternal.class);
20932        StorageManagerInternal.addExternalStoragePolicy(
20933                new StorageManagerInternal.ExternalStorageMountPolicy() {
20934            @Override
20935            public int getMountMode(int uid, String packageName) {
20936                if (Process.isIsolated(uid)) {
20937                    return Zygote.MOUNT_EXTERNAL_NONE;
20938                }
20939                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20940                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20941                }
20942                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20943                    return Zygote.MOUNT_EXTERNAL_READ;
20944                }
20945                return Zygote.MOUNT_EXTERNAL_WRITE;
20946            }
20947
20948            @Override
20949            public boolean hasExternalStorage(int uid, String packageName) {
20950                return true;
20951            }
20952        });
20953
20954        // Now that we're mostly running, clean up stale users and apps
20955        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20956        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20957
20958        mPermissionManager.systemReady();
20959    }
20960
20961    public void waitForAppDataPrepared() {
20962        if (mPrepareAppDataFuture == null) {
20963            return;
20964        }
20965        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20966        mPrepareAppDataFuture = null;
20967    }
20968
20969    @Override
20970    public boolean isSafeMode() {
20971        // allow instant applications
20972        return mSafeMode;
20973    }
20974
20975    @Override
20976    public boolean hasSystemUidErrors() {
20977        // allow instant applications
20978        return mHasSystemUidErrors;
20979    }
20980
20981    static String arrayToString(int[] array) {
20982        StringBuffer buf = new StringBuffer(128);
20983        buf.append('[');
20984        if (array != null) {
20985            for (int i=0; i<array.length; i++) {
20986                if (i > 0) buf.append(", ");
20987                buf.append(array[i]);
20988            }
20989        }
20990        buf.append(']');
20991        return buf.toString();
20992    }
20993
20994    @Override
20995    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20996            FileDescriptor err, String[] args, ShellCallback callback,
20997            ResultReceiver resultReceiver) {
20998        (new PackageManagerShellCommand(this)).exec(
20999                this, in, out, err, args, callback, resultReceiver);
21000    }
21001
21002    @Override
21003    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21004        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21005
21006        DumpState dumpState = new DumpState();
21007        boolean fullPreferred = false;
21008        boolean checkin = false;
21009
21010        String packageName = null;
21011        ArraySet<String> permissionNames = null;
21012
21013        int opti = 0;
21014        while (opti < args.length) {
21015            String opt = args[opti];
21016            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21017                break;
21018            }
21019            opti++;
21020
21021            if ("-a".equals(opt)) {
21022                // Right now we only know how to print all.
21023            } else if ("-h".equals(opt)) {
21024                pw.println("Package manager dump options:");
21025                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21026                pw.println("    --checkin: dump for a checkin");
21027                pw.println("    -f: print details of intent filters");
21028                pw.println("    -h: print this help");
21029                pw.println("  cmd may be one of:");
21030                pw.println("    l[ibraries]: list known shared libraries");
21031                pw.println("    f[eatures]: list device features");
21032                pw.println("    k[eysets]: print known keysets");
21033                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21034                pw.println("    perm[issions]: dump permissions");
21035                pw.println("    permission [name ...]: dump declaration and use of given permission");
21036                pw.println("    pref[erred]: print preferred package settings");
21037                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21038                pw.println("    prov[iders]: dump content providers");
21039                pw.println("    p[ackages]: dump installed packages");
21040                pw.println("    s[hared-users]: dump shared user IDs");
21041                pw.println("    m[essages]: print collected runtime messages");
21042                pw.println("    v[erifiers]: print package verifier info");
21043                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21044                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21045                pw.println("    version: print database version info");
21046                pw.println("    write: write current settings now");
21047                pw.println("    installs: details about install sessions");
21048                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21049                pw.println("    dexopt: dump dexopt state");
21050                pw.println("    compiler-stats: dump compiler statistics");
21051                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21052                pw.println("    service-permissions: dump permissions required by services");
21053                pw.println("    <package.name>: info about given package");
21054                return;
21055            } else if ("--checkin".equals(opt)) {
21056                checkin = true;
21057            } else if ("-f".equals(opt)) {
21058                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21059            } else if ("--proto".equals(opt)) {
21060                dumpProto(fd);
21061                return;
21062            } else {
21063                pw.println("Unknown argument: " + opt + "; use -h for help");
21064            }
21065        }
21066
21067        // Is the caller requesting to dump a particular piece of data?
21068        if (opti < args.length) {
21069            String cmd = args[opti];
21070            opti++;
21071            // Is this a package name?
21072            if ("android".equals(cmd) || cmd.contains(".")) {
21073                packageName = cmd;
21074                // When dumping a single package, we always dump all of its
21075                // filter information since the amount of data will be reasonable.
21076                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21077            } else if ("check-permission".equals(cmd)) {
21078                if (opti >= args.length) {
21079                    pw.println("Error: check-permission missing permission argument");
21080                    return;
21081                }
21082                String perm = args[opti];
21083                opti++;
21084                if (opti >= args.length) {
21085                    pw.println("Error: check-permission missing package argument");
21086                    return;
21087                }
21088
21089                String pkg = args[opti];
21090                opti++;
21091                int user = UserHandle.getUserId(Binder.getCallingUid());
21092                if (opti < args.length) {
21093                    try {
21094                        user = Integer.parseInt(args[opti]);
21095                    } catch (NumberFormatException e) {
21096                        pw.println("Error: check-permission user argument is not a number: "
21097                                + args[opti]);
21098                        return;
21099                    }
21100                }
21101
21102                // Normalize package name to handle renamed packages and static libs
21103                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21104
21105                pw.println(checkPermission(perm, pkg, user));
21106                return;
21107            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21108                dumpState.setDump(DumpState.DUMP_LIBS);
21109            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21110                dumpState.setDump(DumpState.DUMP_FEATURES);
21111            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21112                if (opti >= args.length) {
21113                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21114                            | DumpState.DUMP_SERVICE_RESOLVERS
21115                            | DumpState.DUMP_RECEIVER_RESOLVERS
21116                            | DumpState.DUMP_CONTENT_RESOLVERS);
21117                } else {
21118                    while (opti < args.length) {
21119                        String name = args[opti];
21120                        if ("a".equals(name) || "activity".equals(name)) {
21121                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21122                        } else if ("s".equals(name) || "service".equals(name)) {
21123                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21124                        } else if ("r".equals(name) || "receiver".equals(name)) {
21125                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21126                        } else if ("c".equals(name) || "content".equals(name)) {
21127                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21128                        } else {
21129                            pw.println("Error: unknown resolver table type: " + name);
21130                            return;
21131                        }
21132                        opti++;
21133                    }
21134                }
21135            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21136                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21137            } else if ("permission".equals(cmd)) {
21138                if (opti >= args.length) {
21139                    pw.println("Error: permission requires permission name");
21140                    return;
21141                }
21142                permissionNames = new ArraySet<>();
21143                while (opti < args.length) {
21144                    permissionNames.add(args[opti]);
21145                    opti++;
21146                }
21147                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21148                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21149            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21150                dumpState.setDump(DumpState.DUMP_PREFERRED);
21151            } else if ("preferred-xml".equals(cmd)) {
21152                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21153                if (opti < args.length && "--full".equals(args[opti])) {
21154                    fullPreferred = true;
21155                    opti++;
21156                }
21157            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21158                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21159            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21160                dumpState.setDump(DumpState.DUMP_PACKAGES);
21161            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21162                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21163            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21164                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21165            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21166                dumpState.setDump(DumpState.DUMP_MESSAGES);
21167            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21168                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21169            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21170                    || "intent-filter-verifiers".equals(cmd)) {
21171                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21172            } else if ("version".equals(cmd)) {
21173                dumpState.setDump(DumpState.DUMP_VERSION);
21174            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21175                dumpState.setDump(DumpState.DUMP_KEYSETS);
21176            } else if ("installs".equals(cmd)) {
21177                dumpState.setDump(DumpState.DUMP_INSTALLS);
21178            } else if ("frozen".equals(cmd)) {
21179                dumpState.setDump(DumpState.DUMP_FROZEN);
21180            } else if ("volumes".equals(cmd)) {
21181                dumpState.setDump(DumpState.DUMP_VOLUMES);
21182            } else if ("dexopt".equals(cmd)) {
21183                dumpState.setDump(DumpState.DUMP_DEXOPT);
21184            } else if ("compiler-stats".equals(cmd)) {
21185                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21186            } else if ("changes".equals(cmd)) {
21187                dumpState.setDump(DumpState.DUMP_CHANGES);
21188            } else if ("service-permissions".equals(cmd)) {
21189                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21190            } else if ("write".equals(cmd)) {
21191                synchronized (mPackages) {
21192                    mSettings.writeLPr();
21193                    pw.println("Settings written.");
21194                    return;
21195                }
21196            }
21197        }
21198
21199        if (checkin) {
21200            pw.println("vers,1");
21201        }
21202
21203        // reader
21204        synchronized (mPackages) {
21205            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21206                if (!checkin) {
21207                    if (dumpState.onTitlePrinted())
21208                        pw.println();
21209                    pw.println("Database versions:");
21210                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21211                }
21212            }
21213
21214            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21215                if (!checkin) {
21216                    if (dumpState.onTitlePrinted())
21217                        pw.println();
21218                    pw.println("Verifiers:");
21219                    pw.print("  Required: ");
21220                    pw.print(mRequiredVerifierPackage);
21221                    pw.print(" (uid=");
21222                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21223                            UserHandle.USER_SYSTEM));
21224                    pw.println(")");
21225                } else if (mRequiredVerifierPackage != null) {
21226                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21227                    pw.print(",");
21228                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21229                            UserHandle.USER_SYSTEM));
21230                }
21231            }
21232
21233            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21234                    packageName == null) {
21235                if (mIntentFilterVerifierComponent != null) {
21236                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21237                    if (!checkin) {
21238                        if (dumpState.onTitlePrinted())
21239                            pw.println();
21240                        pw.println("Intent Filter Verifier:");
21241                        pw.print("  Using: ");
21242                        pw.print(verifierPackageName);
21243                        pw.print(" (uid=");
21244                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21245                                UserHandle.USER_SYSTEM));
21246                        pw.println(")");
21247                    } else if (verifierPackageName != null) {
21248                        pw.print("ifv,"); pw.print(verifierPackageName);
21249                        pw.print(",");
21250                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21251                                UserHandle.USER_SYSTEM));
21252                    }
21253                } else {
21254                    pw.println();
21255                    pw.println("No Intent Filter Verifier available!");
21256                }
21257            }
21258
21259            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21260                boolean printedHeader = false;
21261                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21262                while (it.hasNext()) {
21263                    String libName = it.next();
21264                    LongSparseArray<SharedLibraryEntry> versionedLib
21265                            = mSharedLibraries.get(libName);
21266                    if (versionedLib == null) {
21267                        continue;
21268                    }
21269                    final int versionCount = versionedLib.size();
21270                    for (int i = 0; i < versionCount; i++) {
21271                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21272                        if (!checkin) {
21273                            if (!printedHeader) {
21274                                if (dumpState.onTitlePrinted())
21275                                    pw.println();
21276                                pw.println("Libraries:");
21277                                printedHeader = true;
21278                            }
21279                            pw.print("  ");
21280                        } else {
21281                            pw.print("lib,");
21282                        }
21283                        pw.print(libEntry.info.getName());
21284                        if (libEntry.info.isStatic()) {
21285                            pw.print(" version=" + libEntry.info.getLongVersion());
21286                        }
21287                        if (!checkin) {
21288                            pw.print(" -> ");
21289                        }
21290                        if (libEntry.path != null) {
21291                            pw.print(" (jar) ");
21292                            pw.print(libEntry.path);
21293                        } else {
21294                            pw.print(" (apk) ");
21295                            pw.print(libEntry.apk);
21296                        }
21297                        pw.println();
21298                    }
21299                }
21300            }
21301
21302            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21303                if (dumpState.onTitlePrinted())
21304                    pw.println();
21305                if (!checkin) {
21306                    pw.println("Features:");
21307                }
21308
21309                synchronized (mAvailableFeatures) {
21310                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21311                        if (checkin) {
21312                            pw.print("feat,");
21313                            pw.print(feat.name);
21314                            pw.print(",");
21315                            pw.println(feat.version);
21316                        } else {
21317                            pw.print("  ");
21318                            pw.print(feat.name);
21319                            if (feat.version > 0) {
21320                                pw.print(" version=");
21321                                pw.print(feat.version);
21322                            }
21323                            pw.println();
21324                        }
21325                    }
21326                }
21327            }
21328
21329            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21330                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21331                        : "Activity Resolver Table:", "  ", packageName,
21332                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21333                    dumpState.setTitlePrinted(true);
21334                }
21335            }
21336            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21337                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21338                        : "Receiver Resolver Table:", "  ", packageName,
21339                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21340                    dumpState.setTitlePrinted(true);
21341                }
21342            }
21343            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21344                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21345                        : "Service Resolver Table:", "  ", packageName,
21346                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21347                    dumpState.setTitlePrinted(true);
21348                }
21349            }
21350            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21351                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21352                        : "Provider Resolver Table:", "  ", packageName,
21353                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21354                    dumpState.setTitlePrinted(true);
21355                }
21356            }
21357
21358            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21359                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21360                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21361                    int user = mSettings.mPreferredActivities.keyAt(i);
21362                    if (pir.dump(pw,
21363                            dumpState.getTitlePrinted()
21364                                ? "\nPreferred Activities User " + user + ":"
21365                                : "Preferred Activities User " + user + ":", "  ",
21366                            packageName, true, false)) {
21367                        dumpState.setTitlePrinted(true);
21368                    }
21369                }
21370            }
21371
21372            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21373                pw.flush();
21374                FileOutputStream fout = new FileOutputStream(fd);
21375                BufferedOutputStream str = new BufferedOutputStream(fout);
21376                XmlSerializer serializer = new FastXmlSerializer();
21377                try {
21378                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21379                    serializer.startDocument(null, true);
21380                    serializer.setFeature(
21381                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21382                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21383                    serializer.endDocument();
21384                    serializer.flush();
21385                } catch (IllegalArgumentException e) {
21386                    pw.println("Failed writing: " + e);
21387                } catch (IllegalStateException e) {
21388                    pw.println("Failed writing: " + e);
21389                } catch (IOException e) {
21390                    pw.println("Failed writing: " + e);
21391                }
21392            }
21393
21394            if (!checkin
21395                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21396                    && packageName == null) {
21397                pw.println();
21398                int count = mSettings.mPackages.size();
21399                if (count == 0) {
21400                    pw.println("No applications!");
21401                    pw.println();
21402                } else {
21403                    final String prefix = "  ";
21404                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21405                    if (allPackageSettings.size() == 0) {
21406                        pw.println("No domain preferred apps!");
21407                        pw.println();
21408                    } else {
21409                        pw.println("App verification status:");
21410                        pw.println();
21411                        count = 0;
21412                        for (PackageSetting ps : allPackageSettings) {
21413                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21414                            if (ivi == null || ivi.getPackageName() == null) continue;
21415                            pw.println(prefix + "Package: " + ivi.getPackageName());
21416                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21417                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21418                            pw.println();
21419                            count++;
21420                        }
21421                        if (count == 0) {
21422                            pw.println(prefix + "No app verification established.");
21423                            pw.println();
21424                        }
21425                        for (int userId : sUserManager.getUserIds()) {
21426                            pw.println("App linkages for user " + userId + ":");
21427                            pw.println();
21428                            count = 0;
21429                            for (PackageSetting ps : allPackageSettings) {
21430                                final long status = ps.getDomainVerificationStatusForUser(userId);
21431                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21432                                        && !DEBUG_DOMAIN_VERIFICATION) {
21433                                    continue;
21434                                }
21435                                pw.println(prefix + "Package: " + ps.name);
21436                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21437                                String statusStr = IntentFilterVerificationInfo.
21438                                        getStatusStringFromValue(status);
21439                                pw.println(prefix + "Status:  " + statusStr);
21440                                pw.println();
21441                                count++;
21442                            }
21443                            if (count == 0) {
21444                                pw.println(prefix + "No configured app linkages.");
21445                                pw.println();
21446                            }
21447                        }
21448                    }
21449                }
21450            }
21451
21452            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21453                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21454            }
21455
21456            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21457                boolean printedSomething = false;
21458                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21459                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21460                        continue;
21461                    }
21462                    if (!printedSomething) {
21463                        if (dumpState.onTitlePrinted())
21464                            pw.println();
21465                        pw.println("Registered ContentProviders:");
21466                        printedSomething = true;
21467                    }
21468                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21469                    pw.print("    "); pw.println(p.toString());
21470                }
21471                printedSomething = false;
21472                for (Map.Entry<String, PackageParser.Provider> entry :
21473                        mProvidersByAuthority.entrySet()) {
21474                    PackageParser.Provider p = entry.getValue();
21475                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21476                        continue;
21477                    }
21478                    if (!printedSomething) {
21479                        if (dumpState.onTitlePrinted())
21480                            pw.println();
21481                        pw.println("ContentProvider Authorities:");
21482                        printedSomething = true;
21483                    }
21484                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21485                    pw.print("    "); pw.println(p.toString());
21486                    if (p.info != null && p.info.applicationInfo != null) {
21487                        final String appInfo = p.info.applicationInfo.toString();
21488                        pw.print("      applicationInfo="); pw.println(appInfo);
21489                    }
21490                }
21491            }
21492
21493            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21494                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21495            }
21496
21497            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21498                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21499            }
21500
21501            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21502                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21503            }
21504
21505            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21506                if (dumpState.onTitlePrinted()) pw.println();
21507                pw.println("Package Changes:");
21508                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21509                final int K = mChangedPackages.size();
21510                for (int i = 0; i < K; i++) {
21511                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21512                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21513                    final int N = changes.size();
21514                    if (N == 0) {
21515                        pw.print("    "); pw.println("No packages changed");
21516                    } else {
21517                        for (int j = 0; j < N; j++) {
21518                            final String pkgName = changes.valueAt(j);
21519                            final int sequenceNumber = changes.keyAt(j);
21520                            pw.print("    ");
21521                            pw.print("seq=");
21522                            pw.print(sequenceNumber);
21523                            pw.print(", package=");
21524                            pw.println(pkgName);
21525                        }
21526                    }
21527                }
21528            }
21529
21530            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21531                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21532            }
21533
21534            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21535                // XXX should handle packageName != null by dumping only install data that
21536                // the given package is involved with.
21537                if (dumpState.onTitlePrinted()) pw.println();
21538
21539                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21540                ipw.println();
21541                ipw.println("Frozen packages:");
21542                ipw.increaseIndent();
21543                if (mFrozenPackages.size() == 0) {
21544                    ipw.println("(none)");
21545                } else {
21546                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21547                        ipw.println(mFrozenPackages.valueAt(i));
21548                    }
21549                }
21550                ipw.decreaseIndent();
21551            }
21552
21553            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21554                if (dumpState.onTitlePrinted()) pw.println();
21555
21556                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21557                ipw.println();
21558                ipw.println("Loaded volumes:");
21559                ipw.increaseIndent();
21560                if (mLoadedVolumes.size() == 0) {
21561                    ipw.println("(none)");
21562                } else {
21563                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21564                        ipw.println(mLoadedVolumes.valueAt(i));
21565                    }
21566                }
21567                ipw.decreaseIndent();
21568            }
21569
21570            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21571                    && packageName == null) {
21572                if (dumpState.onTitlePrinted()) pw.println();
21573                pw.println("Service permissions:");
21574
21575                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21576                while (filterIterator.hasNext()) {
21577                    final ServiceIntentInfo info = filterIterator.next();
21578                    final ServiceInfo serviceInfo = info.service.info;
21579                    final String permission = serviceInfo.permission;
21580                    if (permission != null) {
21581                        pw.print("    ");
21582                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21583                        pw.print(": ");
21584                        pw.println(permission);
21585                    }
21586                }
21587            }
21588
21589            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21590                if (dumpState.onTitlePrinted()) pw.println();
21591                dumpDexoptStateLPr(pw, packageName);
21592            }
21593
21594            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21595                if (dumpState.onTitlePrinted()) pw.println();
21596                dumpCompilerStatsLPr(pw, packageName);
21597            }
21598
21599            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21600                if (dumpState.onTitlePrinted()) pw.println();
21601                mSettings.dumpReadMessagesLPr(pw, dumpState);
21602
21603                pw.println();
21604                pw.println("Package warning messages:");
21605                dumpCriticalInfo(pw, null);
21606            }
21607
21608            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21609                dumpCriticalInfo(pw, "msg,");
21610            }
21611        }
21612
21613        // PackageInstaller should be called outside of mPackages lock
21614        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21615            // XXX should handle packageName != null by dumping only install data that
21616            // the given package is involved with.
21617            if (dumpState.onTitlePrinted()) pw.println();
21618            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21619        }
21620    }
21621
21622    private void dumpProto(FileDescriptor fd) {
21623        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21624
21625        synchronized (mPackages) {
21626            final long requiredVerifierPackageToken =
21627                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21628            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21629            proto.write(
21630                    PackageServiceDumpProto.PackageShortProto.UID,
21631                    getPackageUid(
21632                            mRequiredVerifierPackage,
21633                            MATCH_DEBUG_TRIAGED_MISSING,
21634                            UserHandle.USER_SYSTEM));
21635            proto.end(requiredVerifierPackageToken);
21636
21637            if (mIntentFilterVerifierComponent != null) {
21638                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21639                final long verifierPackageToken =
21640                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21641                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21642                proto.write(
21643                        PackageServiceDumpProto.PackageShortProto.UID,
21644                        getPackageUid(
21645                                verifierPackageName,
21646                                MATCH_DEBUG_TRIAGED_MISSING,
21647                                UserHandle.USER_SYSTEM));
21648                proto.end(verifierPackageToken);
21649            }
21650
21651            dumpSharedLibrariesProto(proto);
21652            dumpFeaturesProto(proto);
21653            mSettings.dumpPackagesProto(proto);
21654            mSettings.dumpSharedUsersProto(proto);
21655            dumpCriticalInfo(proto);
21656        }
21657        proto.flush();
21658    }
21659
21660    private void dumpFeaturesProto(ProtoOutputStream proto) {
21661        synchronized (mAvailableFeatures) {
21662            final int count = mAvailableFeatures.size();
21663            for (int i = 0; i < count; i++) {
21664                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21665            }
21666        }
21667    }
21668
21669    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21670        final int count = mSharedLibraries.size();
21671        for (int i = 0; i < count; i++) {
21672            final String libName = mSharedLibraries.keyAt(i);
21673            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21674            if (versionedLib == null) {
21675                continue;
21676            }
21677            final int versionCount = versionedLib.size();
21678            for (int j = 0; j < versionCount; j++) {
21679                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21680                final long sharedLibraryToken =
21681                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21682                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21683                final boolean isJar = (libEntry.path != null);
21684                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21685                if (isJar) {
21686                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21687                } else {
21688                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21689                }
21690                proto.end(sharedLibraryToken);
21691            }
21692        }
21693    }
21694
21695    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21696        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21697        ipw.println();
21698        ipw.println("Dexopt state:");
21699        ipw.increaseIndent();
21700        Collection<PackageParser.Package> packages = null;
21701        if (packageName != null) {
21702            PackageParser.Package targetPackage = mPackages.get(packageName);
21703            if (targetPackage != null) {
21704                packages = Collections.singletonList(targetPackage);
21705            } else {
21706                ipw.println("Unable to find package: " + packageName);
21707                return;
21708            }
21709        } else {
21710            packages = mPackages.values();
21711        }
21712
21713        for (PackageParser.Package pkg : packages) {
21714            ipw.println("[" + pkg.packageName + "]");
21715            ipw.increaseIndent();
21716            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21717                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21718            ipw.decreaseIndent();
21719        }
21720    }
21721
21722    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21723        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21724        ipw.println();
21725        ipw.println("Compiler stats:");
21726        ipw.increaseIndent();
21727        Collection<PackageParser.Package> packages = null;
21728        if (packageName != null) {
21729            PackageParser.Package targetPackage = mPackages.get(packageName);
21730            if (targetPackage != null) {
21731                packages = Collections.singletonList(targetPackage);
21732            } else {
21733                ipw.println("Unable to find package: " + packageName);
21734                return;
21735            }
21736        } else {
21737            packages = mPackages.values();
21738        }
21739
21740        for (PackageParser.Package pkg : packages) {
21741            ipw.println("[" + pkg.packageName + "]");
21742            ipw.increaseIndent();
21743
21744            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21745            if (stats == null) {
21746                ipw.println("(No recorded stats)");
21747            } else {
21748                stats.dump(ipw);
21749            }
21750            ipw.decreaseIndent();
21751        }
21752    }
21753
21754    private String dumpDomainString(String packageName) {
21755        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21756                .getList();
21757        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21758
21759        ArraySet<String> result = new ArraySet<>();
21760        if (iviList.size() > 0) {
21761            for (IntentFilterVerificationInfo ivi : iviList) {
21762                for (String host : ivi.getDomains()) {
21763                    result.add(host);
21764                }
21765            }
21766        }
21767        if (filters != null && filters.size() > 0) {
21768            for (IntentFilter filter : filters) {
21769                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21770                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21771                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21772                    result.addAll(filter.getHostsList());
21773                }
21774            }
21775        }
21776
21777        StringBuilder sb = new StringBuilder(result.size() * 16);
21778        for (String domain : result) {
21779            if (sb.length() > 0) sb.append(" ");
21780            sb.append(domain);
21781        }
21782        return sb.toString();
21783    }
21784
21785    // ------- apps on sdcard specific code -------
21786    static final boolean DEBUG_SD_INSTALL = false;
21787
21788    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21789
21790    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21791
21792    private boolean mMediaMounted = false;
21793
21794    static String getEncryptKey() {
21795        try {
21796            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21797                    SD_ENCRYPTION_KEYSTORE_NAME);
21798            if (sdEncKey == null) {
21799                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21800                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21801                if (sdEncKey == null) {
21802                    Slog.e(TAG, "Failed to create encryption keys");
21803                    return null;
21804                }
21805            }
21806            return sdEncKey;
21807        } catch (NoSuchAlgorithmException nsae) {
21808            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21809            return null;
21810        } catch (IOException ioe) {
21811            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21812            return null;
21813        }
21814    }
21815
21816    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21817            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21818        final int size = infos.size();
21819        final String[] packageNames = new String[size];
21820        final int[] packageUids = new int[size];
21821        for (int i = 0; i < size; i++) {
21822            final ApplicationInfo info = infos.get(i);
21823            packageNames[i] = info.packageName;
21824            packageUids[i] = info.uid;
21825        }
21826        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21827                finishedReceiver);
21828    }
21829
21830    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21831            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21832        sendResourcesChangedBroadcast(mediaStatus, replacing,
21833                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21834    }
21835
21836    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21837            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21838        int size = pkgList.length;
21839        if (size > 0) {
21840            // Send broadcasts here
21841            Bundle extras = new Bundle();
21842            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21843            if (uidArr != null) {
21844                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21845            }
21846            if (replacing) {
21847                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21848            }
21849            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21850                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21851            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21852        }
21853    }
21854
21855    private void loadPrivatePackages(final VolumeInfo vol) {
21856        mHandler.post(new Runnable() {
21857            @Override
21858            public void run() {
21859                loadPrivatePackagesInner(vol);
21860            }
21861        });
21862    }
21863
21864    private void loadPrivatePackagesInner(VolumeInfo vol) {
21865        final String volumeUuid = vol.fsUuid;
21866        if (TextUtils.isEmpty(volumeUuid)) {
21867            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21868            return;
21869        }
21870
21871        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21872        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21873        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21874
21875        final VersionInfo ver;
21876        final List<PackageSetting> packages;
21877        synchronized (mPackages) {
21878            ver = mSettings.findOrCreateVersion(volumeUuid);
21879            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21880        }
21881
21882        for (PackageSetting ps : packages) {
21883            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21884            synchronized (mInstallLock) {
21885                final PackageParser.Package pkg;
21886                try {
21887                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21888                    loaded.add(pkg.applicationInfo);
21889
21890                } catch (PackageManagerException e) {
21891                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21892                }
21893
21894                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21895                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21896                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21897                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21898                }
21899            }
21900        }
21901
21902        // Reconcile app data for all started/unlocked users
21903        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21904        final UserManager um = mContext.getSystemService(UserManager.class);
21905        UserManagerInternal umInternal = getUserManagerInternal();
21906        for (UserInfo user : um.getUsers()) {
21907            final int flags;
21908            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21909                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21910            } else if (umInternal.isUserRunning(user.id)) {
21911                flags = StorageManager.FLAG_STORAGE_DE;
21912            } else {
21913                continue;
21914            }
21915
21916            try {
21917                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21918                synchronized (mInstallLock) {
21919                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21920                }
21921            } catch (IllegalStateException e) {
21922                // Device was probably ejected, and we'll process that event momentarily
21923                Slog.w(TAG, "Failed to prepare storage: " + e);
21924            }
21925        }
21926
21927        synchronized (mPackages) {
21928            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21929            if (sdkUpdated) {
21930                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21931                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21932            }
21933            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21934                    mPermissionCallback);
21935
21936            // Yay, everything is now upgraded
21937            ver.forceCurrent();
21938
21939            mSettings.writeLPr();
21940        }
21941
21942        for (PackageFreezer freezer : freezers) {
21943            freezer.close();
21944        }
21945
21946        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21947        sendResourcesChangedBroadcast(true, false, loaded, null);
21948        mLoadedVolumes.add(vol.getId());
21949    }
21950
21951    private void unloadPrivatePackages(final VolumeInfo vol) {
21952        mHandler.post(new Runnable() {
21953            @Override
21954            public void run() {
21955                unloadPrivatePackagesInner(vol);
21956            }
21957        });
21958    }
21959
21960    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21961        final String volumeUuid = vol.fsUuid;
21962        if (TextUtils.isEmpty(volumeUuid)) {
21963            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21964            return;
21965        }
21966
21967        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21968        synchronized (mInstallLock) {
21969        synchronized (mPackages) {
21970            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21971            for (PackageSetting ps : packages) {
21972                if (ps.pkg == null) continue;
21973
21974                final ApplicationInfo info = ps.pkg.applicationInfo;
21975                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21976                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21977
21978                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21979                        "unloadPrivatePackagesInner")) {
21980                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21981                            false, null)) {
21982                        unloaded.add(info);
21983                    } else {
21984                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21985                    }
21986                }
21987
21988                // Try very hard to release any references to this package
21989                // so we don't risk the system server being killed due to
21990                // open FDs
21991                AttributeCache.instance().removePackage(ps.name);
21992            }
21993
21994            mSettings.writeLPr();
21995        }
21996        }
21997
21998        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21999        sendResourcesChangedBroadcast(false, false, unloaded, null);
22000        mLoadedVolumes.remove(vol.getId());
22001
22002        // Try very hard to release any references to this path so we don't risk
22003        // the system server being killed due to open FDs
22004        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22005
22006        for (int i = 0; i < 3; i++) {
22007            System.gc();
22008            System.runFinalization();
22009        }
22010    }
22011
22012    private void assertPackageKnown(String volumeUuid, String packageName)
22013            throws PackageManagerException {
22014        synchronized (mPackages) {
22015            // Normalize package name to handle renamed packages
22016            packageName = normalizePackageNameLPr(packageName);
22017
22018            final PackageSetting ps = mSettings.mPackages.get(packageName);
22019            if (ps == null) {
22020                throw new PackageManagerException("Package " + packageName + " is unknown");
22021            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22022                throw new PackageManagerException(
22023                        "Package " + packageName + " found on unknown volume " + volumeUuid
22024                                + "; expected volume " + ps.volumeUuid);
22025            }
22026        }
22027    }
22028
22029    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22030            throws PackageManagerException {
22031        synchronized (mPackages) {
22032            // Normalize package name to handle renamed packages
22033            packageName = normalizePackageNameLPr(packageName);
22034
22035            final PackageSetting ps = mSettings.mPackages.get(packageName);
22036            if (ps == null) {
22037                throw new PackageManagerException("Package " + packageName + " is unknown");
22038            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22039                throw new PackageManagerException(
22040                        "Package " + packageName + " found on unknown volume " + volumeUuid
22041                                + "; expected volume " + ps.volumeUuid);
22042            } else if (!ps.getInstalled(userId)) {
22043                throw new PackageManagerException(
22044                        "Package " + packageName + " not installed for user " + userId);
22045            }
22046        }
22047    }
22048
22049    private List<String> collectAbsoluteCodePaths() {
22050        synchronized (mPackages) {
22051            List<String> codePaths = new ArrayList<>();
22052            final int packageCount = mSettings.mPackages.size();
22053            for (int i = 0; i < packageCount; i++) {
22054                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22055                codePaths.add(ps.codePath.getAbsolutePath());
22056            }
22057            return codePaths;
22058        }
22059    }
22060
22061    /**
22062     * Examine all apps present on given mounted volume, and destroy apps that
22063     * aren't expected, either due to uninstallation or reinstallation on
22064     * another volume.
22065     */
22066    private void reconcileApps(String volumeUuid) {
22067        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22068        List<File> filesToDelete = null;
22069
22070        final File[] files = FileUtils.listFilesOrEmpty(
22071                Environment.getDataAppDirectory(volumeUuid));
22072        for (File file : files) {
22073            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22074                    && !PackageInstallerService.isStageName(file.getName());
22075            if (!isPackage) {
22076                // Ignore entries which are not packages
22077                continue;
22078            }
22079
22080            String absolutePath = file.getAbsolutePath();
22081
22082            boolean pathValid = false;
22083            final int absoluteCodePathCount = absoluteCodePaths.size();
22084            for (int i = 0; i < absoluteCodePathCount; i++) {
22085                String absoluteCodePath = absoluteCodePaths.get(i);
22086                if (absolutePath.startsWith(absoluteCodePath)) {
22087                    pathValid = true;
22088                    break;
22089                }
22090            }
22091
22092            if (!pathValid) {
22093                if (filesToDelete == null) {
22094                    filesToDelete = new ArrayList<>();
22095                }
22096                filesToDelete.add(file);
22097            }
22098        }
22099
22100        if (filesToDelete != null) {
22101            final int fileToDeleteCount = filesToDelete.size();
22102            for (int i = 0; i < fileToDeleteCount; i++) {
22103                File fileToDelete = filesToDelete.get(i);
22104                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22105                synchronized (mInstallLock) {
22106                    removeCodePathLI(fileToDelete);
22107                }
22108            }
22109        }
22110    }
22111
22112    /**
22113     * Reconcile all app data for the given user.
22114     * <p>
22115     * Verifies that directories exist and that ownership and labeling is
22116     * correct for all installed apps on all mounted volumes.
22117     */
22118    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22119        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22120        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22121            final String volumeUuid = vol.getFsUuid();
22122            synchronized (mInstallLock) {
22123                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22124            }
22125        }
22126    }
22127
22128    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22129            boolean migrateAppData) {
22130        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22131    }
22132
22133    /**
22134     * Reconcile all app data on given mounted volume.
22135     * <p>
22136     * Destroys app data that isn't expected, either due to uninstallation or
22137     * reinstallation on another volume.
22138     * <p>
22139     * Verifies that directories exist and that ownership and labeling is
22140     * correct for all installed apps.
22141     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22142     */
22143    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22144            boolean migrateAppData, boolean onlyCoreApps) {
22145        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22146                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22147        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22148
22149        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22150        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22151
22152        // First look for stale data that doesn't belong, and check if things
22153        // have changed since we did our last restorecon
22154        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22155            if (StorageManager.isFileEncryptedNativeOrEmulated()
22156                    && !StorageManager.isUserKeyUnlocked(userId)) {
22157                throw new RuntimeException(
22158                        "Yikes, someone asked us to reconcile CE storage while " + userId
22159                                + " was still locked; this would have caused massive data loss!");
22160            }
22161
22162            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22163            for (File file : files) {
22164                final String packageName = file.getName();
22165                try {
22166                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22167                } catch (PackageManagerException e) {
22168                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22169                    try {
22170                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22171                                StorageManager.FLAG_STORAGE_CE, 0);
22172                    } catch (InstallerException e2) {
22173                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22174                    }
22175                }
22176            }
22177        }
22178        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22179            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22180            for (File file : files) {
22181                final String packageName = file.getName();
22182                try {
22183                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22184                } catch (PackageManagerException e) {
22185                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22186                    try {
22187                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22188                                StorageManager.FLAG_STORAGE_DE, 0);
22189                    } catch (InstallerException e2) {
22190                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22191                    }
22192                }
22193            }
22194        }
22195
22196        // Ensure that data directories are ready to roll for all packages
22197        // installed for this volume and user
22198        final List<PackageSetting> packages;
22199        synchronized (mPackages) {
22200            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22201        }
22202        int preparedCount = 0;
22203        for (PackageSetting ps : packages) {
22204            final String packageName = ps.name;
22205            if (ps.pkg == null) {
22206                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22207                // TODO: might be due to legacy ASEC apps; we should circle back
22208                // and reconcile again once they're scanned
22209                continue;
22210            }
22211            // Skip non-core apps if requested
22212            if (onlyCoreApps && !ps.pkg.coreApp) {
22213                result.add(packageName);
22214                continue;
22215            }
22216
22217            if (ps.getInstalled(userId)) {
22218                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22219                preparedCount++;
22220            }
22221        }
22222
22223        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22224        return result;
22225    }
22226
22227    /**
22228     * Prepare app data for the given app just after it was installed or
22229     * upgraded. This method carefully only touches users that it's installed
22230     * for, and it forces a restorecon to handle any seinfo changes.
22231     * <p>
22232     * Verifies that directories exist and that ownership and labeling is
22233     * correct for all installed apps. If there is an ownership mismatch, it
22234     * will try recovering system apps by wiping data; third-party app data is
22235     * left intact.
22236     * <p>
22237     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22238     */
22239    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22240        final PackageSetting ps;
22241        synchronized (mPackages) {
22242            ps = mSettings.mPackages.get(pkg.packageName);
22243            mSettings.writeKernelMappingLPr(ps);
22244        }
22245
22246        final UserManager um = mContext.getSystemService(UserManager.class);
22247        UserManagerInternal umInternal = getUserManagerInternal();
22248        for (UserInfo user : um.getUsers()) {
22249            final int flags;
22250            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22251                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22252            } else if (umInternal.isUserRunning(user.id)) {
22253                flags = StorageManager.FLAG_STORAGE_DE;
22254            } else {
22255                continue;
22256            }
22257
22258            if (ps.getInstalled(user.id)) {
22259                // TODO: when user data is locked, mark that we're still dirty
22260                prepareAppDataLIF(pkg, user.id, flags);
22261            }
22262        }
22263    }
22264
22265    /**
22266     * Prepare app data for the given app.
22267     * <p>
22268     * Verifies that directories exist and that ownership and labeling is
22269     * correct for all installed apps. If there is an ownership mismatch, this
22270     * will try recovering system apps by wiping data; third-party app data is
22271     * left intact.
22272     */
22273    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22274        if (pkg == null) {
22275            Slog.wtf(TAG, "Package was null!", new Throwable());
22276            return;
22277        }
22278        prepareAppDataLeafLIF(pkg, userId, flags);
22279        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22280        for (int i = 0; i < childCount; i++) {
22281            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22282        }
22283    }
22284
22285    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22286            boolean maybeMigrateAppData) {
22287        prepareAppDataLIF(pkg, userId, flags);
22288
22289        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22290            // We may have just shuffled around app data directories, so
22291            // prepare them one more time
22292            prepareAppDataLIF(pkg, userId, flags);
22293        }
22294    }
22295
22296    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22297        if (DEBUG_APP_DATA) {
22298            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22299                    + Integer.toHexString(flags));
22300        }
22301
22302        final String volumeUuid = pkg.volumeUuid;
22303        final String packageName = pkg.packageName;
22304        final ApplicationInfo app = pkg.applicationInfo;
22305        final int appId = UserHandle.getAppId(app.uid);
22306
22307        Preconditions.checkNotNull(app.seInfo);
22308
22309        long ceDataInode = -1;
22310        try {
22311            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22312                    appId, app.seInfo, app.targetSdkVersion);
22313        } catch (InstallerException e) {
22314            if (app.isSystemApp()) {
22315                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22316                        + ", but trying to recover: " + e);
22317                destroyAppDataLeafLIF(pkg, userId, flags);
22318                try {
22319                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22320                            appId, app.seInfo, app.targetSdkVersion);
22321                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22322                } catch (InstallerException e2) {
22323                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22324                }
22325            } else {
22326                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22327            }
22328        }
22329        // Prepare the application profiles.
22330        mArtManagerService.prepareAppProfiles(pkg, userId);
22331
22332        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22333            // TODO: mark this structure as dirty so we persist it!
22334            synchronized (mPackages) {
22335                final PackageSetting ps = mSettings.mPackages.get(packageName);
22336                if (ps != null) {
22337                    ps.setCeDataInode(ceDataInode, userId);
22338                }
22339            }
22340        }
22341
22342        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22343    }
22344
22345    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22346        if (pkg == null) {
22347            Slog.wtf(TAG, "Package was null!", new Throwable());
22348            return;
22349        }
22350        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22351        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22352        for (int i = 0; i < childCount; i++) {
22353            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22354        }
22355    }
22356
22357    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22358        final String volumeUuid = pkg.volumeUuid;
22359        final String packageName = pkg.packageName;
22360        final ApplicationInfo app = pkg.applicationInfo;
22361
22362        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22363            // Create a native library symlink only if we have native libraries
22364            // and if the native libraries are 32 bit libraries. We do not provide
22365            // this symlink for 64 bit libraries.
22366            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22367                final String nativeLibPath = app.nativeLibraryDir;
22368                try {
22369                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22370                            nativeLibPath, userId);
22371                } catch (InstallerException e) {
22372                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22373                }
22374            }
22375        }
22376    }
22377
22378    /**
22379     * For system apps on non-FBE devices, this method migrates any existing
22380     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22381     * requested by the app.
22382     */
22383    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22384        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22385                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22386            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22387                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22388            try {
22389                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22390                        storageTarget);
22391            } catch (InstallerException e) {
22392                logCriticalInfo(Log.WARN,
22393                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22394            }
22395            return true;
22396        } else {
22397            return false;
22398        }
22399    }
22400
22401    public PackageFreezer freezePackage(String packageName, String killReason) {
22402        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22403    }
22404
22405    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22406        return new PackageFreezer(packageName, userId, killReason);
22407    }
22408
22409    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22410            String killReason) {
22411        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22412    }
22413
22414    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22415            String killReason) {
22416        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22417            return new PackageFreezer();
22418        } else {
22419            return freezePackage(packageName, userId, killReason);
22420        }
22421    }
22422
22423    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22424            String killReason) {
22425        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22426    }
22427
22428    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22429            String killReason) {
22430        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22431            return new PackageFreezer();
22432        } else {
22433            return freezePackage(packageName, userId, killReason);
22434        }
22435    }
22436
22437    /**
22438     * Class that freezes and kills the given package upon creation, and
22439     * unfreezes it upon closing. This is typically used when doing surgery on
22440     * app code/data to prevent the app from running while you're working.
22441     */
22442    private class PackageFreezer implements AutoCloseable {
22443        private final String mPackageName;
22444        private final PackageFreezer[] mChildren;
22445
22446        private final boolean mWeFroze;
22447
22448        private final AtomicBoolean mClosed = new AtomicBoolean();
22449        private final CloseGuard mCloseGuard = CloseGuard.get();
22450
22451        /**
22452         * Create and return a stub freezer that doesn't actually do anything,
22453         * typically used when someone requested
22454         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22455         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22456         */
22457        public PackageFreezer() {
22458            mPackageName = null;
22459            mChildren = null;
22460            mWeFroze = false;
22461            mCloseGuard.open("close");
22462        }
22463
22464        public PackageFreezer(String packageName, int userId, String killReason) {
22465            synchronized (mPackages) {
22466                mPackageName = packageName;
22467                mWeFroze = mFrozenPackages.add(mPackageName);
22468
22469                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22470                if (ps != null) {
22471                    killApplication(ps.name, ps.appId, userId, killReason);
22472                }
22473
22474                final PackageParser.Package p = mPackages.get(packageName);
22475                if (p != null && p.childPackages != null) {
22476                    final int N = p.childPackages.size();
22477                    mChildren = new PackageFreezer[N];
22478                    for (int i = 0; i < N; i++) {
22479                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22480                                userId, killReason);
22481                    }
22482                } else {
22483                    mChildren = null;
22484                }
22485            }
22486            mCloseGuard.open("close");
22487        }
22488
22489        @Override
22490        protected void finalize() throws Throwable {
22491            try {
22492                if (mCloseGuard != null) {
22493                    mCloseGuard.warnIfOpen();
22494                }
22495
22496                close();
22497            } finally {
22498                super.finalize();
22499            }
22500        }
22501
22502        @Override
22503        public void close() {
22504            mCloseGuard.close();
22505            if (mClosed.compareAndSet(false, true)) {
22506                synchronized (mPackages) {
22507                    if (mWeFroze) {
22508                        mFrozenPackages.remove(mPackageName);
22509                    }
22510
22511                    if (mChildren != null) {
22512                        for (PackageFreezer freezer : mChildren) {
22513                            freezer.close();
22514                        }
22515                    }
22516                }
22517            }
22518        }
22519    }
22520
22521    /**
22522     * Verify that given package is currently frozen.
22523     */
22524    private void checkPackageFrozen(String packageName) {
22525        synchronized (mPackages) {
22526            if (!mFrozenPackages.contains(packageName)) {
22527                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22528            }
22529        }
22530    }
22531
22532    @Override
22533    public int movePackage(final String packageName, final String volumeUuid) {
22534        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22535
22536        final int callingUid = Binder.getCallingUid();
22537        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22538        final int moveId = mNextMoveId.getAndIncrement();
22539        mHandler.post(new Runnable() {
22540            @Override
22541            public void run() {
22542                try {
22543                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22544                } catch (PackageManagerException e) {
22545                    Slog.w(TAG, "Failed to move " + packageName, e);
22546                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22547                }
22548            }
22549        });
22550        return moveId;
22551    }
22552
22553    private void movePackageInternal(final String packageName, final String volumeUuid,
22554            final int moveId, final int callingUid, UserHandle user)
22555                    throws PackageManagerException {
22556        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22557        final PackageManager pm = mContext.getPackageManager();
22558
22559        final boolean currentAsec;
22560        final String currentVolumeUuid;
22561        final File codeFile;
22562        final String installerPackageName;
22563        final String packageAbiOverride;
22564        final int appId;
22565        final String seinfo;
22566        final String label;
22567        final int targetSdkVersion;
22568        final PackageFreezer freezer;
22569        final int[] installedUserIds;
22570
22571        // reader
22572        synchronized (mPackages) {
22573            final PackageParser.Package pkg = mPackages.get(packageName);
22574            final PackageSetting ps = mSettings.mPackages.get(packageName);
22575            if (pkg == null
22576                    || ps == null
22577                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22578                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22579            }
22580            if (pkg.applicationInfo.isSystemApp()) {
22581                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22582                        "Cannot move system application");
22583            }
22584
22585            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22586            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22587                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22588            if (isInternalStorage && !allow3rdPartyOnInternal) {
22589                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22590                        "3rd party apps are not allowed on internal storage");
22591            }
22592
22593            if (pkg.applicationInfo.isExternalAsec()) {
22594                currentAsec = true;
22595                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22596            } else if (pkg.applicationInfo.isForwardLocked()) {
22597                currentAsec = true;
22598                currentVolumeUuid = "forward_locked";
22599            } else {
22600                currentAsec = false;
22601                currentVolumeUuid = ps.volumeUuid;
22602
22603                final File probe = new File(pkg.codePath);
22604                final File probeOat = new File(probe, "oat");
22605                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22606                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22607                            "Move only supported for modern cluster style installs");
22608                }
22609            }
22610
22611            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22612                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22613                        "Package already moved to " + volumeUuid);
22614            }
22615            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22616                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22617                        "Device admin cannot be moved");
22618            }
22619
22620            if (mFrozenPackages.contains(packageName)) {
22621                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22622                        "Failed to move already frozen package");
22623            }
22624
22625            codeFile = new File(pkg.codePath);
22626            installerPackageName = ps.installerPackageName;
22627            packageAbiOverride = ps.cpuAbiOverrideString;
22628            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22629            seinfo = pkg.applicationInfo.seInfo;
22630            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22631            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22632            freezer = freezePackage(packageName, "movePackageInternal");
22633            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22634        }
22635
22636        final Bundle extras = new Bundle();
22637        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22638        extras.putString(Intent.EXTRA_TITLE, label);
22639        mMoveCallbacks.notifyCreated(moveId, extras);
22640
22641        int installFlags;
22642        final boolean moveCompleteApp;
22643        final File measurePath;
22644
22645        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22646            installFlags = INSTALL_INTERNAL;
22647            moveCompleteApp = !currentAsec;
22648            measurePath = Environment.getDataAppDirectory(volumeUuid);
22649        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22650            installFlags = INSTALL_EXTERNAL;
22651            moveCompleteApp = false;
22652            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22653        } else {
22654            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22655            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22656                    || !volume.isMountedWritable()) {
22657                freezer.close();
22658                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22659                        "Move location not mounted private volume");
22660            }
22661
22662            Preconditions.checkState(!currentAsec);
22663
22664            installFlags = INSTALL_INTERNAL;
22665            moveCompleteApp = true;
22666            measurePath = Environment.getDataAppDirectory(volumeUuid);
22667        }
22668
22669        // If we're moving app data around, we need all the users unlocked
22670        if (moveCompleteApp) {
22671            for (int userId : installedUserIds) {
22672                if (StorageManager.isFileEncryptedNativeOrEmulated()
22673                        && !StorageManager.isUserKeyUnlocked(userId)) {
22674                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22675                            "User " + userId + " must be unlocked");
22676                }
22677            }
22678        }
22679
22680        final PackageStats stats = new PackageStats(null, -1);
22681        synchronized (mInstaller) {
22682            for (int userId : installedUserIds) {
22683                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22684                    freezer.close();
22685                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22686                            "Failed to measure package size");
22687                }
22688            }
22689        }
22690
22691        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22692                + stats.dataSize);
22693
22694        final long startFreeBytes = measurePath.getUsableSpace();
22695        final long sizeBytes;
22696        if (moveCompleteApp) {
22697            sizeBytes = stats.codeSize + stats.dataSize;
22698        } else {
22699            sizeBytes = stats.codeSize;
22700        }
22701
22702        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22703            freezer.close();
22704            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22705                    "Not enough free space to move");
22706        }
22707
22708        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22709
22710        final CountDownLatch installedLatch = new CountDownLatch(1);
22711        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22712            @Override
22713            public void onUserActionRequired(Intent intent) throws RemoteException {
22714                throw new IllegalStateException();
22715            }
22716
22717            @Override
22718            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22719                    Bundle extras) throws RemoteException {
22720                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22721                        + PackageManager.installStatusToString(returnCode, msg));
22722
22723                installedLatch.countDown();
22724                freezer.close();
22725
22726                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22727                switch (status) {
22728                    case PackageInstaller.STATUS_SUCCESS:
22729                        mMoveCallbacks.notifyStatusChanged(moveId,
22730                                PackageManager.MOVE_SUCCEEDED);
22731                        break;
22732                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22733                        mMoveCallbacks.notifyStatusChanged(moveId,
22734                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22735                        break;
22736                    default:
22737                        mMoveCallbacks.notifyStatusChanged(moveId,
22738                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22739                        break;
22740                }
22741            }
22742        };
22743
22744        final MoveInfo move;
22745        if (moveCompleteApp) {
22746            // Kick off a thread to report progress estimates
22747            new Thread() {
22748                @Override
22749                public void run() {
22750                    while (true) {
22751                        try {
22752                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22753                                break;
22754                            }
22755                        } catch (InterruptedException ignored) {
22756                        }
22757
22758                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22759                        final int progress = 10 + (int) MathUtils.constrain(
22760                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22761                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22762                    }
22763                }
22764            }.start();
22765
22766            final String dataAppName = codeFile.getName();
22767            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22768                    dataAppName, appId, seinfo, targetSdkVersion);
22769        } else {
22770            move = null;
22771        }
22772
22773        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22774
22775        final Message msg = mHandler.obtainMessage(INIT_COPY);
22776        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22777        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22778                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22779                packageAbiOverride, null /*grantedPermissions*/,
22780                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22781        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22782        msg.obj = params;
22783
22784        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22785                System.identityHashCode(msg.obj));
22786        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22787                System.identityHashCode(msg.obj));
22788
22789        mHandler.sendMessage(msg);
22790    }
22791
22792    @Override
22793    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22794        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22795
22796        final int realMoveId = mNextMoveId.getAndIncrement();
22797        final Bundle extras = new Bundle();
22798        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22799        mMoveCallbacks.notifyCreated(realMoveId, extras);
22800
22801        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22802            @Override
22803            public void onCreated(int moveId, Bundle extras) {
22804                // Ignored
22805            }
22806
22807            @Override
22808            public void onStatusChanged(int moveId, int status, long estMillis) {
22809                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22810            }
22811        };
22812
22813        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22814        storage.setPrimaryStorageUuid(volumeUuid, callback);
22815        return realMoveId;
22816    }
22817
22818    @Override
22819    public int getMoveStatus(int moveId) {
22820        mContext.enforceCallingOrSelfPermission(
22821                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22822        return mMoveCallbacks.mLastStatus.get(moveId);
22823    }
22824
22825    @Override
22826    public void registerMoveCallback(IPackageMoveObserver callback) {
22827        mContext.enforceCallingOrSelfPermission(
22828                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22829        mMoveCallbacks.register(callback);
22830    }
22831
22832    @Override
22833    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22834        mContext.enforceCallingOrSelfPermission(
22835                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22836        mMoveCallbacks.unregister(callback);
22837    }
22838
22839    @Override
22840    public boolean setInstallLocation(int loc) {
22841        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22842                null);
22843        if (getInstallLocation() == loc) {
22844            return true;
22845        }
22846        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22847                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22848            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22849                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22850            return true;
22851        }
22852        return false;
22853   }
22854
22855    @Override
22856    public int getInstallLocation() {
22857        // allow instant app access
22858        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22859                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22860                PackageHelper.APP_INSTALL_AUTO);
22861    }
22862
22863    /** Called by UserManagerService */
22864    void cleanUpUser(UserManagerService userManager, int userHandle) {
22865        synchronized (mPackages) {
22866            mDirtyUsers.remove(userHandle);
22867            mUserNeedsBadging.delete(userHandle);
22868            mSettings.removeUserLPw(userHandle);
22869            mPendingBroadcasts.remove(userHandle);
22870            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22871            removeUnusedPackagesLPw(userManager, userHandle);
22872        }
22873    }
22874
22875    /**
22876     * We're removing userHandle and would like to remove any downloaded packages
22877     * that are no longer in use by any other user.
22878     * @param userHandle the user being removed
22879     */
22880    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22881        final boolean DEBUG_CLEAN_APKS = false;
22882        int [] users = userManager.getUserIds();
22883        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22884        while (psit.hasNext()) {
22885            PackageSetting ps = psit.next();
22886            if (ps.pkg == null) {
22887                continue;
22888            }
22889            final String packageName = ps.pkg.packageName;
22890            // Skip over if system app
22891            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22892                continue;
22893            }
22894            if (DEBUG_CLEAN_APKS) {
22895                Slog.i(TAG, "Checking package " + packageName);
22896            }
22897            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22898            if (keep) {
22899                if (DEBUG_CLEAN_APKS) {
22900                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22901                }
22902            } else {
22903                for (int i = 0; i < users.length; i++) {
22904                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22905                        keep = true;
22906                        if (DEBUG_CLEAN_APKS) {
22907                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22908                                    + users[i]);
22909                        }
22910                        break;
22911                    }
22912                }
22913            }
22914            if (!keep) {
22915                if (DEBUG_CLEAN_APKS) {
22916                    Slog.i(TAG, "  Removing package " + packageName);
22917                }
22918                mHandler.post(new Runnable() {
22919                    public void run() {
22920                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22921                                userHandle, 0);
22922                    } //end run
22923                });
22924            }
22925        }
22926    }
22927
22928    /** Called by UserManagerService */
22929    void createNewUser(int userId, String[] disallowedPackages) {
22930        synchronized (mInstallLock) {
22931            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22932        }
22933        synchronized (mPackages) {
22934            scheduleWritePackageRestrictionsLocked(userId);
22935            scheduleWritePackageListLocked(userId);
22936            applyFactoryDefaultBrowserLPw(userId);
22937            primeDomainVerificationsLPw(userId);
22938        }
22939    }
22940
22941    void onNewUserCreated(final int userId) {
22942        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22943        synchronized(mPackages) {
22944            // If permission review for legacy apps is required, we represent
22945            // dagerous permissions for such apps as always granted runtime
22946            // permissions to keep per user flag state whether review is needed.
22947            // Hence, if a new user is added we have to propagate dangerous
22948            // permission grants for these legacy apps.
22949            if (mSettings.mPermissions.mPermissionReviewRequired) {
22950// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22951                mPermissionManager.updateAllPermissions(
22952                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22953                        mPermissionCallback);
22954            }
22955        }
22956    }
22957
22958    @Override
22959    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22960        mContext.enforceCallingOrSelfPermission(
22961                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22962                "Only package verification agents can read the verifier device identity");
22963
22964        synchronized (mPackages) {
22965            return mSettings.getVerifierDeviceIdentityLPw();
22966        }
22967    }
22968
22969    @Override
22970    public void setPermissionEnforced(String permission, boolean enforced) {
22971        // TODO: Now that we no longer change GID for storage, this should to away.
22972        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22973                "setPermissionEnforced");
22974        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22975            synchronized (mPackages) {
22976                if (mSettings.mReadExternalStorageEnforced == null
22977                        || mSettings.mReadExternalStorageEnforced != enforced) {
22978                    mSettings.mReadExternalStorageEnforced =
22979                            enforced ? Boolean.TRUE : Boolean.FALSE;
22980                    mSettings.writeLPr();
22981                }
22982            }
22983            // kill any non-foreground processes so we restart them and
22984            // grant/revoke the GID.
22985            final IActivityManager am = ActivityManager.getService();
22986            if (am != null) {
22987                final long token = Binder.clearCallingIdentity();
22988                try {
22989                    am.killProcessesBelowForeground("setPermissionEnforcement");
22990                } catch (RemoteException e) {
22991                } finally {
22992                    Binder.restoreCallingIdentity(token);
22993                }
22994            }
22995        } else {
22996            throw new IllegalArgumentException("No selective enforcement for " + permission);
22997        }
22998    }
22999
23000    @Override
23001    @Deprecated
23002    public boolean isPermissionEnforced(String permission) {
23003        // allow instant applications
23004        return true;
23005    }
23006
23007    @Override
23008    public boolean isStorageLow() {
23009        // allow instant applications
23010        final long token = Binder.clearCallingIdentity();
23011        try {
23012            final DeviceStorageMonitorInternal
23013                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23014            if (dsm != null) {
23015                return dsm.isMemoryLow();
23016            } else {
23017                return false;
23018            }
23019        } finally {
23020            Binder.restoreCallingIdentity(token);
23021        }
23022    }
23023
23024    @Override
23025    public IPackageInstaller getPackageInstaller() {
23026        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23027            return null;
23028        }
23029        return mInstallerService;
23030    }
23031
23032    @Override
23033    public IArtManager getArtManager() {
23034        return mArtManagerService;
23035    }
23036
23037    private boolean userNeedsBadging(int userId) {
23038        int index = mUserNeedsBadging.indexOfKey(userId);
23039        if (index < 0) {
23040            final UserInfo userInfo;
23041            final long token = Binder.clearCallingIdentity();
23042            try {
23043                userInfo = sUserManager.getUserInfo(userId);
23044            } finally {
23045                Binder.restoreCallingIdentity(token);
23046            }
23047            final boolean b;
23048            if (userInfo != null && userInfo.isManagedProfile()) {
23049                b = true;
23050            } else {
23051                b = false;
23052            }
23053            mUserNeedsBadging.put(userId, b);
23054            return b;
23055        }
23056        return mUserNeedsBadging.valueAt(index);
23057    }
23058
23059    @Override
23060    public KeySet getKeySetByAlias(String packageName, String alias) {
23061        if (packageName == null || alias == null) {
23062            return null;
23063        }
23064        synchronized(mPackages) {
23065            final PackageParser.Package pkg = mPackages.get(packageName);
23066            if (pkg == null) {
23067                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23068                throw new IllegalArgumentException("Unknown package: " + packageName);
23069            }
23070            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23071            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23072                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23073                throw new IllegalArgumentException("Unknown package: " + packageName);
23074            }
23075            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23076            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23077        }
23078    }
23079
23080    @Override
23081    public KeySet getSigningKeySet(String packageName) {
23082        if (packageName == null) {
23083            return null;
23084        }
23085        synchronized(mPackages) {
23086            final int callingUid = Binder.getCallingUid();
23087            final int callingUserId = UserHandle.getUserId(callingUid);
23088            final PackageParser.Package pkg = mPackages.get(packageName);
23089            if (pkg == null) {
23090                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23091                throw new IllegalArgumentException("Unknown package: " + packageName);
23092            }
23093            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23094            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23095                // filter and pretend the package doesn't exist
23096                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23097                        + ", uid:" + callingUid);
23098                throw new IllegalArgumentException("Unknown package: " + packageName);
23099            }
23100            if (pkg.applicationInfo.uid != callingUid
23101                    && Process.SYSTEM_UID != callingUid) {
23102                throw new SecurityException("May not access signing KeySet of other apps.");
23103            }
23104            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23105            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23106        }
23107    }
23108
23109    @Override
23110    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23111        final int callingUid = Binder.getCallingUid();
23112        if (getInstantAppPackageName(callingUid) != null) {
23113            return false;
23114        }
23115        if (packageName == null || ks == null) {
23116            return false;
23117        }
23118        synchronized(mPackages) {
23119            final PackageParser.Package pkg = mPackages.get(packageName);
23120            if (pkg == null
23121                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23122                            UserHandle.getUserId(callingUid))) {
23123                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23124                throw new IllegalArgumentException("Unknown package: " + packageName);
23125            }
23126            IBinder ksh = ks.getToken();
23127            if (ksh instanceof KeySetHandle) {
23128                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23129                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23130            }
23131            return false;
23132        }
23133    }
23134
23135    @Override
23136    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23137        final int callingUid = Binder.getCallingUid();
23138        if (getInstantAppPackageName(callingUid) != null) {
23139            return false;
23140        }
23141        if (packageName == null || ks == null) {
23142            return false;
23143        }
23144        synchronized(mPackages) {
23145            final PackageParser.Package pkg = mPackages.get(packageName);
23146            if (pkg == null
23147                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23148                            UserHandle.getUserId(callingUid))) {
23149                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23150                throw new IllegalArgumentException("Unknown package: " + packageName);
23151            }
23152            IBinder ksh = ks.getToken();
23153            if (ksh instanceof KeySetHandle) {
23154                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23155                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23156            }
23157            return false;
23158        }
23159    }
23160
23161    private void deletePackageIfUnusedLPr(final String packageName) {
23162        PackageSetting ps = mSettings.mPackages.get(packageName);
23163        if (ps == null) {
23164            return;
23165        }
23166        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23167            // TODO Implement atomic delete if package is unused
23168            // It is currently possible that the package will be deleted even if it is installed
23169            // after this method returns.
23170            mHandler.post(new Runnable() {
23171                public void run() {
23172                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23173                            0, PackageManager.DELETE_ALL_USERS);
23174                }
23175            });
23176        }
23177    }
23178
23179    /**
23180     * Check and throw if the given before/after packages would be considered a
23181     * downgrade.
23182     */
23183    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23184            throws PackageManagerException {
23185        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23186            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23187                    "Update version code " + after.versionCode + " is older than current "
23188                    + before.getLongVersionCode());
23189        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23190            if (after.baseRevisionCode < before.baseRevisionCode) {
23191                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23192                        "Update base revision code " + after.baseRevisionCode
23193                        + " is older than current " + before.baseRevisionCode);
23194            }
23195
23196            if (!ArrayUtils.isEmpty(after.splitNames)) {
23197                for (int i = 0; i < after.splitNames.length; i++) {
23198                    final String splitName = after.splitNames[i];
23199                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23200                    if (j != -1) {
23201                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23202                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23203                                    "Update split " + splitName + " revision code "
23204                                    + after.splitRevisionCodes[i] + " is older than current "
23205                                    + before.splitRevisionCodes[j]);
23206                        }
23207                    }
23208                }
23209            }
23210        }
23211    }
23212
23213    private static class MoveCallbacks extends Handler {
23214        private static final int MSG_CREATED = 1;
23215        private static final int MSG_STATUS_CHANGED = 2;
23216
23217        private final RemoteCallbackList<IPackageMoveObserver>
23218                mCallbacks = new RemoteCallbackList<>();
23219
23220        private final SparseIntArray mLastStatus = new SparseIntArray();
23221
23222        public MoveCallbacks(Looper looper) {
23223            super(looper);
23224        }
23225
23226        public void register(IPackageMoveObserver callback) {
23227            mCallbacks.register(callback);
23228        }
23229
23230        public void unregister(IPackageMoveObserver callback) {
23231            mCallbacks.unregister(callback);
23232        }
23233
23234        @Override
23235        public void handleMessage(Message msg) {
23236            final SomeArgs args = (SomeArgs) msg.obj;
23237            final int n = mCallbacks.beginBroadcast();
23238            for (int i = 0; i < n; i++) {
23239                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23240                try {
23241                    invokeCallback(callback, msg.what, args);
23242                } catch (RemoteException ignored) {
23243                }
23244            }
23245            mCallbacks.finishBroadcast();
23246            args.recycle();
23247        }
23248
23249        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23250                throws RemoteException {
23251            switch (what) {
23252                case MSG_CREATED: {
23253                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23254                    break;
23255                }
23256                case MSG_STATUS_CHANGED: {
23257                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23258                    break;
23259                }
23260            }
23261        }
23262
23263        private void notifyCreated(int moveId, Bundle extras) {
23264            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23265
23266            final SomeArgs args = SomeArgs.obtain();
23267            args.argi1 = moveId;
23268            args.arg2 = extras;
23269            obtainMessage(MSG_CREATED, args).sendToTarget();
23270        }
23271
23272        private void notifyStatusChanged(int moveId, int status) {
23273            notifyStatusChanged(moveId, status, -1);
23274        }
23275
23276        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23277            Slog.v(TAG, "Move " + moveId + " status " + status);
23278
23279            final SomeArgs args = SomeArgs.obtain();
23280            args.argi1 = moveId;
23281            args.argi2 = status;
23282            args.arg3 = estMillis;
23283            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23284
23285            synchronized (mLastStatus) {
23286                mLastStatus.put(moveId, status);
23287            }
23288        }
23289    }
23290
23291    private final static class OnPermissionChangeListeners extends Handler {
23292        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23293
23294        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23295                new RemoteCallbackList<>();
23296
23297        public OnPermissionChangeListeners(Looper looper) {
23298            super(looper);
23299        }
23300
23301        @Override
23302        public void handleMessage(Message msg) {
23303            switch (msg.what) {
23304                case MSG_ON_PERMISSIONS_CHANGED: {
23305                    final int uid = msg.arg1;
23306                    handleOnPermissionsChanged(uid);
23307                } break;
23308            }
23309        }
23310
23311        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23312            mPermissionListeners.register(listener);
23313
23314        }
23315
23316        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23317            mPermissionListeners.unregister(listener);
23318        }
23319
23320        public void onPermissionsChanged(int uid) {
23321            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23322                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23323            }
23324        }
23325
23326        private void handleOnPermissionsChanged(int uid) {
23327            final int count = mPermissionListeners.beginBroadcast();
23328            try {
23329                for (int i = 0; i < count; i++) {
23330                    IOnPermissionsChangeListener callback = mPermissionListeners
23331                            .getBroadcastItem(i);
23332                    try {
23333                        callback.onPermissionsChanged(uid);
23334                    } catch (RemoteException e) {
23335                        Log.e(TAG, "Permission listener is dead", e);
23336                    }
23337                }
23338            } finally {
23339                mPermissionListeners.finishBroadcast();
23340            }
23341        }
23342    }
23343
23344    private class PackageManagerNative extends IPackageManagerNative.Stub {
23345        @Override
23346        public String[] getNamesForUids(int[] uids) throws RemoteException {
23347            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23348            // massage results so they can be parsed by the native binder
23349            for (int i = results.length - 1; i >= 0; --i) {
23350                if (results[i] == null) {
23351                    results[i] = "";
23352                }
23353            }
23354            return results;
23355        }
23356
23357        // NB: this differentiates between preloads and sideloads
23358        @Override
23359        public String getInstallerForPackage(String packageName) throws RemoteException {
23360            final String installerName = getInstallerPackageName(packageName);
23361            if (!TextUtils.isEmpty(installerName)) {
23362                return installerName;
23363            }
23364            // differentiate between preload and sideload
23365            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23366            ApplicationInfo appInfo = getApplicationInfo(packageName,
23367                                    /*flags*/ 0,
23368                                    /*userId*/ callingUser);
23369            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23370                return "preload";
23371            }
23372            return "";
23373        }
23374
23375        @Override
23376        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23377            try {
23378                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23379                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23380                if (pInfo != null) {
23381                    return pInfo.getLongVersionCode();
23382                }
23383            } catch (Exception e) {
23384            }
23385            return 0;
23386        }
23387    }
23388
23389    private class PackageManagerInternalImpl extends PackageManagerInternal {
23390        @Override
23391        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23392                int flagValues, int userId) {
23393            PackageManagerService.this.updatePermissionFlags(
23394                    permName, packageName, flagMask, flagValues, userId);
23395        }
23396
23397        @Override
23398        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23399            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23400        }
23401
23402        @Override
23403        public boolean isInstantApp(String packageName, int userId) {
23404            return PackageManagerService.this.isInstantApp(packageName, userId);
23405        }
23406
23407        @Override
23408        public String getInstantAppPackageName(int uid) {
23409            return PackageManagerService.this.getInstantAppPackageName(uid);
23410        }
23411
23412        @Override
23413        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23414            synchronized (mPackages) {
23415                return PackageManagerService.this.filterAppAccessLPr(
23416                        (PackageSetting) pkg.mExtras, callingUid, userId);
23417            }
23418        }
23419
23420        @Override
23421        public PackageParser.Package getPackage(String packageName) {
23422            synchronized (mPackages) {
23423                packageName = resolveInternalPackageNameLPr(
23424                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23425                return mPackages.get(packageName);
23426            }
23427        }
23428
23429        @Override
23430        public PackageList getPackageList(PackageListObserver observer) {
23431            synchronized (mPackages) {
23432                final int N = mPackages.size();
23433                final ArrayList<String> list = new ArrayList<>(N);
23434                for (int i = 0; i < N; i++) {
23435                    list.add(mPackages.keyAt(i));
23436                }
23437                final PackageList packageList = new PackageList(list, observer);
23438                if (observer != null) {
23439                    mPackageListObservers.add(packageList);
23440                }
23441                return packageList;
23442            }
23443        }
23444
23445        @Override
23446        public void removePackageListObserver(PackageListObserver observer) {
23447            synchronized (mPackages) {
23448                mPackageListObservers.remove(observer);
23449            }
23450        }
23451
23452        @Override
23453        public PackageParser.Package getDisabledPackage(String packageName) {
23454            synchronized (mPackages) {
23455                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23456                return (ps != null) ? ps.pkg : null;
23457            }
23458        }
23459
23460        @Override
23461        public String getKnownPackageName(int knownPackage, int userId) {
23462            switch(knownPackage) {
23463                case PackageManagerInternal.PACKAGE_BROWSER:
23464                    return getDefaultBrowserPackageName(userId);
23465                case PackageManagerInternal.PACKAGE_INSTALLER:
23466                    return mRequiredInstallerPackage;
23467                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23468                    return mSetupWizardPackage;
23469                case PackageManagerInternal.PACKAGE_SYSTEM:
23470                    return "android";
23471                case PackageManagerInternal.PACKAGE_VERIFIER:
23472                    return mRequiredVerifierPackage;
23473            }
23474            return null;
23475        }
23476
23477        @Override
23478        public boolean isResolveActivityComponent(ComponentInfo component) {
23479            return mResolveActivity.packageName.equals(component.packageName)
23480                    && mResolveActivity.name.equals(component.name);
23481        }
23482
23483        @Override
23484        public void setLocationPackagesProvider(PackagesProvider provider) {
23485            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23486        }
23487
23488        @Override
23489        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23490            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23491        }
23492
23493        @Override
23494        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23495            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23496        }
23497
23498        @Override
23499        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23500            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23501        }
23502
23503        @Override
23504        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23505            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23506        }
23507
23508        @Override
23509        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23510            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23511        }
23512
23513        @Override
23514        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23515            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23516        }
23517
23518        @Override
23519        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23520            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23521        }
23522
23523        @Override
23524        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23525            synchronized (mPackages) {
23526                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23527            }
23528            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23529        }
23530
23531        @Override
23532        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23533            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23534                    packageName, userId);
23535        }
23536
23537        @Override
23538        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23539            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23540                    packageName, userId);
23541        }
23542
23543        @Override
23544        public void setKeepUninstalledPackages(final List<String> packageList) {
23545            Preconditions.checkNotNull(packageList);
23546            List<String> removedFromList = null;
23547            synchronized (mPackages) {
23548                if (mKeepUninstalledPackages != null) {
23549                    final int packagesCount = mKeepUninstalledPackages.size();
23550                    for (int i = 0; i < packagesCount; i++) {
23551                        String oldPackage = mKeepUninstalledPackages.get(i);
23552                        if (packageList != null && packageList.contains(oldPackage)) {
23553                            continue;
23554                        }
23555                        if (removedFromList == null) {
23556                            removedFromList = new ArrayList<>();
23557                        }
23558                        removedFromList.add(oldPackage);
23559                    }
23560                }
23561                mKeepUninstalledPackages = new ArrayList<>(packageList);
23562                if (removedFromList != null) {
23563                    final int removedCount = removedFromList.size();
23564                    for (int i = 0; i < removedCount; i++) {
23565                        deletePackageIfUnusedLPr(removedFromList.get(i));
23566                    }
23567                }
23568            }
23569        }
23570
23571        @Override
23572        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23573            synchronized (mPackages) {
23574                return mPermissionManager.isPermissionsReviewRequired(
23575                        mPackages.get(packageName), userId);
23576            }
23577        }
23578
23579        @Override
23580        public PackageInfo getPackageInfo(
23581                String packageName, int flags, int filterCallingUid, int userId) {
23582            return PackageManagerService.this
23583                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23584                            flags, filterCallingUid, userId);
23585        }
23586
23587        @Override
23588        public int getPackageUid(String packageName, int flags, int userId) {
23589            return PackageManagerService.this
23590                    .getPackageUid(packageName, flags, userId);
23591        }
23592
23593        @Override
23594        public ApplicationInfo getApplicationInfo(
23595                String packageName, int flags, int filterCallingUid, int userId) {
23596            return PackageManagerService.this
23597                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23598        }
23599
23600        @Override
23601        public ActivityInfo getActivityInfo(
23602                ComponentName component, int flags, int filterCallingUid, int userId) {
23603            return PackageManagerService.this
23604                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23605        }
23606
23607        @Override
23608        public List<ResolveInfo> queryIntentActivities(
23609                Intent intent, int flags, int filterCallingUid, int userId) {
23610            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23611            return PackageManagerService.this
23612                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23613                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23614        }
23615
23616        @Override
23617        public List<ResolveInfo> queryIntentServices(
23618                Intent intent, int flags, int callingUid, int userId) {
23619            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23620            return PackageManagerService.this
23621                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23622                            false);
23623        }
23624
23625        @Override
23626        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23627                int userId) {
23628            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23629        }
23630
23631        @Override
23632        public void setDeviceAndProfileOwnerPackages(
23633                int deviceOwnerUserId, String deviceOwnerPackage,
23634                SparseArray<String> profileOwnerPackages) {
23635            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23636                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23637        }
23638
23639        @Override
23640        public boolean isPackageDataProtected(int userId, String packageName) {
23641            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23642        }
23643
23644        @Override
23645        public boolean isPackageEphemeral(int userId, String packageName) {
23646            synchronized (mPackages) {
23647                final PackageSetting ps = mSettings.mPackages.get(packageName);
23648                return ps != null ? ps.getInstantApp(userId) : false;
23649            }
23650        }
23651
23652        @Override
23653        public boolean wasPackageEverLaunched(String packageName, int userId) {
23654            synchronized (mPackages) {
23655                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23656            }
23657        }
23658
23659        @Override
23660        public void grantRuntimePermission(String packageName, String permName, int userId,
23661                boolean overridePolicy) {
23662            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23663                    permName, packageName, overridePolicy, getCallingUid(), userId,
23664                    mPermissionCallback);
23665        }
23666
23667        @Override
23668        public void revokeRuntimePermission(String packageName, String permName, int userId,
23669                boolean overridePolicy) {
23670            mPermissionManager.revokeRuntimePermission(
23671                    permName, packageName, overridePolicy, getCallingUid(), userId,
23672                    mPermissionCallback);
23673        }
23674
23675        @Override
23676        public String getNameForUid(int uid) {
23677            return PackageManagerService.this.getNameForUid(uid);
23678        }
23679
23680        @Override
23681        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23682                Intent origIntent, String resolvedType, String callingPackage,
23683                Bundle verificationBundle, int userId) {
23684            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23685                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23686                    userId);
23687        }
23688
23689        @Override
23690        public void grantEphemeralAccess(int userId, Intent intent,
23691                int targetAppId, int ephemeralAppId) {
23692            synchronized (mPackages) {
23693                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23694                        targetAppId, ephemeralAppId);
23695            }
23696        }
23697
23698        @Override
23699        public boolean isInstantAppInstallerComponent(ComponentName component) {
23700            synchronized (mPackages) {
23701                return mInstantAppInstallerActivity != null
23702                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23703            }
23704        }
23705
23706        @Override
23707        public void pruneInstantApps() {
23708            mInstantAppRegistry.pruneInstantApps();
23709        }
23710
23711        @Override
23712        public String getSetupWizardPackageName() {
23713            return mSetupWizardPackage;
23714        }
23715
23716        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23717            if (policy != null) {
23718                mExternalSourcesPolicy = policy;
23719            }
23720        }
23721
23722        @Override
23723        public boolean isPackagePersistent(String packageName) {
23724            synchronized (mPackages) {
23725                PackageParser.Package pkg = mPackages.get(packageName);
23726                return pkg != null
23727                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23728                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23729                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23730                        : false;
23731            }
23732        }
23733
23734        @Override
23735        public boolean isLegacySystemApp(Package pkg) {
23736            synchronized (mPackages) {
23737                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23738                return mPromoteSystemApps
23739                        && ps.isSystem()
23740                        && mExistingSystemPackages.contains(ps.name);
23741            }
23742        }
23743
23744        @Override
23745        public List<PackageInfo> getOverlayPackages(int userId) {
23746            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23747            synchronized (mPackages) {
23748                for (PackageParser.Package p : mPackages.values()) {
23749                    if (p.mOverlayTarget != null) {
23750                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23751                        if (pkg != null) {
23752                            overlayPackages.add(pkg);
23753                        }
23754                    }
23755                }
23756            }
23757            return overlayPackages;
23758        }
23759
23760        @Override
23761        public List<String> getTargetPackageNames(int userId) {
23762            List<String> targetPackages = new ArrayList<>();
23763            synchronized (mPackages) {
23764                for (PackageParser.Package p : mPackages.values()) {
23765                    if (p.mOverlayTarget == null) {
23766                        targetPackages.add(p.packageName);
23767                    }
23768                }
23769            }
23770            return targetPackages;
23771        }
23772
23773        @Override
23774        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23775                @Nullable List<String> overlayPackageNames) {
23776            synchronized (mPackages) {
23777                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23778                    Slog.e(TAG, "failed to find package " + targetPackageName);
23779                    return false;
23780                }
23781                ArrayList<String> overlayPaths = null;
23782                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23783                    final int N = overlayPackageNames.size();
23784                    overlayPaths = new ArrayList<>(N);
23785                    for (int i = 0; i < N; i++) {
23786                        final String packageName = overlayPackageNames.get(i);
23787                        final PackageParser.Package pkg = mPackages.get(packageName);
23788                        if (pkg == null) {
23789                            Slog.e(TAG, "failed to find package " + packageName);
23790                            return false;
23791                        }
23792                        overlayPaths.add(pkg.baseCodePath);
23793                    }
23794                }
23795
23796                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23797                ps.setOverlayPaths(overlayPaths, userId);
23798                return true;
23799            }
23800        }
23801
23802        @Override
23803        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23804                int flags, int userId, boolean resolveForStart) {
23805            return resolveIntentInternal(
23806                    intent, resolvedType, flags, userId, resolveForStart);
23807        }
23808
23809        @Override
23810        public ResolveInfo resolveService(Intent intent, String resolvedType,
23811                int flags, int userId, int callingUid) {
23812            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23813        }
23814
23815        @Override
23816        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23817            return PackageManagerService.this.resolveContentProviderInternal(
23818                    name, flags, userId);
23819        }
23820
23821        @Override
23822        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23823            synchronized (mPackages) {
23824                mIsolatedOwners.put(isolatedUid, ownerUid);
23825            }
23826        }
23827
23828        @Override
23829        public void removeIsolatedUid(int isolatedUid) {
23830            synchronized (mPackages) {
23831                mIsolatedOwners.delete(isolatedUid);
23832            }
23833        }
23834
23835        @Override
23836        public int getUidTargetSdkVersion(int uid) {
23837            synchronized (mPackages) {
23838                return getUidTargetSdkVersionLockedLPr(uid);
23839            }
23840        }
23841
23842        @Override
23843        public int getPackageTargetSdkVersion(String packageName) {
23844            synchronized (mPackages) {
23845                return getPackageTargetSdkVersionLockedLPr(packageName);
23846            }
23847        }
23848
23849        @Override
23850        public boolean canAccessInstantApps(int callingUid, int userId) {
23851            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23852        }
23853
23854        @Override
23855        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23856            synchronized (mPackages) {
23857                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23858            }
23859        }
23860
23861        @Override
23862        public void notifyPackageUse(String packageName, int reason) {
23863            synchronized (mPackages) {
23864                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23865            }
23866        }
23867    }
23868
23869    @Override
23870    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23871        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23872        synchronized (mPackages) {
23873            final long identity = Binder.clearCallingIdentity();
23874            try {
23875                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23876                        packageNames, userId);
23877            } finally {
23878                Binder.restoreCallingIdentity(identity);
23879            }
23880        }
23881    }
23882
23883    @Override
23884    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23885        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23886        synchronized (mPackages) {
23887            final long identity = Binder.clearCallingIdentity();
23888            try {
23889                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23890                        packageNames, userId);
23891            } finally {
23892                Binder.restoreCallingIdentity(identity);
23893            }
23894        }
23895    }
23896
23897    private static void enforceSystemOrPhoneCaller(String tag) {
23898        int callingUid = Binder.getCallingUid();
23899        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23900            throw new SecurityException(
23901                    "Cannot call " + tag + " from UID " + callingUid);
23902        }
23903    }
23904
23905    boolean isHistoricalPackageUsageAvailable() {
23906        return mPackageUsage.isHistoricalPackageUsageAvailable();
23907    }
23908
23909    /**
23910     * Return a <b>copy</b> of the collection of packages known to the package manager.
23911     * @return A copy of the values of mPackages.
23912     */
23913    Collection<PackageParser.Package> getPackages() {
23914        synchronized (mPackages) {
23915            return new ArrayList<>(mPackages.values());
23916        }
23917    }
23918
23919    /**
23920     * Logs process start information (including base APK hash) to the security log.
23921     * @hide
23922     */
23923    @Override
23924    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23925            String apkFile, int pid) {
23926        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23927            return;
23928        }
23929        if (!SecurityLog.isLoggingEnabled()) {
23930            return;
23931        }
23932        Bundle data = new Bundle();
23933        data.putLong("startTimestamp", System.currentTimeMillis());
23934        data.putString("processName", processName);
23935        data.putInt("uid", uid);
23936        data.putString("seinfo", seinfo);
23937        data.putString("apkFile", apkFile);
23938        data.putInt("pid", pid);
23939        Message msg = mProcessLoggingHandler.obtainMessage(
23940                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23941        msg.setData(data);
23942        mProcessLoggingHandler.sendMessage(msg);
23943    }
23944
23945    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23946        return mCompilerStats.getPackageStats(pkgName);
23947    }
23948
23949    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23950        return getOrCreateCompilerPackageStats(pkg.packageName);
23951    }
23952
23953    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23954        return mCompilerStats.getOrCreatePackageStats(pkgName);
23955    }
23956
23957    public void deleteCompilerPackageStats(String pkgName) {
23958        mCompilerStats.deletePackageStats(pkgName);
23959    }
23960
23961    @Override
23962    public int getInstallReason(String packageName, int userId) {
23963        final int callingUid = Binder.getCallingUid();
23964        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23965                true /* requireFullPermission */, false /* checkShell */,
23966                "get install reason");
23967        synchronized (mPackages) {
23968            final PackageSetting ps = mSettings.mPackages.get(packageName);
23969            if (filterAppAccessLPr(ps, callingUid, userId)) {
23970                return PackageManager.INSTALL_REASON_UNKNOWN;
23971            }
23972            if (ps != null) {
23973                return ps.getInstallReason(userId);
23974            }
23975        }
23976        return PackageManager.INSTALL_REASON_UNKNOWN;
23977    }
23978
23979    @Override
23980    public boolean canRequestPackageInstalls(String packageName, int userId) {
23981        return canRequestPackageInstallsInternal(packageName, 0, userId,
23982                true /* throwIfPermNotDeclared*/);
23983    }
23984
23985    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23986            boolean throwIfPermNotDeclared) {
23987        int callingUid = Binder.getCallingUid();
23988        int uid = getPackageUid(packageName, 0, userId);
23989        if (callingUid != uid && callingUid != Process.ROOT_UID
23990                && callingUid != Process.SYSTEM_UID) {
23991            throw new SecurityException(
23992                    "Caller uid " + callingUid + " does not own package " + packageName);
23993        }
23994        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23995        if (info == null) {
23996            return false;
23997        }
23998        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23999            return false;
24000        }
24001        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24002        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24003        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24004            if (throwIfPermNotDeclared) {
24005                throw new SecurityException("Need to declare " + appOpPermission
24006                        + " to call this api");
24007            } else {
24008                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24009                return false;
24010            }
24011        }
24012        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24013            return false;
24014        }
24015        if (mExternalSourcesPolicy != null) {
24016            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24017            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24018                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24019            }
24020        }
24021        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24022    }
24023
24024    @Override
24025    public ComponentName getInstantAppResolverSettingsComponent() {
24026        return mInstantAppResolverSettingsComponent;
24027    }
24028
24029    @Override
24030    public ComponentName getInstantAppInstallerComponent() {
24031        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24032            return null;
24033        }
24034        return mInstantAppInstallerActivity == null
24035                ? null : mInstantAppInstallerActivity.getComponentName();
24036    }
24037
24038    @Override
24039    public String getInstantAppAndroidId(String packageName, int userId) {
24040        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24041                "getInstantAppAndroidId");
24042        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24043                true /* requireFullPermission */, false /* checkShell */,
24044                "getInstantAppAndroidId");
24045        // Make sure the target is an Instant App.
24046        if (!isInstantApp(packageName, userId)) {
24047            return null;
24048        }
24049        synchronized (mPackages) {
24050            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24051        }
24052    }
24053
24054    boolean canHaveOatDir(String packageName) {
24055        synchronized (mPackages) {
24056            PackageParser.Package p = mPackages.get(packageName);
24057            if (p == null) {
24058                return false;
24059            }
24060            return p.canHaveOatDir();
24061        }
24062    }
24063
24064    private String getOatDir(PackageParser.Package pkg) {
24065        if (!pkg.canHaveOatDir()) {
24066            return null;
24067        }
24068        File codePath = new File(pkg.codePath);
24069        if (codePath.isDirectory()) {
24070            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24071        }
24072        return null;
24073    }
24074
24075    void deleteOatArtifactsOfPackage(String packageName) {
24076        final String[] instructionSets;
24077        final List<String> codePaths;
24078        final String oatDir;
24079        final PackageParser.Package pkg;
24080        synchronized (mPackages) {
24081            pkg = mPackages.get(packageName);
24082        }
24083        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24084        codePaths = pkg.getAllCodePaths();
24085        oatDir = getOatDir(pkg);
24086
24087        for (String codePath : codePaths) {
24088            for (String isa : instructionSets) {
24089                try {
24090                    mInstaller.deleteOdex(codePath, isa, oatDir);
24091                } catch (InstallerException e) {
24092                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24093                }
24094            }
24095        }
24096    }
24097
24098    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24099        Set<String> unusedPackages = new HashSet<>();
24100        long currentTimeInMillis = System.currentTimeMillis();
24101        synchronized (mPackages) {
24102            for (PackageParser.Package pkg : mPackages.values()) {
24103                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24104                if (ps == null) {
24105                    continue;
24106                }
24107                PackageDexUsage.PackageUseInfo packageUseInfo =
24108                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24109                if (PackageManagerServiceUtils
24110                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24111                                downgradeTimeThresholdMillis, packageUseInfo,
24112                                pkg.getLatestPackageUseTimeInMills(),
24113                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24114                    unusedPackages.add(pkg.packageName);
24115                }
24116            }
24117        }
24118        return unusedPackages;
24119    }
24120
24121    @Override
24122    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24123            int userId) {
24124        final int callingUid = Binder.getCallingUid();
24125        final int callingAppId = UserHandle.getAppId(callingUid);
24126
24127        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24128                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24129
24130        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24131                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24132            throw new SecurityException("Caller must have the "
24133                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24134        }
24135
24136        synchronized(mPackages) {
24137            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24138            scheduleWritePackageRestrictionsLocked(userId);
24139        }
24140    }
24141
24142    @Nullable
24143    @Override
24144    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24145        final int callingUid = Binder.getCallingUid();
24146        final int callingAppId = UserHandle.getAppId(callingUid);
24147
24148        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24149                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24150
24151        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24152                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24153            throw new SecurityException("Caller must have the "
24154                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24155        }
24156
24157        synchronized(mPackages) {
24158            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24159        }
24160    }
24161}
24162
24163interface PackageSender {
24164    /**
24165     * @param userIds User IDs where the action occurred on a full application
24166     * @param instantUserIds User IDs where the action occurred on an instant application
24167     */
24168    void sendPackageBroadcast(final String action, final String pkg,
24169        final Bundle extras, final int flags, final String targetPkg,
24170        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24171    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24172        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24173    void notifyPackageAdded(String packageName);
24174    void notifyPackageRemoved(String packageName);
24175}
24176