PackageManagerService.java revision 43c97a0e9057e2f7ff34b90cb50692cf56937da2
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        PackageParser.Package p = ps.pkg;
3844        if (p == null) {
3845            return null;
3846        }
3847        final int callingUid = Binder.getCallingUid();
3848        // Filter out ephemeral app metadata:
3849        //   * The system/shell/root can see metadata for any app
3850        //   * An installed app can see metadata for 1) other installed apps
3851        //     and 2) ephemeral apps that have explicitly interacted with it
3852        //   * Ephemeral apps can only see their own data and exposed installed apps
3853        //   * Holding a signature permission allows seeing instant apps
3854        if (filterAppAccessLPr(ps, callingUid, userId)) {
3855            return null;
3856        }
3857
3858        final PermissionsState permissionsState = ps.getPermissionsState();
3859
3860        // Compute GIDs only if requested
3861        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3862                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3863        // Compute granted permissions only if package has requested permissions
3864        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3865                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3866        final PackageUserState state = ps.readUserState(userId);
3867
3868        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3869                && ps.isSystem()) {
3870            flags |= MATCH_ANY_USER;
3871        }
3872
3873        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3874                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3875
3876        if (packageInfo == null) {
3877            return null;
3878        }
3879
3880        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3881                resolveExternalPackageNameLPr(p);
3882
3883        return packageInfo;
3884    }
3885
3886    @Override
3887    public void checkPackageStartable(String packageName, int userId) {
3888        final int callingUid = Binder.getCallingUid();
3889        if (getInstantAppPackageName(callingUid) != null) {
3890            throw new SecurityException("Instant applications don't have access to this method");
3891        }
3892        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3893        synchronized (mPackages) {
3894            final PackageSetting ps = mSettings.mPackages.get(packageName);
3895            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3896                throw new SecurityException("Package " + packageName + " was not found!");
3897            }
3898
3899            if (!ps.getInstalled(userId)) {
3900                throw new SecurityException(
3901                        "Package " + packageName + " was not installed for user " + userId + "!");
3902            }
3903
3904            if (mSafeMode && !ps.isSystem()) {
3905                throw new SecurityException("Package " + packageName + " not a system app!");
3906            }
3907
3908            if (mFrozenPackages.contains(packageName)) {
3909                throw new SecurityException("Package " + packageName + " is currently frozen!");
3910            }
3911
3912            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3913                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3914            }
3915        }
3916    }
3917
3918    @Override
3919    public boolean isPackageAvailable(String packageName, int userId) {
3920        if (!sUserManager.exists(userId)) return false;
3921        final int callingUid = Binder.getCallingUid();
3922        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3923                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3924        synchronized (mPackages) {
3925            PackageParser.Package p = mPackages.get(packageName);
3926            if (p != null) {
3927                final PackageSetting ps = (PackageSetting) p.mExtras;
3928                if (filterAppAccessLPr(ps, callingUid, userId)) {
3929                    return false;
3930                }
3931                if (ps != null) {
3932                    final PackageUserState state = ps.readUserState(userId);
3933                    if (state != null) {
3934                        return PackageParser.isAvailable(state);
3935                    }
3936                }
3937            }
3938        }
3939        return false;
3940    }
3941
3942    @Override
3943    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3944        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3945                flags, Binder.getCallingUid(), userId);
3946    }
3947
3948    @Override
3949    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3950            int flags, int userId) {
3951        return getPackageInfoInternal(versionedPackage.getPackageName(),
3952                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3953    }
3954
3955    /**
3956     * Important: The provided filterCallingUid is used exclusively to filter out packages
3957     * that can be seen based on user state. It's typically the original caller uid prior
3958     * to clearing. Because it can only be provided by trusted code, it's value can be
3959     * trusted and will be used as-is; unlike userId which will be validated by this method.
3960     */
3961    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3962            int flags, int filterCallingUid, int userId) {
3963        if (!sUserManager.exists(userId)) return null;
3964        flags = updateFlagsForPackage(flags, userId, packageName);
3965        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3966                false /* requireFullPermission */, false /* checkShell */, "get package info");
3967
3968        // reader
3969        synchronized (mPackages) {
3970            // Normalize package name to handle renamed packages and static libs
3971            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3972
3973            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3974            if (matchFactoryOnly) {
3975                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3976                if (ps != null) {
3977                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3978                        return null;
3979                    }
3980                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3981                        return null;
3982                    }
3983                    return generatePackageInfo(ps, flags, userId);
3984                }
3985            }
3986
3987            PackageParser.Package p = mPackages.get(packageName);
3988            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3989                return null;
3990            }
3991            if (DEBUG_PACKAGE_INFO)
3992                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3993            if (p != null) {
3994                final PackageSetting ps = (PackageSetting) p.mExtras;
3995                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3996                    return null;
3997                }
3998                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3999                    return null;
4000                }
4001                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4002            }
4003            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4004                final PackageSetting ps = mSettings.mPackages.get(packageName);
4005                if (ps == null) return null;
4006                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4007                    return null;
4008                }
4009                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4010                    return null;
4011                }
4012                return generatePackageInfo(ps, flags, userId);
4013            }
4014        }
4015        return null;
4016    }
4017
4018    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4019        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4020            return true;
4021        }
4022        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4023            return true;
4024        }
4025        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4026            return true;
4027        }
4028        return false;
4029    }
4030
4031    private boolean isComponentVisibleToInstantApp(
4032            @Nullable ComponentName component, @ComponentType int type) {
4033        if (type == TYPE_ACTIVITY) {
4034            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4035            return activity != null
4036                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4037                    : false;
4038        } else if (type == TYPE_RECEIVER) {
4039            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4040            return activity != null
4041                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4042                    : false;
4043        } else if (type == TYPE_SERVICE) {
4044            final PackageParser.Service service = mServices.mServices.get(component);
4045            return service != null
4046                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4047                    : false;
4048        } else if (type == TYPE_PROVIDER) {
4049            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4050            return provider != null
4051                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4052                    : false;
4053        } else if (type == TYPE_UNKNOWN) {
4054            return isComponentVisibleToInstantApp(component);
4055        }
4056        return false;
4057    }
4058
4059    /**
4060     * Returns whether or not access to the application should be filtered.
4061     * <p>
4062     * Access may be limited based upon whether the calling or target applications
4063     * are instant applications.
4064     *
4065     * @see #canAccessInstantApps(int)
4066     */
4067    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4068            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4069        // if we're in an isolated process, get the real calling UID
4070        if (Process.isIsolated(callingUid)) {
4071            callingUid = mIsolatedOwners.get(callingUid);
4072        }
4073        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4074        final boolean callerIsInstantApp = instantAppPkgName != null;
4075        if (ps == null) {
4076            if (callerIsInstantApp) {
4077                // pretend the application exists, but, needs to be filtered
4078                return true;
4079            }
4080            return false;
4081        }
4082        // if the target and caller are the same application, don't filter
4083        if (isCallerSameApp(ps.name, callingUid)) {
4084            return false;
4085        }
4086        if (callerIsInstantApp) {
4087            // request for a specific component; if it hasn't been explicitly exposed, filter
4088            if (component != null) {
4089                return !isComponentVisibleToInstantApp(component, componentType);
4090            }
4091            // request for application; if no components have been explicitly exposed, filter
4092            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4093        }
4094        if (ps.getInstantApp(userId)) {
4095            // caller can see all components of all instant applications, don't filter
4096            if (canViewInstantApps(callingUid, userId)) {
4097                return false;
4098            }
4099            // request for a specific instant application component, filter
4100            if (component != null) {
4101                return true;
4102            }
4103            // request for an instant application; if the caller hasn't been granted access, filter
4104            return !mInstantAppRegistry.isInstantAccessGranted(
4105                    userId, UserHandle.getAppId(callingUid), ps.appId);
4106        }
4107        return false;
4108    }
4109
4110    /**
4111     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4112     */
4113    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4114        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4115    }
4116
4117    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4118            int flags) {
4119        // Callers can access only the libs they depend on, otherwise they need to explicitly
4120        // ask for the shared libraries given the caller is allowed to access all static libs.
4121        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4122            // System/shell/root get to see all static libs
4123            final int appId = UserHandle.getAppId(uid);
4124            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4125                    || appId == Process.ROOT_UID) {
4126                return false;
4127            }
4128        }
4129
4130        // No package means no static lib as it is always on internal storage
4131        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4132            return false;
4133        }
4134
4135        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4136                ps.pkg.staticSharedLibVersion);
4137        if (libEntry == null) {
4138            return false;
4139        }
4140
4141        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4142        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4143        if (uidPackageNames == null) {
4144            return true;
4145        }
4146
4147        for (String uidPackageName : uidPackageNames) {
4148            if (ps.name.equals(uidPackageName)) {
4149                return false;
4150            }
4151            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4152            if (uidPs != null) {
4153                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4154                        libEntry.info.getName());
4155                if (index < 0) {
4156                    continue;
4157                }
4158                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4159                    return false;
4160                }
4161            }
4162        }
4163        return true;
4164    }
4165
4166    @Override
4167    public String[] currentToCanonicalPackageNames(String[] names) {
4168        final int callingUid = Binder.getCallingUid();
4169        if (getInstantAppPackageName(callingUid) != null) {
4170            return names;
4171        }
4172        final String[] out = new String[names.length];
4173        // reader
4174        synchronized (mPackages) {
4175            final int callingUserId = UserHandle.getUserId(callingUid);
4176            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4177            for (int i=names.length-1; i>=0; i--) {
4178                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4179                boolean translateName = false;
4180                if (ps != null && ps.realName != null) {
4181                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4182                    translateName = !targetIsInstantApp
4183                            || canViewInstantApps
4184                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4185                                    UserHandle.getAppId(callingUid), ps.appId);
4186                }
4187                out[i] = translateName ? ps.realName : names[i];
4188            }
4189        }
4190        return out;
4191    }
4192
4193    @Override
4194    public String[] canonicalToCurrentPackageNames(String[] names) {
4195        final int callingUid = Binder.getCallingUid();
4196        if (getInstantAppPackageName(callingUid) != null) {
4197            return names;
4198        }
4199        final String[] out = new String[names.length];
4200        // reader
4201        synchronized (mPackages) {
4202            final int callingUserId = UserHandle.getUserId(callingUid);
4203            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4204            for (int i=names.length-1; i>=0; i--) {
4205                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4206                boolean translateName = false;
4207                if (cur != null) {
4208                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4209                    final boolean targetIsInstantApp =
4210                            ps != null && ps.getInstantApp(callingUserId);
4211                    translateName = !targetIsInstantApp
4212                            || canViewInstantApps
4213                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4214                                    UserHandle.getAppId(callingUid), ps.appId);
4215                }
4216                out[i] = translateName ? cur : names[i];
4217            }
4218        }
4219        return out;
4220    }
4221
4222    @Override
4223    public int getPackageUid(String packageName, int flags, int userId) {
4224        if (!sUserManager.exists(userId)) return -1;
4225        final int callingUid = Binder.getCallingUid();
4226        flags = updateFlagsForPackage(flags, userId, packageName);
4227        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4228                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4229
4230        // reader
4231        synchronized (mPackages) {
4232            final PackageParser.Package p = mPackages.get(packageName);
4233            if (p != null && p.isMatch(flags)) {
4234                PackageSetting ps = (PackageSetting) p.mExtras;
4235                if (filterAppAccessLPr(ps, callingUid, userId)) {
4236                    return -1;
4237                }
4238                return UserHandle.getUid(userId, p.applicationInfo.uid);
4239            }
4240            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4241                final PackageSetting ps = mSettings.mPackages.get(packageName);
4242                if (ps != null && ps.isMatch(flags)
4243                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4244                    return UserHandle.getUid(userId, ps.appId);
4245                }
4246            }
4247        }
4248
4249        return -1;
4250    }
4251
4252    @Override
4253    public int[] getPackageGids(String packageName, int flags, int userId) {
4254        if (!sUserManager.exists(userId)) return null;
4255        final int callingUid = Binder.getCallingUid();
4256        flags = updateFlagsForPackage(flags, userId, packageName);
4257        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4258                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4259
4260        // reader
4261        synchronized (mPackages) {
4262            final PackageParser.Package p = mPackages.get(packageName);
4263            if (p != null && p.isMatch(flags)) {
4264                PackageSetting ps = (PackageSetting) p.mExtras;
4265                if (filterAppAccessLPr(ps, callingUid, userId)) {
4266                    return null;
4267                }
4268                // TODO: Shouldn't this be checking for package installed state for userId and
4269                // return null?
4270                return ps.getPermissionsState().computeGids(userId);
4271            }
4272            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4273                final PackageSetting ps = mSettings.mPackages.get(packageName);
4274                if (ps != null && ps.isMatch(flags)
4275                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4276                    return ps.getPermissionsState().computeGids(userId);
4277                }
4278            }
4279        }
4280
4281        return null;
4282    }
4283
4284    @Override
4285    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4286        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4287    }
4288
4289    @Override
4290    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4291            int flags) {
4292        final List<PermissionInfo> permissionList =
4293                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4294        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4295    }
4296
4297    @Override
4298    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4299        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4300    }
4301
4302    @Override
4303    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4304        final List<PermissionGroupInfo> permissionList =
4305                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4306        return (permissionList == null)
4307                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4308    }
4309
4310    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4311            int filterCallingUid, int userId) {
4312        if (!sUserManager.exists(userId)) return null;
4313        PackageSetting ps = mSettings.mPackages.get(packageName);
4314        if (ps != null) {
4315            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4316                return null;
4317            }
4318            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4319                return null;
4320            }
4321            if (ps.pkg == null) {
4322                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4323                if (pInfo != null) {
4324                    return pInfo.applicationInfo;
4325                }
4326                return null;
4327            }
4328            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4329                    ps.readUserState(userId), userId);
4330            if (ai != null) {
4331                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4332            }
4333            return ai;
4334        }
4335        return null;
4336    }
4337
4338    @Override
4339    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4340        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4341    }
4342
4343    /**
4344     * Important: The provided filterCallingUid is used exclusively to filter out applications
4345     * that can be seen based on user state. It's typically the original caller uid prior
4346     * to clearing. Because it can only be provided by trusted code, it's value can be
4347     * trusted and will be used as-is; unlike userId which will be validated by this method.
4348     */
4349    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4350            int filterCallingUid, int userId) {
4351        if (!sUserManager.exists(userId)) return null;
4352        flags = updateFlagsForApplication(flags, userId, packageName);
4353        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4354                false /* requireFullPermission */, false /* checkShell */, "get application info");
4355
4356        // writer
4357        synchronized (mPackages) {
4358            // Normalize package name to handle renamed packages and static libs
4359            packageName = resolveInternalPackageNameLPr(packageName,
4360                    PackageManager.VERSION_CODE_HIGHEST);
4361
4362            PackageParser.Package p = mPackages.get(packageName);
4363            if (DEBUG_PACKAGE_INFO) Log.v(
4364                    TAG, "getApplicationInfo " + packageName
4365                    + ": " + p);
4366            if (p != null) {
4367                PackageSetting ps = mSettings.mPackages.get(packageName);
4368                if (ps == null) return null;
4369                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4370                    return null;
4371                }
4372                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4373                    return null;
4374                }
4375                // Note: isEnabledLP() does not apply here - always return info
4376                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4377                        p, flags, ps.readUserState(userId), userId);
4378                if (ai != null) {
4379                    ai.packageName = resolveExternalPackageNameLPr(p);
4380                }
4381                return ai;
4382            }
4383            if ("android".equals(packageName)||"system".equals(packageName)) {
4384                return mAndroidApplication;
4385            }
4386            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4387                // Already generates the external package name
4388                return generateApplicationInfoFromSettingsLPw(packageName,
4389                        flags, filterCallingUid, userId);
4390            }
4391        }
4392        return null;
4393    }
4394
4395    private String normalizePackageNameLPr(String packageName) {
4396        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4397        return normalizedPackageName != null ? normalizedPackageName : packageName;
4398    }
4399
4400    @Override
4401    public void deletePreloadsFileCache() {
4402        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4403            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4404        }
4405        File dir = Environment.getDataPreloadsFileCacheDirectory();
4406        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4407        FileUtils.deleteContents(dir);
4408    }
4409
4410    @Override
4411    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4412            final int storageFlags, final IPackageDataObserver observer) {
4413        mContext.enforceCallingOrSelfPermission(
4414                android.Manifest.permission.CLEAR_APP_CACHE, null);
4415        mHandler.post(() -> {
4416            boolean success = false;
4417            try {
4418                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4419                success = true;
4420            } catch (IOException e) {
4421                Slog.w(TAG, e);
4422            }
4423            if (observer != null) {
4424                try {
4425                    observer.onRemoveCompleted(null, success);
4426                } catch (RemoteException e) {
4427                    Slog.w(TAG, e);
4428                }
4429            }
4430        });
4431    }
4432
4433    @Override
4434    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4435            final int storageFlags, final IntentSender pi) {
4436        mContext.enforceCallingOrSelfPermission(
4437                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4438        mHandler.post(() -> {
4439            boolean success = false;
4440            try {
4441                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4442                success = true;
4443            } catch (IOException e) {
4444                Slog.w(TAG, e);
4445            }
4446            if (pi != null) {
4447                try {
4448                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4449                } catch (SendIntentException e) {
4450                    Slog.w(TAG, e);
4451                }
4452            }
4453        });
4454    }
4455
4456    /**
4457     * Blocking call to clear various types of cached data across the system
4458     * until the requested bytes are available.
4459     */
4460    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4461        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4462        final File file = storage.findPathForUuid(volumeUuid);
4463        if (file.getUsableSpace() >= bytes) return;
4464
4465        if (ENABLE_FREE_CACHE_V2) {
4466            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4467                    volumeUuid);
4468            final boolean aggressive = (storageFlags
4469                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4470            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4471
4472            // 1. Pre-flight to determine if we have any chance to succeed
4473            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4474            if (internalVolume && (aggressive || SystemProperties
4475                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4476                deletePreloadsFileCache();
4477                if (file.getUsableSpace() >= bytes) return;
4478            }
4479
4480            // 3. Consider parsed APK data (aggressive only)
4481            if (internalVolume && aggressive) {
4482                FileUtils.deleteContents(mCacheDir);
4483                if (file.getUsableSpace() >= bytes) return;
4484            }
4485
4486            // 4. Consider cached app data (above quotas)
4487            try {
4488                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4489                        Installer.FLAG_FREE_CACHE_V2);
4490            } catch (InstallerException ignored) {
4491            }
4492            if (file.getUsableSpace() >= bytes) return;
4493
4494            // 5. Consider shared libraries with refcount=0 and age>min cache period
4495            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4496                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4497                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4498                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4499                return;
4500            }
4501
4502            // 6. Consider dexopt output (aggressive only)
4503            // TODO: Implement
4504
4505            // 7. Consider installed instant apps unused longer than min cache period
4506            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4507                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4508                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4509                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4510                return;
4511            }
4512
4513            // 8. Consider cached app data (below quotas)
4514            try {
4515                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4516                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4517            } catch (InstallerException ignored) {
4518            }
4519            if (file.getUsableSpace() >= bytes) return;
4520
4521            // 9. Consider DropBox entries
4522            // TODO: Implement
4523
4524            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4525            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4526                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4527                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4528                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4529                return;
4530            }
4531        } else {
4532            try {
4533                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4534            } catch (InstallerException ignored) {
4535            }
4536            if (file.getUsableSpace() >= bytes) return;
4537        }
4538
4539        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4540    }
4541
4542    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4543            throws IOException {
4544        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4545        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4546
4547        List<VersionedPackage> packagesToDelete = null;
4548        final long now = System.currentTimeMillis();
4549
4550        synchronized (mPackages) {
4551            final int[] allUsers = sUserManager.getUserIds();
4552            final int libCount = mSharedLibraries.size();
4553            for (int i = 0; i < libCount; i++) {
4554                final LongSparseArray<SharedLibraryEntry> versionedLib
4555                        = mSharedLibraries.valueAt(i);
4556                if (versionedLib == null) {
4557                    continue;
4558                }
4559                final int versionCount = versionedLib.size();
4560                for (int j = 0; j < versionCount; j++) {
4561                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4562                    // Skip packages that are not static shared libs.
4563                    if (!libInfo.isStatic()) {
4564                        break;
4565                    }
4566                    // Important: We skip static shared libs used for some user since
4567                    // in such a case we need to keep the APK on the device. The check for
4568                    // a lib being used for any user is performed by the uninstall call.
4569                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4570                    // Resolve the package name - we use synthetic package names internally
4571                    final String internalPackageName = resolveInternalPackageNameLPr(
4572                            declaringPackage.getPackageName(),
4573                            declaringPackage.getLongVersionCode());
4574                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4575                    // Skip unused static shared libs cached less than the min period
4576                    // to prevent pruning a lib needed by a subsequently installed package.
4577                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4578                        continue;
4579                    }
4580                    if (packagesToDelete == null) {
4581                        packagesToDelete = new ArrayList<>();
4582                    }
4583                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4584                            declaringPackage.getLongVersionCode()));
4585                }
4586            }
4587        }
4588
4589        if (packagesToDelete != null) {
4590            final int packageCount = packagesToDelete.size();
4591            for (int i = 0; i < packageCount; i++) {
4592                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4593                // Delete the package synchronously (will fail of the lib used for any user).
4594                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4595                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4596                                == PackageManager.DELETE_SUCCEEDED) {
4597                    if (volume.getUsableSpace() >= neededSpace) {
4598                        return true;
4599                    }
4600                }
4601            }
4602        }
4603
4604        return false;
4605    }
4606
4607    /**
4608     * Update given flags based on encryption status of current user.
4609     */
4610    private int updateFlags(int flags, int userId) {
4611        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4612                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4613            // Caller expressed an explicit opinion about what encryption
4614            // aware/unaware components they want to see, so fall through and
4615            // give them what they want
4616        } else {
4617            // Caller expressed no opinion, so match based on user state
4618            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4619                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4620            } else {
4621                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4622            }
4623        }
4624        return flags;
4625    }
4626
4627    private UserManagerInternal getUserManagerInternal() {
4628        if (mUserManagerInternal == null) {
4629            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4630        }
4631        return mUserManagerInternal;
4632    }
4633
4634    private ActivityManagerInternal getActivityManagerInternal() {
4635        if (mActivityManagerInternal == null) {
4636            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4637        }
4638        return mActivityManagerInternal;
4639    }
4640
4641
4642    private DeviceIdleController.LocalService getDeviceIdleController() {
4643        if (mDeviceIdleController == null) {
4644            mDeviceIdleController =
4645                    LocalServices.getService(DeviceIdleController.LocalService.class);
4646        }
4647        return mDeviceIdleController;
4648    }
4649
4650    /**
4651     * Update given flags when being used to request {@link PackageInfo}.
4652     */
4653    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4654        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4655        boolean triaged = true;
4656        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4657                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4658            // Caller is asking for component details, so they'd better be
4659            // asking for specific encryption matching behavior, or be triaged
4660            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4661                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4662                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4663                triaged = false;
4664            }
4665        }
4666        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4667                | PackageManager.MATCH_SYSTEM_ONLY
4668                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4669            triaged = false;
4670        }
4671        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4672            mPermissionManager.enforceCrossUserPermission(
4673                    Binder.getCallingUid(), userId, false, false,
4674                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4675                    + Debug.getCallers(5));
4676        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4677                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4678            // If the caller wants all packages and has a restricted profile associated with it,
4679            // then match all users. This is to make sure that launchers that need to access work
4680            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4681            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4682            flags |= PackageManager.MATCH_ANY_USER;
4683        }
4684        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4685            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4686                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4687        }
4688        return updateFlags(flags, userId);
4689    }
4690
4691    /**
4692     * Update given flags when being used to request {@link ApplicationInfo}.
4693     */
4694    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4695        return updateFlagsForPackage(flags, userId, cookie);
4696    }
4697
4698    /**
4699     * Update given flags when being used to request {@link ComponentInfo}.
4700     */
4701    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4702        if (cookie instanceof Intent) {
4703            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4704                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4705            }
4706        }
4707
4708        boolean triaged = true;
4709        // Caller is asking for component details, so they'd better be
4710        // asking for specific encryption matching behavior, or be triaged
4711        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4712                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4713                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4714            triaged = false;
4715        }
4716        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4717            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4718                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4719        }
4720
4721        return updateFlags(flags, userId);
4722    }
4723
4724    /**
4725     * Update given intent when being used to request {@link ResolveInfo}.
4726     */
4727    private Intent updateIntentForResolve(Intent intent) {
4728        if (intent.getSelector() != null) {
4729            intent = intent.getSelector();
4730        }
4731        if (DEBUG_PREFERRED) {
4732            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4733        }
4734        return intent;
4735    }
4736
4737    /**
4738     * Update given flags when being used to request {@link ResolveInfo}.
4739     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4740     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4741     * flag set. However, this flag is only honoured in three circumstances:
4742     * <ul>
4743     * <li>when called from a system process</li>
4744     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4745     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4746     * action and a {@code android.intent.category.BROWSABLE} category</li>
4747     * </ul>
4748     */
4749    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4750        return updateFlagsForResolve(flags, userId, intent, callingUid,
4751                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4752    }
4753    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4754            boolean wantInstantApps) {
4755        return updateFlagsForResolve(flags, userId, intent, callingUid,
4756                wantInstantApps, false /*onlyExposedExplicitly*/);
4757    }
4758    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4759            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4760        // Safe mode means we shouldn't match any third-party components
4761        if (mSafeMode) {
4762            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4763        }
4764        if (getInstantAppPackageName(callingUid) != null) {
4765            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4766            if (onlyExposedExplicitly) {
4767                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4768            }
4769            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4770            flags |= PackageManager.MATCH_INSTANT;
4771        } else {
4772            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4773            final boolean allowMatchInstant = wantInstantApps
4774                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4775            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4776                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4777            if (!allowMatchInstant) {
4778                flags &= ~PackageManager.MATCH_INSTANT;
4779            }
4780        }
4781        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4782    }
4783
4784    @Override
4785    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4786        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4787    }
4788
4789    /**
4790     * Important: The provided filterCallingUid is used exclusively to filter out activities
4791     * that can be seen based on user state. It's typically the original caller uid prior
4792     * to clearing. Because it can only be provided by trusted code, it's value can be
4793     * trusted and will be used as-is; unlike userId which will be validated by this method.
4794     */
4795    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4796            int filterCallingUid, int userId) {
4797        if (!sUserManager.exists(userId)) return null;
4798        flags = updateFlagsForComponent(flags, userId, component);
4799
4800        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4801            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4802                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4803        }
4804
4805        synchronized (mPackages) {
4806            PackageParser.Activity a = mActivities.mActivities.get(component);
4807
4808            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4809            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4810                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4811                if (ps == null) return null;
4812                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4813                    return null;
4814                }
4815                return PackageParser.generateActivityInfo(
4816                        a, flags, ps.readUserState(userId), userId);
4817            }
4818            if (mResolveComponentName.equals(component)) {
4819                return PackageParser.generateActivityInfo(
4820                        mResolveActivity, flags, new PackageUserState(), userId);
4821            }
4822        }
4823        return null;
4824    }
4825
4826    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4827        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4828            return false;
4829        }
4830        final long token = Binder.clearCallingIdentity();
4831        try {
4832            final int callingUserId = UserHandle.getUserId(callingUid);
4833            if (ActivityManager.getCurrentUser() != callingUserId) {
4834                return false;
4835            }
4836            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4837        } finally {
4838            Binder.restoreCallingIdentity(token);
4839        }
4840    }
4841
4842    @Override
4843    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4844            String resolvedType) {
4845        synchronized (mPackages) {
4846            if (component.equals(mResolveComponentName)) {
4847                // The resolver supports EVERYTHING!
4848                return true;
4849            }
4850            final int callingUid = Binder.getCallingUid();
4851            final int callingUserId = UserHandle.getUserId(callingUid);
4852            PackageParser.Activity a = mActivities.mActivities.get(component);
4853            if (a == null) {
4854                return false;
4855            }
4856            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4857            if (ps == null) {
4858                return false;
4859            }
4860            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4861                return false;
4862            }
4863            for (int i=0; i<a.intents.size(); i++) {
4864                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4865                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4866                    return true;
4867                }
4868            }
4869            return false;
4870        }
4871    }
4872
4873    @Override
4874    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4875        if (!sUserManager.exists(userId)) return null;
4876        final int callingUid = Binder.getCallingUid();
4877        flags = updateFlagsForComponent(flags, userId, component);
4878        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4879                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4880        synchronized (mPackages) {
4881            PackageParser.Activity a = mReceivers.mActivities.get(component);
4882            if (DEBUG_PACKAGE_INFO) Log.v(
4883                TAG, "getReceiverInfo " + component + ": " + a);
4884            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4885                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4886                if (ps == null) return null;
4887                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4888                    return null;
4889                }
4890                return PackageParser.generateActivityInfo(
4891                        a, flags, ps.readUserState(userId), userId);
4892            }
4893        }
4894        return null;
4895    }
4896
4897    @Override
4898    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4899            int flags, int userId) {
4900        if (!sUserManager.exists(userId)) return null;
4901        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4902        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4903            return null;
4904        }
4905
4906        flags = updateFlagsForPackage(flags, userId, null);
4907
4908        final boolean canSeeStaticLibraries =
4909                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4910                        == PERMISSION_GRANTED
4911                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4912                        == PERMISSION_GRANTED
4913                || canRequestPackageInstallsInternal(packageName,
4914                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4915                        false  /* throwIfPermNotDeclared*/)
4916                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4917                        == PERMISSION_GRANTED;
4918
4919        synchronized (mPackages) {
4920            List<SharedLibraryInfo> result = null;
4921
4922            final int libCount = mSharedLibraries.size();
4923            for (int i = 0; i < libCount; i++) {
4924                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4925                if (versionedLib == null) {
4926                    continue;
4927                }
4928
4929                final int versionCount = versionedLib.size();
4930                for (int j = 0; j < versionCount; j++) {
4931                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4932                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4933                        break;
4934                    }
4935                    final long identity = Binder.clearCallingIdentity();
4936                    try {
4937                        PackageInfo packageInfo = getPackageInfoVersioned(
4938                                libInfo.getDeclaringPackage(), flags
4939                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4940                        if (packageInfo == null) {
4941                            continue;
4942                        }
4943                    } finally {
4944                        Binder.restoreCallingIdentity(identity);
4945                    }
4946
4947                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4948                            libInfo.getLongVersion(), libInfo.getType(),
4949                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4950                            flags, userId));
4951
4952                    if (result == null) {
4953                        result = new ArrayList<>();
4954                    }
4955                    result.add(resLibInfo);
4956                }
4957            }
4958
4959            return result != null ? new ParceledListSlice<>(result) : null;
4960        }
4961    }
4962
4963    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4964            SharedLibraryInfo libInfo, int flags, int userId) {
4965        List<VersionedPackage> versionedPackages = null;
4966        final int packageCount = mSettings.mPackages.size();
4967        for (int i = 0; i < packageCount; i++) {
4968            PackageSetting ps = mSettings.mPackages.valueAt(i);
4969
4970            if (ps == null) {
4971                continue;
4972            }
4973
4974            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4975                continue;
4976            }
4977
4978            final String libName = libInfo.getName();
4979            if (libInfo.isStatic()) {
4980                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4981                if (libIdx < 0) {
4982                    continue;
4983                }
4984                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4985                    continue;
4986                }
4987                if (versionedPackages == null) {
4988                    versionedPackages = new ArrayList<>();
4989                }
4990                // If the dependent is a static shared lib, use the public package name
4991                String dependentPackageName = ps.name;
4992                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4993                    dependentPackageName = ps.pkg.manifestPackageName;
4994                }
4995                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4996            } else if (ps.pkg != null) {
4997                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4998                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4999                    if (versionedPackages == null) {
5000                        versionedPackages = new ArrayList<>();
5001                    }
5002                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5003                }
5004            }
5005        }
5006
5007        return versionedPackages;
5008    }
5009
5010    @Override
5011    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5012        if (!sUserManager.exists(userId)) return null;
5013        final int callingUid = Binder.getCallingUid();
5014        flags = updateFlagsForComponent(flags, userId, component);
5015        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5016                false /* requireFullPermission */, false /* checkShell */, "get service info");
5017        synchronized (mPackages) {
5018            PackageParser.Service s = mServices.mServices.get(component);
5019            if (DEBUG_PACKAGE_INFO) Log.v(
5020                TAG, "getServiceInfo " + component + ": " + s);
5021            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5022                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5023                if (ps == null) return null;
5024                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5025                    return null;
5026                }
5027                return PackageParser.generateServiceInfo(
5028                        s, flags, ps.readUserState(userId), userId);
5029            }
5030        }
5031        return null;
5032    }
5033
5034    @Override
5035    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5036        if (!sUserManager.exists(userId)) return null;
5037        final int callingUid = Binder.getCallingUid();
5038        flags = updateFlagsForComponent(flags, userId, component);
5039        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5040                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5041        synchronized (mPackages) {
5042            PackageParser.Provider p = mProviders.mProviders.get(component);
5043            if (DEBUG_PACKAGE_INFO) Log.v(
5044                TAG, "getProviderInfo " + component + ": " + p);
5045            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5046                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5047                if (ps == null) return null;
5048                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5049                    return null;
5050                }
5051                return PackageParser.generateProviderInfo(
5052                        p, flags, ps.readUserState(userId), userId);
5053            }
5054        }
5055        return null;
5056    }
5057
5058    @Override
5059    public String[] getSystemSharedLibraryNames() {
5060        // allow instant applications
5061        synchronized (mPackages) {
5062            Set<String> libs = null;
5063            final int libCount = mSharedLibraries.size();
5064            for (int i = 0; i < libCount; i++) {
5065                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5066                if (versionedLib == null) {
5067                    continue;
5068                }
5069                final int versionCount = versionedLib.size();
5070                for (int j = 0; j < versionCount; j++) {
5071                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5072                    if (!libEntry.info.isStatic()) {
5073                        if (libs == null) {
5074                            libs = new ArraySet<>();
5075                        }
5076                        libs.add(libEntry.info.getName());
5077                        break;
5078                    }
5079                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5080                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5081                            UserHandle.getUserId(Binder.getCallingUid()),
5082                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5083                        if (libs == null) {
5084                            libs = new ArraySet<>();
5085                        }
5086                        libs.add(libEntry.info.getName());
5087                        break;
5088                    }
5089                }
5090            }
5091
5092            if (libs != null) {
5093                String[] libsArray = new String[libs.size()];
5094                libs.toArray(libsArray);
5095                return libsArray;
5096            }
5097
5098            return null;
5099        }
5100    }
5101
5102    @Override
5103    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5104        // allow instant applications
5105        synchronized (mPackages) {
5106            return mServicesSystemSharedLibraryPackageName;
5107        }
5108    }
5109
5110    @Override
5111    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5112        // allow instant applications
5113        synchronized (mPackages) {
5114            return mSharedSystemSharedLibraryPackageName;
5115        }
5116    }
5117
5118    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5119        for (int i = userList.length - 1; i >= 0; --i) {
5120            final int userId = userList[i];
5121            // don't add instant app to the list of updates
5122            if (pkgSetting.getInstantApp(userId)) {
5123                continue;
5124            }
5125            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5126            if (changedPackages == null) {
5127                changedPackages = new SparseArray<>();
5128                mChangedPackages.put(userId, changedPackages);
5129            }
5130            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5131            if (sequenceNumbers == null) {
5132                sequenceNumbers = new HashMap<>();
5133                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5134            }
5135            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5136            if (sequenceNumber != null) {
5137                changedPackages.remove(sequenceNumber);
5138            }
5139            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5140            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5141        }
5142        mChangedPackagesSequenceNumber++;
5143    }
5144
5145    @Override
5146    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5147        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5148            return null;
5149        }
5150        synchronized (mPackages) {
5151            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5152                return null;
5153            }
5154            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5155            if (changedPackages == null) {
5156                return null;
5157            }
5158            final List<String> packageNames =
5159                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5160            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5161                final String packageName = changedPackages.get(i);
5162                if (packageName != null) {
5163                    packageNames.add(packageName);
5164                }
5165            }
5166            return packageNames.isEmpty()
5167                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5168        }
5169    }
5170
5171    @Override
5172    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5173        // allow instant applications
5174        ArrayList<FeatureInfo> res;
5175        synchronized (mAvailableFeatures) {
5176            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5177            res.addAll(mAvailableFeatures.values());
5178        }
5179        final FeatureInfo fi = new FeatureInfo();
5180        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5181                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5182        res.add(fi);
5183
5184        return new ParceledListSlice<>(res);
5185    }
5186
5187    @Override
5188    public boolean hasSystemFeature(String name, int version) {
5189        // allow instant applications
5190        synchronized (mAvailableFeatures) {
5191            final FeatureInfo feat = mAvailableFeatures.get(name);
5192            if (feat == null) {
5193                return false;
5194            } else {
5195                return feat.version >= version;
5196            }
5197        }
5198    }
5199
5200    @Override
5201    public int checkPermission(String permName, String pkgName, int userId) {
5202        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5203    }
5204
5205    @Override
5206    public int checkUidPermission(String permName, int uid) {
5207        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5208    }
5209
5210    @Override
5211    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5212        if (UserHandle.getCallingUserId() != userId) {
5213            mContext.enforceCallingPermission(
5214                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5215                    "isPermissionRevokedByPolicy for user " + userId);
5216        }
5217
5218        if (checkPermission(permission, packageName, userId)
5219                == PackageManager.PERMISSION_GRANTED) {
5220            return false;
5221        }
5222
5223        final int callingUid = Binder.getCallingUid();
5224        if (getInstantAppPackageName(callingUid) != null) {
5225            if (!isCallerSameApp(packageName, callingUid)) {
5226                return false;
5227            }
5228        } else {
5229            if (isInstantApp(packageName, userId)) {
5230                return false;
5231            }
5232        }
5233
5234        final long identity = Binder.clearCallingIdentity();
5235        try {
5236            final int flags = getPermissionFlags(permission, packageName, userId);
5237            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5238        } finally {
5239            Binder.restoreCallingIdentity(identity);
5240        }
5241    }
5242
5243    @Override
5244    public String getPermissionControllerPackageName() {
5245        synchronized (mPackages) {
5246            return mRequiredInstallerPackage;
5247        }
5248    }
5249
5250    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5251        return mPermissionManager.addDynamicPermission(
5252                info, async, getCallingUid(), new PermissionCallback() {
5253                    @Override
5254                    public void onPermissionChanged() {
5255                        if (!async) {
5256                            mSettings.writeLPr();
5257                        } else {
5258                            scheduleWriteSettingsLocked();
5259                        }
5260                    }
5261                });
5262    }
5263
5264    @Override
5265    public boolean addPermission(PermissionInfo info) {
5266        synchronized (mPackages) {
5267            return addDynamicPermission(info, false);
5268        }
5269    }
5270
5271    @Override
5272    public boolean addPermissionAsync(PermissionInfo info) {
5273        synchronized (mPackages) {
5274            return addDynamicPermission(info, true);
5275        }
5276    }
5277
5278    @Override
5279    public void removePermission(String permName) {
5280        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5281    }
5282
5283    @Override
5284    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5285        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5286                getCallingUid(), userId, mPermissionCallback);
5287    }
5288
5289    @Override
5290    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5291        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5292                getCallingUid(), userId, mPermissionCallback);
5293    }
5294
5295    @Override
5296    public void resetRuntimePermissions() {
5297        mContext.enforceCallingOrSelfPermission(
5298                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5299                "revokeRuntimePermission");
5300
5301        int callingUid = Binder.getCallingUid();
5302        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5303            mContext.enforceCallingOrSelfPermission(
5304                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5305                    "resetRuntimePermissions");
5306        }
5307
5308        synchronized (mPackages) {
5309            mPermissionManager.updateAllPermissions(
5310                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5311                    mPermissionCallback);
5312            for (int userId : UserManagerService.getInstance().getUserIds()) {
5313                final int packageCount = mPackages.size();
5314                for (int i = 0; i < packageCount; i++) {
5315                    PackageParser.Package pkg = mPackages.valueAt(i);
5316                    if (!(pkg.mExtras instanceof PackageSetting)) {
5317                        continue;
5318                    }
5319                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5320                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5321                }
5322            }
5323        }
5324    }
5325
5326    @Override
5327    public int getPermissionFlags(String permName, String packageName, int userId) {
5328        return mPermissionManager.getPermissionFlags(
5329                permName, packageName, getCallingUid(), userId);
5330    }
5331
5332    @Override
5333    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5334            int flagValues, int userId) {
5335        mPermissionManager.updatePermissionFlags(
5336                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5337                mPermissionCallback);
5338    }
5339
5340    /**
5341     * Update the permission flags for all packages and runtime permissions of a user in order
5342     * to allow device or profile owner to remove POLICY_FIXED.
5343     */
5344    @Override
5345    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5346        synchronized (mPackages) {
5347            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5348                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5349                    mPermissionCallback);
5350            if (changed) {
5351                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5352            }
5353        }
5354    }
5355
5356    @Override
5357    public boolean shouldShowRequestPermissionRationale(String permissionName,
5358            String packageName, int userId) {
5359        if (UserHandle.getCallingUserId() != userId) {
5360            mContext.enforceCallingPermission(
5361                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5362                    "canShowRequestPermissionRationale for user " + userId);
5363        }
5364
5365        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5366        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5367            return false;
5368        }
5369
5370        if (checkPermission(permissionName, packageName, userId)
5371                == PackageManager.PERMISSION_GRANTED) {
5372            return false;
5373        }
5374
5375        final int flags;
5376
5377        final long identity = Binder.clearCallingIdentity();
5378        try {
5379            flags = getPermissionFlags(permissionName,
5380                    packageName, userId);
5381        } finally {
5382            Binder.restoreCallingIdentity(identity);
5383        }
5384
5385        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5386                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5387                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5388
5389        if ((flags & fixedFlags) != 0) {
5390            return false;
5391        }
5392
5393        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5394    }
5395
5396    @Override
5397    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5398        mContext.enforceCallingOrSelfPermission(
5399                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5400                "addOnPermissionsChangeListener");
5401
5402        synchronized (mPackages) {
5403            mOnPermissionChangeListeners.addListenerLocked(listener);
5404        }
5405    }
5406
5407    @Override
5408    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5409        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5410            throw new SecurityException("Instant applications don't have access to this method");
5411        }
5412        synchronized (mPackages) {
5413            mOnPermissionChangeListeners.removeListenerLocked(listener);
5414        }
5415    }
5416
5417    @Override
5418    public boolean isProtectedBroadcast(String actionName) {
5419        // allow instant applications
5420        synchronized (mProtectedBroadcasts) {
5421            if (mProtectedBroadcasts.contains(actionName)) {
5422                return true;
5423            } else if (actionName != null) {
5424                // TODO: remove these terrible hacks
5425                if (actionName.startsWith("android.net.netmon.lingerExpired")
5426                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5427                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5428                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5429                    return true;
5430                }
5431            }
5432        }
5433        return false;
5434    }
5435
5436    @Override
5437    public int checkSignatures(String pkg1, String pkg2) {
5438        synchronized (mPackages) {
5439            final PackageParser.Package p1 = mPackages.get(pkg1);
5440            final PackageParser.Package p2 = mPackages.get(pkg2);
5441            if (p1 == null || p1.mExtras == null
5442                    || p2 == null || p2.mExtras == null) {
5443                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5444            }
5445            final int callingUid = Binder.getCallingUid();
5446            final int callingUserId = UserHandle.getUserId(callingUid);
5447            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5448            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5449            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5450                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5451                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5452            }
5453            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5454        }
5455    }
5456
5457    @Override
5458    public int checkUidSignatures(int uid1, int uid2) {
5459        final int callingUid = Binder.getCallingUid();
5460        final int callingUserId = UserHandle.getUserId(callingUid);
5461        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5462        // Map to base uids.
5463        uid1 = UserHandle.getAppId(uid1);
5464        uid2 = UserHandle.getAppId(uid2);
5465        // reader
5466        synchronized (mPackages) {
5467            Signature[] s1;
5468            Signature[] s2;
5469            Object obj = mSettings.getUserIdLPr(uid1);
5470            if (obj != null) {
5471                if (obj instanceof SharedUserSetting) {
5472                    if (isCallerInstantApp) {
5473                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5474                    }
5475                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5476                } else if (obj instanceof PackageSetting) {
5477                    final PackageSetting ps = (PackageSetting) obj;
5478                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5479                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5480                    }
5481                    s1 = ps.signatures.mSigningDetails.signatures;
5482                } else {
5483                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5484                }
5485            } else {
5486                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5487            }
5488            obj = mSettings.getUserIdLPr(uid2);
5489            if (obj != null) {
5490                if (obj instanceof SharedUserSetting) {
5491                    if (isCallerInstantApp) {
5492                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5493                    }
5494                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5495                } else if (obj instanceof PackageSetting) {
5496                    final PackageSetting ps = (PackageSetting) obj;
5497                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5498                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5499                    }
5500                    s2 = ps.signatures.mSigningDetails.signatures;
5501                } else {
5502                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5503                }
5504            } else {
5505                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5506            }
5507            return compareSignatures(s1, s2);
5508        }
5509    }
5510
5511    @Override
5512    public boolean hasSigningCertificate(
5513            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5514
5515        synchronized (mPackages) {
5516            final PackageParser.Package p = mPackages.get(packageName);
5517            if (p == null || p.mExtras == null) {
5518                return false;
5519            }
5520            final int callingUid = Binder.getCallingUid();
5521            final int callingUserId = UserHandle.getUserId(callingUid);
5522            final PackageSetting ps = (PackageSetting) p.mExtras;
5523            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5524                return false;
5525            }
5526            switch (type) {
5527                case CERT_INPUT_RAW_X509:
5528                    return p.mSigningDetails.hasCertificate(certificate);
5529                case CERT_INPUT_SHA256:
5530                    return p.mSigningDetails.hasSha256Certificate(certificate);
5531                default:
5532                    return false;
5533            }
5534        }
5535    }
5536
5537    @Override
5538    public boolean hasUidSigningCertificate(
5539            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5540        final int callingUid = Binder.getCallingUid();
5541        final int callingUserId = UserHandle.getUserId(callingUid);
5542        // Map to base uids.
5543        uid = UserHandle.getAppId(uid);
5544        // reader
5545        synchronized (mPackages) {
5546            final PackageParser.SigningDetails signingDetails;
5547            final Object obj = mSettings.getUserIdLPr(uid);
5548            if (obj != null) {
5549                if (obj instanceof SharedUserSetting) {
5550                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5551                    if (isCallerInstantApp) {
5552                        return false;
5553                    }
5554                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5555                } else if (obj instanceof PackageSetting) {
5556                    final PackageSetting ps = (PackageSetting) obj;
5557                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5558                        return false;
5559                    }
5560                    signingDetails = ps.signatures.mSigningDetails;
5561                } else {
5562                    return false;
5563                }
5564            } else {
5565                return false;
5566            }
5567            switch (type) {
5568                case CERT_INPUT_RAW_X509:
5569                    return signingDetails.hasCertificate(certificate);
5570                case CERT_INPUT_SHA256:
5571                    return signingDetails.hasSha256Certificate(certificate);
5572                default:
5573                    return false;
5574            }
5575        }
5576    }
5577
5578    /**
5579     * This method should typically only be used when granting or revoking
5580     * permissions, since the app may immediately restart after this call.
5581     * <p>
5582     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5583     * guard your work against the app being relaunched.
5584     */
5585    private void killUid(int appId, int userId, String reason) {
5586        final long identity = Binder.clearCallingIdentity();
5587        try {
5588            IActivityManager am = ActivityManager.getService();
5589            if (am != null) {
5590                try {
5591                    am.killUid(appId, userId, reason);
5592                } catch (RemoteException e) {
5593                    /* ignore - same process */
5594                }
5595            }
5596        } finally {
5597            Binder.restoreCallingIdentity(identity);
5598        }
5599    }
5600
5601    /**
5602     * If the database version for this type of package (internal storage or
5603     * external storage) is less than the version where package signatures
5604     * were updated, return true.
5605     */
5606    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5607        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5608        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5609    }
5610
5611    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5612        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5613        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5614    }
5615
5616    @Override
5617    public List<String> getAllPackages() {
5618        final int callingUid = Binder.getCallingUid();
5619        final int callingUserId = UserHandle.getUserId(callingUid);
5620        synchronized (mPackages) {
5621            if (canViewInstantApps(callingUid, callingUserId)) {
5622                return new ArrayList<String>(mPackages.keySet());
5623            }
5624            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5625            final List<String> result = new ArrayList<>();
5626            if (instantAppPkgName != null) {
5627                // caller is an instant application; filter unexposed applications
5628                for (PackageParser.Package pkg : mPackages.values()) {
5629                    if (!pkg.visibleToInstantApps) {
5630                        continue;
5631                    }
5632                    result.add(pkg.packageName);
5633                }
5634            } else {
5635                // caller is a normal application; filter instant applications
5636                for (PackageParser.Package pkg : mPackages.values()) {
5637                    final PackageSetting ps =
5638                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5639                    if (ps != null
5640                            && ps.getInstantApp(callingUserId)
5641                            && !mInstantAppRegistry.isInstantAccessGranted(
5642                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5643                        continue;
5644                    }
5645                    result.add(pkg.packageName);
5646                }
5647            }
5648            return result;
5649        }
5650    }
5651
5652    @Override
5653    public String[] getPackagesForUid(int uid) {
5654        final int callingUid = Binder.getCallingUid();
5655        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5656        final int userId = UserHandle.getUserId(uid);
5657        uid = UserHandle.getAppId(uid);
5658        // reader
5659        synchronized (mPackages) {
5660            Object obj = mSettings.getUserIdLPr(uid);
5661            if (obj instanceof SharedUserSetting) {
5662                if (isCallerInstantApp) {
5663                    return null;
5664                }
5665                final SharedUserSetting sus = (SharedUserSetting) obj;
5666                final int N = sus.packages.size();
5667                String[] res = new String[N];
5668                final Iterator<PackageSetting> it = sus.packages.iterator();
5669                int i = 0;
5670                while (it.hasNext()) {
5671                    PackageSetting ps = it.next();
5672                    if (ps.getInstalled(userId)) {
5673                        res[i++] = ps.name;
5674                    } else {
5675                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5676                    }
5677                }
5678                return res;
5679            } else if (obj instanceof PackageSetting) {
5680                final PackageSetting ps = (PackageSetting) obj;
5681                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5682                    return new String[]{ps.name};
5683                }
5684            }
5685        }
5686        return null;
5687    }
5688
5689    @Override
5690    public String getNameForUid(int uid) {
5691        final int callingUid = Binder.getCallingUid();
5692        if (getInstantAppPackageName(callingUid) != null) {
5693            return null;
5694        }
5695        synchronized (mPackages) {
5696            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5697            if (obj instanceof SharedUserSetting) {
5698                final SharedUserSetting sus = (SharedUserSetting) obj;
5699                return sus.name + ":" + sus.userId;
5700            } else if (obj instanceof PackageSetting) {
5701                final PackageSetting ps = (PackageSetting) obj;
5702                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5703                    return null;
5704                }
5705                return ps.name;
5706            }
5707            return null;
5708        }
5709    }
5710
5711    @Override
5712    public String[] getNamesForUids(int[] uids) {
5713        if (uids == null || uids.length == 0) {
5714            return null;
5715        }
5716        final int callingUid = Binder.getCallingUid();
5717        if (getInstantAppPackageName(callingUid) != null) {
5718            return null;
5719        }
5720        final String[] names = new String[uids.length];
5721        synchronized (mPackages) {
5722            for (int i = uids.length - 1; i >= 0; i--) {
5723                final int uid = uids[i];
5724                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5725                if (obj instanceof SharedUserSetting) {
5726                    final SharedUserSetting sus = (SharedUserSetting) obj;
5727                    names[i] = "shared:" + sus.name;
5728                } else if (obj instanceof PackageSetting) {
5729                    final PackageSetting ps = (PackageSetting) obj;
5730                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5731                        names[i] = null;
5732                    } else {
5733                        names[i] = ps.name;
5734                    }
5735                } else {
5736                    names[i] = null;
5737                }
5738            }
5739        }
5740        return names;
5741    }
5742
5743    @Override
5744    public int getUidForSharedUser(String sharedUserName) {
5745        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5746            return -1;
5747        }
5748        if (sharedUserName == null) {
5749            return -1;
5750        }
5751        // reader
5752        synchronized (mPackages) {
5753            SharedUserSetting suid;
5754            try {
5755                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5756                if (suid != null) {
5757                    return suid.userId;
5758                }
5759            } catch (PackageManagerException ignore) {
5760                // can't happen, but, still need to catch it
5761            }
5762            return -1;
5763        }
5764    }
5765
5766    @Override
5767    public int getFlagsForUid(int uid) {
5768        final int callingUid = Binder.getCallingUid();
5769        if (getInstantAppPackageName(callingUid) != null) {
5770            return 0;
5771        }
5772        synchronized (mPackages) {
5773            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5774            if (obj instanceof SharedUserSetting) {
5775                final SharedUserSetting sus = (SharedUserSetting) obj;
5776                return sus.pkgFlags;
5777            } else if (obj instanceof PackageSetting) {
5778                final PackageSetting ps = (PackageSetting) obj;
5779                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5780                    return 0;
5781                }
5782                return ps.pkgFlags;
5783            }
5784        }
5785        return 0;
5786    }
5787
5788    @Override
5789    public int getPrivateFlagsForUid(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.pkgPrivateFlags;
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.pkgPrivateFlags;
5805            }
5806        }
5807        return 0;
5808    }
5809
5810    @Override
5811    public boolean isUidPrivileged(int uid) {
5812        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5813            return false;
5814        }
5815        uid = UserHandle.getAppId(uid);
5816        // reader
5817        synchronized (mPackages) {
5818            Object obj = mSettings.getUserIdLPr(uid);
5819            if (obj instanceof SharedUserSetting) {
5820                final SharedUserSetting sus = (SharedUserSetting) obj;
5821                final Iterator<PackageSetting> it = sus.packages.iterator();
5822                while (it.hasNext()) {
5823                    if (it.next().isPrivileged()) {
5824                        return true;
5825                    }
5826                }
5827            } else if (obj instanceof PackageSetting) {
5828                final PackageSetting ps = (PackageSetting) obj;
5829                return ps.isPrivileged();
5830            }
5831        }
5832        return false;
5833    }
5834
5835    @Override
5836    public String[] getAppOpPermissionPackages(String permName) {
5837        return mPermissionManager.getAppOpPermissionPackages(permName);
5838    }
5839
5840    @Override
5841    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5842            int flags, int userId) {
5843        return resolveIntentInternal(
5844                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5845    }
5846
5847    /**
5848     * Normally instant apps can only be resolved when they're visible to the caller.
5849     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5850     * since we need to allow the system to start any installed application.
5851     */
5852    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5853            int flags, int userId, boolean resolveForStart) {
5854        try {
5855            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5856
5857            if (!sUserManager.exists(userId)) return null;
5858            final int callingUid = Binder.getCallingUid();
5859            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5860            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5861                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5862
5863            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5864            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5865                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5866            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5867
5868            final ResolveInfo bestChoice =
5869                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5870            return bestChoice;
5871        } finally {
5872            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5873        }
5874    }
5875
5876    @Override
5877    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5878        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5879            throw new SecurityException(
5880                    "findPersistentPreferredActivity can only be run by the system");
5881        }
5882        if (!sUserManager.exists(userId)) {
5883            return null;
5884        }
5885        final int callingUid = Binder.getCallingUid();
5886        intent = updateIntentForResolve(intent);
5887        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5888        final int flags = updateFlagsForResolve(
5889                0, userId, intent, callingUid, false /*includeInstantApps*/);
5890        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5891                userId);
5892        synchronized (mPackages) {
5893            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5894                    userId);
5895        }
5896    }
5897
5898    @Override
5899    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5900            IntentFilter filter, int match, ComponentName activity) {
5901        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5902            return;
5903        }
5904        final int userId = UserHandle.getCallingUserId();
5905        if (DEBUG_PREFERRED) {
5906            Log.v(TAG, "setLastChosenActivity intent=" + intent
5907                + " resolvedType=" + resolvedType
5908                + " flags=" + flags
5909                + " filter=" + filter
5910                + " match=" + match
5911                + " activity=" + activity);
5912            filter.dump(new PrintStreamPrinter(System.out), "    ");
5913        }
5914        intent.setComponent(null);
5915        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5916                userId);
5917        // Find any earlier preferred or last chosen entries and nuke them
5918        findPreferredActivity(intent, resolvedType,
5919                flags, query, 0, false, true, false, userId);
5920        // Add the new activity as the last chosen for this filter
5921        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5922                "Setting last chosen");
5923    }
5924
5925    @Override
5926    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5927        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5928            return null;
5929        }
5930        final int userId = UserHandle.getCallingUserId();
5931        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5932        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5933                userId);
5934        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5935                false, false, false, userId);
5936    }
5937
5938    /**
5939     * Returns whether or not instant apps have been disabled remotely.
5940     */
5941    private boolean isEphemeralDisabled() {
5942        return mEphemeralAppsDisabled;
5943    }
5944
5945    private boolean isInstantAppAllowed(
5946            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5947            boolean skipPackageCheck) {
5948        if (mInstantAppResolverConnection == null) {
5949            return false;
5950        }
5951        if (mInstantAppInstallerActivity == null) {
5952            return false;
5953        }
5954        if (intent.getComponent() != null) {
5955            return false;
5956        }
5957        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5958            return false;
5959        }
5960        if (!skipPackageCheck && intent.getPackage() != null) {
5961            return false;
5962        }
5963        if (!intent.isBrowsableWebIntent()) {
5964            // for non web intents, we should not resolve externally if an app already exists to
5965            // handle it or if the caller didn't explicitly request it.
5966            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5967                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5968                return false;
5969            }
5970        } else if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5971            return false;
5972        }
5973        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5974        // Or if there's already an ephemeral app installed that handles the action
5975        synchronized (mPackages) {
5976            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5977            for (int n = 0; n < count; n++) {
5978                final ResolveInfo info = resolvedActivities.get(n);
5979                final String packageName = info.activityInfo.packageName;
5980                final PackageSetting ps = mSettings.mPackages.get(packageName);
5981                if (ps != null) {
5982                    // only check domain verification status if the app is not a browser
5983                    if (!info.handleAllWebDataURI) {
5984                        // Try to get the status from User settings first
5985                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5986                        final int status = (int) (packedStatus >> 32);
5987                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5988                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5989                            if (DEBUG_INSTANT) {
5990                                Slog.v(TAG, "DENY instant app;"
5991                                    + " pkg: " + packageName + ", status: " + status);
5992                            }
5993                            return false;
5994                        }
5995                    }
5996                    if (ps.getInstantApp(userId)) {
5997                        if (DEBUG_INSTANT) {
5998                            Slog.v(TAG, "DENY instant app installed;"
5999                                    + " pkg: " + packageName);
6000                        }
6001                        return false;
6002                    }
6003                }
6004            }
6005        }
6006        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6007        return true;
6008    }
6009
6010    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6011            Intent origIntent, String resolvedType, String callingPackage,
6012            Bundle verificationBundle, int userId) {
6013        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6014                new InstantAppRequest(responseObj, origIntent, resolvedType,
6015                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6016        mHandler.sendMessage(msg);
6017    }
6018
6019    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6020            int flags, List<ResolveInfo> query, int userId) {
6021        if (query != null) {
6022            final int N = query.size();
6023            if (N == 1) {
6024                return query.get(0);
6025            } else if (N > 1) {
6026                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6027                // If there is more than one activity with the same priority,
6028                // then let the user decide between them.
6029                ResolveInfo r0 = query.get(0);
6030                ResolveInfo r1 = query.get(1);
6031                if (DEBUG_INTENT_MATCHING || debug) {
6032                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6033                            + r1.activityInfo.name + "=" + r1.priority);
6034                }
6035                // If the first activity has a higher priority, or a different
6036                // default, then it is always desirable to pick it.
6037                if (r0.priority != r1.priority
6038                        || r0.preferredOrder != r1.preferredOrder
6039                        || r0.isDefault != r1.isDefault) {
6040                    return query.get(0);
6041                }
6042                // If we have saved a preference for a preferred activity for
6043                // this Intent, use that.
6044                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6045                        flags, query, r0.priority, true, false, debug, userId);
6046                if (ri != null) {
6047                    return ri;
6048                }
6049                // If we have an ephemeral app, use it
6050                for (int i = 0; i < N; i++) {
6051                    ri = query.get(i);
6052                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6053                        final String packageName = ri.activityInfo.packageName;
6054                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6055                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6056                        final int status = (int)(packedStatus >> 32);
6057                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6058                            return ri;
6059                        }
6060                    }
6061                }
6062                ri = new ResolveInfo(mResolveInfo);
6063                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6064                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6065                // If all of the options come from the same package, show the application's
6066                // label and icon instead of the generic resolver's.
6067                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6068                // and then throw away the ResolveInfo itself, meaning that the caller loses
6069                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6070                // a fallback for this case; we only set the target package's resources on
6071                // the ResolveInfo, not the ActivityInfo.
6072                final String intentPackage = intent.getPackage();
6073                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6074                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6075                    ri.resolvePackageName = intentPackage;
6076                    if (userNeedsBadging(userId)) {
6077                        ri.noResourceId = true;
6078                    } else {
6079                        ri.icon = appi.icon;
6080                    }
6081                    ri.iconResourceId = appi.icon;
6082                    ri.labelRes = appi.labelRes;
6083                }
6084                ri.activityInfo.applicationInfo = new ApplicationInfo(
6085                        ri.activityInfo.applicationInfo);
6086                if (userId != 0) {
6087                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6088                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6089                }
6090                // Make sure that the resolver is displayable in car mode
6091                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6092                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6093                return ri;
6094            }
6095        }
6096        return null;
6097    }
6098
6099    /**
6100     * Return true if the given list is not empty and all of its contents have
6101     * an activityInfo with the given package name.
6102     */
6103    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6104        if (ArrayUtils.isEmpty(list)) {
6105            return false;
6106        }
6107        for (int i = 0, N = list.size(); i < N; i++) {
6108            final ResolveInfo ri = list.get(i);
6109            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6110            if (ai == null || !packageName.equals(ai.packageName)) {
6111                return false;
6112            }
6113        }
6114        return true;
6115    }
6116
6117    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6118            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6119        final int N = query.size();
6120        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6121                .get(userId);
6122        // Get the list of persistent preferred activities that handle the intent
6123        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6124        List<PersistentPreferredActivity> pprefs = ppir != null
6125                ? ppir.queryIntent(intent, resolvedType,
6126                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6127                        userId)
6128                : null;
6129        if (pprefs != null && pprefs.size() > 0) {
6130            final int M = pprefs.size();
6131            for (int i=0; i<M; i++) {
6132                final PersistentPreferredActivity ppa = pprefs.get(i);
6133                if (DEBUG_PREFERRED || debug) {
6134                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6135                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6136                            + "\n  component=" + ppa.mComponent);
6137                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6138                }
6139                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6140                        flags | MATCH_DISABLED_COMPONENTS, userId);
6141                if (DEBUG_PREFERRED || debug) {
6142                    Slog.v(TAG, "Found persistent preferred activity:");
6143                    if (ai != null) {
6144                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6145                    } else {
6146                        Slog.v(TAG, "  null");
6147                    }
6148                }
6149                if (ai == null) {
6150                    // This previously registered persistent preferred activity
6151                    // component is no longer known. Ignore it and do NOT remove it.
6152                    continue;
6153                }
6154                for (int j=0; j<N; j++) {
6155                    final ResolveInfo ri = query.get(j);
6156                    if (!ri.activityInfo.applicationInfo.packageName
6157                            .equals(ai.applicationInfo.packageName)) {
6158                        continue;
6159                    }
6160                    if (!ri.activityInfo.name.equals(ai.name)) {
6161                        continue;
6162                    }
6163                    //  Found a persistent preference that can handle the intent.
6164                    if (DEBUG_PREFERRED || debug) {
6165                        Slog.v(TAG, "Returning persistent preferred activity: " +
6166                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6167                    }
6168                    return ri;
6169                }
6170            }
6171        }
6172        return null;
6173    }
6174
6175    // TODO: handle preferred activities missing while user has amnesia
6176    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6177            List<ResolveInfo> query, int priority, boolean always,
6178            boolean removeMatches, boolean debug, int userId) {
6179        if (!sUserManager.exists(userId)) return null;
6180        final int callingUid = Binder.getCallingUid();
6181        flags = updateFlagsForResolve(
6182                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6183        intent = updateIntentForResolve(intent);
6184        // writer
6185        synchronized (mPackages) {
6186            // Try to find a matching persistent preferred activity.
6187            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6188                    debug, userId);
6189
6190            // If a persistent preferred activity matched, use it.
6191            if (pri != null) {
6192                return pri;
6193            }
6194
6195            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6196            // Get the list of preferred activities that handle the intent
6197            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6198            List<PreferredActivity> prefs = pir != null
6199                    ? pir.queryIntent(intent, resolvedType,
6200                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6201                            userId)
6202                    : null;
6203            if (prefs != null && prefs.size() > 0) {
6204                boolean changed = false;
6205                try {
6206                    // First figure out how good the original match set is.
6207                    // We will only allow preferred activities that came
6208                    // from the same match quality.
6209                    int match = 0;
6210
6211                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6212
6213                    final int N = query.size();
6214                    for (int j=0; j<N; j++) {
6215                        final ResolveInfo ri = query.get(j);
6216                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6217                                + ": 0x" + Integer.toHexString(match));
6218                        if (ri.match > match) {
6219                            match = ri.match;
6220                        }
6221                    }
6222
6223                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6224                            + Integer.toHexString(match));
6225
6226                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6227                    final int M = prefs.size();
6228                    for (int i=0; i<M; i++) {
6229                        final PreferredActivity pa = prefs.get(i);
6230                        if (DEBUG_PREFERRED || debug) {
6231                            Slog.v(TAG, "Checking PreferredActivity ds="
6232                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6233                                    + "\n  component=" + pa.mPref.mComponent);
6234                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6235                        }
6236                        if (pa.mPref.mMatch != match) {
6237                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6238                                    + Integer.toHexString(pa.mPref.mMatch));
6239                            continue;
6240                        }
6241                        // If it's not an "always" type preferred activity and that's what we're
6242                        // looking for, skip it.
6243                        if (always && !pa.mPref.mAlways) {
6244                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6245                            continue;
6246                        }
6247                        final ActivityInfo ai = getActivityInfo(
6248                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6249                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6250                                userId);
6251                        if (DEBUG_PREFERRED || debug) {
6252                            Slog.v(TAG, "Found preferred activity:");
6253                            if (ai != null) {
6254                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6255                            } else {
6256                                Slog.v(TAG, "  null");
6257                            }
6258                        }
6259                        if (ai == null) {
6260                            // This previously registered preferred activity
6261                            // component is no longer known.  Most likely an update
6262                            // to the app was installed and in the new version this
6263                            // component no longer exists.  Clean it up by removing
6264                            // it from the preferred activities list, and skip it.
6265                            Slog.w(TAG, "Removing dangling preferred activity: "
6266                                    + pa.mPref.mComponent);
6267                            pir.removeFilter(pa);
6268                            changed = true;
6269                            continue;
6270                        }
6271                        for (int j=0; j<N; j++) {
6272                            final ResolveInfo ri = query.get(j);
6273                            if (!ri.activityInfo.applicationInfo.packageName
6274                                    .equals(ai.applicationInfo.packageName)) {
6275                                continue;
6276                            }
6277                            if (!ri.activityInfo.name.equals(ai.name)) {
6278                                continue;
6279                            }
6280
6281                            if (removeMatches) {
6282                                pir.removeFilter(pa);
6283                                changed = true;
6284                                if (DEBUG_PREFERRED) {
6285                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6286                                }
6287                                break;
6288                            }
6289
6290                            // Okay we found a previously set preferred or last chosen app.
6291                            // If the result set is different from when this
6292                            // was created, and is not a subset of the preferred set, we need to
6293                            // clear it and re-ask the user their preference, if we're looking for
6294                            // an "always" type entry.
6295                            if (always && !pa.mPref.sameSet(query)) {
6296                                if (pa.mPref.isSuperset(query)) {
6297                                    // some components of the set are no longer present in
6298                                    // the query, but the preferred activity can still be reused
6299                                    if (DEBUG_PREFERRED) {
6300                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6301                                                + " still valid as only non-preferred components"
6302                                                + " were removed for " + intent + " type "
6303                                                + resolvedType);
6304                                    }
6305                                    // remove obsolete components and re-add the up-to-date filter
6306                                    PreferredActivity freshPa = new PreferredActivity(pa,
6307                                            pa.mPref.mMatch,
6308                                            pa.mPref.discardObsoleteComponents(query),
6309                                            pa.mPref.mComponent,
6310                                            pa.mPref.mAlways);
6311                                    pir.removeFilter(pa);
6312                                    pir.addFilter(freshPa);
6313                                    changed = true;
6314                                } else {
6315                                    Slog.i(TAG,
6316                                            "Result set changed, dropping preferred activity for "
6317                                                    + intent + " type " + resolvedType);
6318                                    if (DEBUG_PREFERRED) {
6319                                        Slog.v(TAG, "Removing preferred activity since set changed "
6320                                                + pa.mPref.mComponent);
6321                                    }
6322                                    pir.removeFilter(pa);
6323                                    // Re-add the filter as a "last chosen" entry (!always)
6324                                    PreferredActivity lastChosen = new PreferredActivity(
6325                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6326                                    pir.addFilter(lastChosen);
6327                                    changed = true;
6328                                    return null;
6329                                }
6330                            }
6331
6332                            // Yay! Either the set matched or we're looking for the last chosen
6333                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6334                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6335                            return ri;
6336                        }
6337                    }
6338                } finally {
6339                    if (changed) {
6340                        if (DEBUG_PREFERRED) {
6341                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6342                        }
6343                        scheduleWritePackageRestrictionsLocked(userId);
6344                    }
6345                }
6346            }
6347        }
6348        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6349        return null;
6350    }
6351
6352    /*
6353     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6354     */
6355    @Override
6356    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6357            int targetUserId) {
6358        mContext.enforceCallingOrSelfPermission(
6359                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6360        List<CrossProfileIntentFilter> matches =
6361                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6362        if (matches != null) {
6363            int size = matches.size();
6364            for (int i = 0; i < size; i++) {
6365                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6366            }
6367        }
6368        if (intent.hasWebURI()) {
6369            // cross-profile app linking works only towards the parent.
6370            final int callingUid = Binder.getCallingUid();
6371            final UserInfo parent = getProfileParent(sourceUserId);
6372            synchronized(mPackages) {
6373                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6374                        false /*includeInstantApps*/);
6375                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6376                        intent, resolvedType, flags, sourceUserId, parent.id);
6377                return xpDomainInfo != null;
6378            }
6379        }
6380        return false;
6381    }
6382
6383    private UserInfo getProfileParent(int userId) {
6384        final long identity = Binder.clearCallingIdentity();
6385        try {
6386            return sUserManager.getProfileParent(userId);
6387        } finally {
6388            Binder.restoreCallingIdentity(identity);
6389        }
6390    }
6391
6392    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6393            String resolvedType, int userId) {
6394        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6395        if (resolver != null) {
6396            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6397        }
6398        return null;
6399    }
6400
6401    @Override
6402    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6403            String resolvedType, int flags, int userId) {
6404        try {
6405            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6406
6407            return new ParceledListSlice<>(
6408                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6409        } finally {
6410            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6411        }
6412    }
6413
6414    /**
6415     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6416     * instant, returns {@code null}.
6417     */
6418    private String getInstantAppPackageName(int callingUid) {
6419        synchronized (mPackages) {
6420            // If the caller is an isolated app use the owner's uid for the lookup.
6421            if (Process.isIsolated(callingUid)) {
6422                callingUid = mIsolatedOwners.get(callingUid);
6423            }
6424            final int appId = UserHandle.getAppId(callingUid);
6425            final Object obj = mSettings.getUserIdLPr(appId);
6426            if (obj instanceof PackageSetting) {
6427                final PackageSetting ps = (PackageSetting) obj;
6428                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6429                return isInstantApp ? ps.pkg.packageName : null;
6430            }
6431        }
6432        return null;
6433    }
6434
6435    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6436            String resolvedType, int flags, int userId) {
6437        return queryIntentActivitiesInternal(
6438                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6439                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6440    }
6441
6442    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6443            String resolvedType, int flags, int filterCallingUid, int userId,
6444            boolean resolveForStart, boolean allowDynamicSplits) {
6445        if (!sUserManager.exists(userId)) return Collections.emptyList();
6446        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6447        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6448                false /* requireFullPermission */, false /* checkShell */,
6449                "query intent activities");
6450        final String pkgName = intent.getPackage();
6451        ComponentName comp = intent.getComponent();
6452        if (comp == null) {
6453            if (intent.getSelector() != null) {
6454                intent = intent.getSelector();
6455                comp = intent.getComponent();
6456            }
6457        }
6458
6459        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6460                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6461        if (comp != null) {
6462            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6463            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6464            if (ai != null) {
6465                // When specifying an explicit component, we prevent the activity from being
6466                // used when either 1) the calling package is normal and the activity is within
6467                // an ephemeral application or 2) the calling package is ephemeral and the
6468                // activity is not visible to ephemeral applications.
6469                final boolean matchInstantApp =
6470                        (flags & PackageManager.MATCH_INSTANT) != 0;
6471                final boolean matchVisibleToInstantAppOnly =
6472                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6473                final boolean matchExplicitlyVisibleOnly =
6474                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6475                final boolean isCallerInstantApp =
6476                        instantAppPkgName != null;
6477                final boolean isTargetSameInstantApp =
6478                        comp.getPackageName().equals(instantAppPkgName);
6479                final boolean isTargetInstantApp =
6480                        (ai.applicationInfo.privateFlags
6481                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6482                final boolean isTargetVisibleToInstantApp =
6483                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6484                final boolean isTargetExplicitlyVisibleToInstantApp =
6485                        isTargetVisibleToInstantApp
6486                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6487                final boolean isTargetHiddenFromInstantApp =
6488                        !isTargetVisibleToInstantApp
6489                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6490                final boolean blockResolution =
6491                        !isTargetSameInstantApp
6492                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6493                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6494                                        && isTargetHiddenFromInstantApp));
6495                if (!blockResolution) {
6496                    final ResolveInfo ri = new ResolveInfo();
6497                    ri.activityInfo = ai;
6498                    list.add(ri);
6499                }
6500            }
6501            return applyPostResolutionFilter(
6502                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6503        }
6504
6505        // reader
6506        boolean sortResult = false;
6507        boolean addEphemeral = false;
6508        List<ResolveInfo> result;
6509        final boolean ephemeralDisabled = isEphemeralDisabled();
6510        synchronized (mPackages) {
6511            if (pkgName == null) {
6512                List<CrossProfileIntentFilter> matchingFilters =
6513                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6514                // Check for results that need to skip the current profile.
6515                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6516                        resolvedType, flags, userId);
6517                if (xpResolveInfo != null) {
6518                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6519                    xpResult.add(xpResolveInfo);
6520                    return applyPostResolutionFilter(
6521                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6522                            allowDynamicSplits, filterCallingUid, userId);
6523                }
6524
6525                // Check for results in the current profile.
6526                result = filterIfNotSystemUser(mActivities.queryIntent(
6527                        intent, resolvedType, flags, userId), userId);
6528                addEphemeral = !ephemeralDisabled
6529                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6530                // Check for cross profile results.
6531                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6532                xpResolveInfo = queryCrossProfileIntents(
6533                        matchingFilters, intent, resolvedType, flags, userId,
6534                        hasNonNegativePriorityResult);
6535                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6536                    boolean isVisibleToUser = filterIfNotSystemUser(
6537                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6538                    if (isVisibleToUser) {
6539                        result.add(xpResolveInfo);
6540                        sortResult = true;
6541                    }
6542                }
6543                if (intent.hasWebURI()) {
6544                    CrossProfileDomainInfo xpDomainInfo = null;
6545                    final UserInfo parent = getProfileParent(userId);
6546                    if (parent != null) {
6547                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6548                                flags, userId, parent.id);
6549                    }
6550                    if (xpDomainInfo != null) {
6551                        if (xpResolveInfo != null) {
6552                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6553                            // in the result.
6554                            result.remove(xpResolveInfo);
6555                        }
6556                        if (result.size() == 0 && !addEphemeral) {
6557                            // No result in current profile, but found candidate in parent user.
6558                            // And we are not going to add emphemeral app, so we can return the
6559                            // result straight away.
6560                            result.add(xpDomainInfo.resolveInfo);
6561                            return applyPostResolutionFilter(result, instantAppPkgName,
6562                                    allowDynamicSplits, filterCallingUid, userId);
6563                        }
6564                    } else if (result.size() <= 1 && !addEphemeral) {
6565                        // No result in parent user and <= 1 result in current profile, and we
6566                        // are not going to add emphemeral app, so we can return the result without
6567                        // further processing.
6568                        return applyPostResolutionFilter(result, instantAppPkgName,
6569                                allowDynamicSplits, filterCallingUid, userId);
6570                    }
6571                    // We have more than one candidate (combining results from current and parent
6572                    // profile), so we need filtering and sorting.
6573                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6574                            intent, flags, result, xpDomainInfo, userId);
6575                    sortResult = true;
6576                }
6577            } else {
6578                final PackageParser.Package pkg = mPackages.get(pkgName);
6579                result = null;
6580                if (pkg != null) {
6581                    result = filterIfNotSystemUser(
6582                            mActivities.queryIntentForPackage(
6583                                    intent, resolvedType, flags, pkg.activities, userId),
6584                            userId);
6585                }
6586                if (result == null || result.size() == 0) {
6587                    // the caller wants to resolve for a particular package; however, there
6588                    // were no installed results, so, try to find an ephemeral result
6589                    addEphemeral = !ephemeralDisabled
6590                            && isInstantAppAllowed(
6591                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6592                    if (result == null) {
6593                        result = new ArrayList<>();
6594                    }
6595                }
6596            }
6597        }
6598        if (addEphemeral) {
6599            result = maybeAddInstantAppInstaller(
6600                    result, intent, resolvedType, flags, userId, resolveForStart);
6601        }
6602        if (sortResult) {
6603            Collections.sort(result, mResolvePrioritySorter);
6604        }
6605        return applyPostResolutionFilter(
6606                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6607    }
6608
6609    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6610            String resolvedType, int flags, int userId, boolean resolveForStart) {
6611        // first, check to see if we've got an instant app already installed
6612        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6613        ResolveInfo localInstantApp = null;
6614        boolean blockResolution = false;
6615        if (!alreadyResolvedLocally) {
6616            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6617                    flags
6618                        | PackageManager.GET_RESOLVED_FILTER
6619                        | PackageManager.MATCH_INSTANT
6620                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6621                    userId);
6622            for (int i = instantApps.size() - 1; i >= 0; --i) {
6623                final ResolveInfo info = instantApps.get(i);
6624                final String packageName = info.activityInfo.packageName;
6625                final PackageSetting ps = mSettings.mPackages.get(packageName);
6626                if (ps.getInstantApp(userId)) {
6627                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6628                    final int status = (int)(packedStatus >> 32);
6629                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6630                        // there's a local instant application installed, but, the user has
6631                        // chosen to never use it; skip resolution and don't acknowledge
6632                        // an instant application is even available
6633                        if (DEBUG_INSTANT) {
6634                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6635                        }
6636                        blockResolution = true;
6637                        break;
6638                    } else {
6639                        // we have a locally installed instant application; skip resolution
6640                        // but acknowledge there's an instant application available
6641                        if (DEBUG_INSTANT) {
6642                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6643                        }
6644                        localInstantApp = info;
6645                        break;
6646                    }
6647                }
6648            }
6649        }
6650        // no app installed, let's see if one's available
6651        AuxiliaryResolveInfo auxiliaryResponse = null;
6652        if (!blockResolution) {
6653            if (localInstantApp == null) {
6654                // we don't have an instant app locally, resolve externally
6655                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6656                final InstantAppRequest requestObject = new InstantAppRequest(
6657                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6658                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6659                        resolveForStart);
6660                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6661                        mInstantAppResolverConnection, requestObject);
6662                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6663            } else {
6664                // we have an instant application locally, but, we can't admit that since
6665                // callers shouldn't be able to determine prior browsing. create a dummy
6666                // auxiliary response so the downstream code behaves as if there's an
6667                // instant application available externally. when it comes time to start
6668                // the instant application, we'll do the right thing.
6669                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6670                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6671                                        ai.packageName, ai.versionCode, null /* splitName */);
6672            }
6673        }
6674        if (intent.isBrowsableWebIntent() && auxiliaryResponse == null) {
6675            return result;
6676        }
6677        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6678        if (ps == null) {
6679            return result;
6680        }
6681        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6682        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6683                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6684        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6685                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6686        // add a non-generic filter
6687        ephemeralInstaller.filter = new IntentFilter();
6688        if (intent.getAction() != null) {
6689            ephemeralInstaller.filter.addAction(intent.getAction());
6690        }
6691        if (intent.getData() != null && intent.getData().getPath() != null) {
6692            ephemeralInstaller.filter.addDataPath(
6693                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6694        }
6695        ephemeralInstaller.isInstantAppAvailable = true;
6696        // make sure this resolver is the default
6697        ephemeralInstaller.isDefault = true;
6698        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6699        if (DEBUG_INSTANT) {
6700            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6701        }
6702
6703        result.add(ephemeralInstaller);
6704        return result;
6705    }
6706
6707    private static class CrossProfileDomainInfo {
6708        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6709        ResolveInfo resolveInfo;
6710        /* Best domain verification status of the activities found in the other profile */
6711        int bestDomainVerificationStatus;
6712    }
6713
6714    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6715            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6716        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6717                sourceUserId)) {
6718            return null;
6719        }
6720        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6721                resolvedType, flags, parentUserId);
6722
6723        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6724            return null;
6725        }
6726        CrossProfileDomainInfo result = null;
6727        int size = resultTargetUser.size();
6728        for (int i = 0; i < size; i++) {
6729            ResolveInfo riTargetUser = resultTargetUser.get(i);
6730            // Intent filter verification is only for filters that specify a host. So don't return
6731            // those that handle all web uris.
6732            if (riTargetUser.handleAllWebDataURI) {
6733                continue;
6734            }
6735            String packageName = riTargetUser.activityInfo.packageName;
6736            PackageSetting ps = mSettings.mPackages.get(packageName);
6737            if (ps == null) {
6738                continue;
6739            }
6740            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6741            int status = (int)(verificationState >> 32);
6742            if (result == null) {
6743                result = new CrossProfileDomainInfo();
6744                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6745                        sourceUserId, parentUserId);
6746                result.bestDomainVerificationStatus = status;
6747            } else {
6748                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6749                        result.bestDomainVerificationStatus);
6750            }
6751        }
6752        // Don't consider matches with status NEVER across profiles.
6753        if (result != null && result.bestDomainVerificationStatus
6754                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6755            return null;
6756        }
6757        return result;
6758    }
6759
6760    /**
6761     * Verification statuses are ordered from the worse to the best, except for
6762     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6763     */
6764    private int bestDomainVerificationStatus(int status1, int status2) {
6765        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6766            return status2;
6767        }
6768        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6769            return status1;
6770        }
6771        return (int) MathUtils.max(status1, status2);
6772    }
6773
6774    private boolean isUserEnabled(int userId) {
6775        long callingId = Binder.clearCallingIdentity();
6776        try {
6777            UserInfo userInfo = sUserManager.getUserInfo(userId);
6778            return userInfo != null && userInfo.isEnabled();
6779        } finally {
6780            Binder.restoreCallingIdentity(callingId);
6781        }
6782    }
6783
6784    /**
6785     * Filter out activities with systemUserOnly flag set, when current user is not System.
6786     *
6787     * @return filtered list
6788     */
6789    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6790        if (userId == UserHandle.USER_SYSTEM) {
6791            return resolveInfos;
6792        }
6793        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6794            ResolveInfo info = resolveInfos.get(i);
6795            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6796                resolveInfos.remove(i);
6797            }
6798        }
6799        return resolveInfos;
6800    }
6801
6802    /**
6803     * Filters out ephemeral activities.
6804     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6805     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6806     *
6807     * @param resolveInfos The pre-filtered list of resolved activities
6808     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6809     *          is performed.
6810     * @return A filtered list of resolved activities.
6811     */
6812    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6813            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6814        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6815            final ResolveInfo info = resolveInfos.get(i);
6816            // allow activities that are defined in the provided package
6817            if (allowDynamicSplits
6818                    && info.activityInfo != null
6819                    && info.activityInfo.splitName != null
6820                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6821                            info.activityInfo.splitName)) {
6822                if (mInstantAppInstallerActivity == null) {
6823                    if (DEBUG_INSTALL) {
6824                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6825                    }
6826                    resolveInfos.remove(i);
6827                    continue;
6828                }
6829                // requested activity is defined in a split that hasn't been installed yet.
6830                // add the installer to the resolve list
6831                if (DEBUG_INSTALL) {
6832                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6833                }
6834                final ResolveInfo installerInfo = new ResolveInfo(
6835                        mInstantAppInstallerInfo);
6836                final ComponentName installFailureActivity = findInstallFailureActivity(
6837                        info.activityInfo.packageName,  filterCallingUid, userId);
6838                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6839                        installFailureActivity,
6840                        info.activityInfo.packageName,
6841                        info.activityInfo.applicationInfo.versionCode,
6842                        info.activityInfo.splitName);
6843                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6844                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6845                // add a non-generic filter
6846                installerInfo.filter = new IntentFilter();
6847
6848                // This resolve info may appear in the chooser UI, so let us make it
6849                // look as the one it replaces as far as the user is concerned which
6850                // requires loading the correct label and icon for the resolve info.
6851                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6852                installerInfo.labelRes = info.resolveLabelResId();
6853                installerInfo.icon = info.resolveIconResId();
6854
6855                // propagate priority/preferred order/default
6856                installerInfo.priority = info.priority;
6857                installerInfo.preferredOrder = info.preferredOrder;
6858                installerInfo.isDefault = info.isDefault;
6859                installerInfo.isInstantAppAvailable = true;
6860                resolveInfos.set(i, installerInfo);
6861                continue;
6862            }
6863            // caller is a full app, don't need to apply any other filtering
6864            if (ephemeralPkgName == null) {
6865                continue;
6866            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6867                // caller is same app; don't need to apply any other filtering
6868                continue;
6869            }
6870            // allow activities that have been explicitly exposed to ephemeral apps
6871            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6872            if (!isEphemeralApp
6873                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6874                continue;
6875            }
6876            resolveInfos.remove(i);
6877        }
6878        return resolveInfos;
6879    }
6880
6881    /**
6882     * Returns the activity component that can handle install failures.
6883     * <p>By default, the instant application installer handles failures. However, an
6884     * application may want to handle failures on its own. Applications do this by
6885     * creating an activity with an intent filter that handles the action
6886     * {@link Intent#ACTION_INSTALL_FAILURE}.
6887     */
6888    private @Nullable ComponentName findInstallFailureActivity(
6889            String packageName, int filterCallingUid, int userId) {
6890        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6891        failureActivityIntent.setPackage(packageName);
6892        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6893        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6894                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6895                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6896        final int NR = result.size();
6897        if (NR > 0) {
6898            for (int i = 0; i < NR; i++) {
6899                final ResolveInfo info = result.get(i);
6900                if (info.activityInfo.splitName != null) {
6901                    continue;
6902                }
6903                return new ComponentName(packageName, info.activityInfo.name);
6904            }
6905        }
6906        return null;
6907    }
6908
6909    /**
6910     * @param resolveInfos list of resolve infos in descending priority order
6911     * @return if the list contains a resolve info with non-negative priority
6912     */
6913    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6914        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6915    }
6916
6917    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6918            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6919            int userId) {
6920        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6921
6922        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6923            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6924                    candidates.size());
6925        }
6926
6927        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6928        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6929        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6930        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6931        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6932        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6933
6934        synchronized (mPackages) {
6935            final int count = candidates.size();
6936            // First, try to use linked apps. Partition the candidates into four lists:
6937            // one for the final results, one for the "do not use ever", one for "undefined status"
6938            // and finally one for "browser app type".
6939            for (int n=0; n<count; n++) {
6940                ResolveInfo info = candidates.get(n);
6941                String packageName = info.activityInfo.packageName;
6942                PackageSetting ps = mSettings.mPackages.get(packageName);
6943                if (ps != null) {
6944                    // Add to the special match all list (Browser use case)
6945                    if (info.handleAllWebDataURI) {
6946                        matchAllList.add(info);
6947                        continue;
6948                    }
6949                    // Try to get the status from User settings first
6950                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6951                    int status = (int)(packedStatus >> 32);
6952                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6953                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6954                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6955                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6956                                    + " : linkgen=" + linkGeneration);
6957                        }
6958                        // Use link-enabled generation as preferredOrder, i.e.
6959                        // prefer newly-enabled over earlier-enabled.
6960                        info.preferredOrder = linkGeneration;
6961                        alwaysList.add(info);
6962                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6963                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6964                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6965                        }
6966                        neverList.add(info);
6967                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6968                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6969                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6970                        }
6971                        alwaysAskList.add(info);
6972                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6973                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6974                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6975                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6976                        }
6977                        undefinedList.add(info);
6978                    }
6979                }
6980            }
6981
6982            // We'll want to include browser possibilities in a few cases
6983            boolean includeBrowser = false;
6984
6985            // First try to add the "always" resolution(s) for the current user, if any
6986            if (alwaysList.size() > 0) {
6987                result.addAll(alwaysList);
6988            } else {
6989                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6990                result.addAll(undefinedList);
6991                // Maybe add one for the other profile.
6992                if (xpDomainInfo != null && (
6993                        xpDomainInfo.bestDomainVerificationStatus
6994                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6995                    result.add(xpDomainInfo.resolveInfo);
6996                }
6997                includeBrowser = true;
6998            }
6999
7000            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7001            // If there were 'always' entries their preferred order has been set, so we also
7002            // back that off to make the alternatives equivalent
7003            if (alwaysAskList.size() > 0) {
7004                for (ResolveInfo i : result) {
7005                    i.preferredOrder = 0;
7006                }
7007                result.addAll(alwaysAskList);
7008                includeBrowser = true;
7009            }
7010
7011            if (includeBrowser) {
7012                // Also add browsers (all of them or only the default one)
7013                if (DEBUG_DOMAIN_VERIFICATION) {
7014                    Slog.v(TAG, "   ...including browsers in candidate set");
7015                }
7016                if ((matchFlags & MATCH_ALL) != 0) {
7017                    result.addAll(matchAllList);
7018                } else {
7019                    // Browser/generic handling case.  If there's a default browser, go straight
7020                    // to that (but only if there is no other higher-priority match).
7021                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7022                    int maxMatchPrio = 0;
7023                    ResolveInfo defaultBrowserMatch = null;
7024                    final int numCandidates = matchAllList.size();
7025                    for (int n = 0; n < numCandidates; n++) {
7026                        ResolveInfo info = matchAllList.get(n);
7027                        // track the highest overall match priority...
7028                        if (info.priority > maxMatchPrio) {
7029                            maxMatchPrio = info.priority;
7030                        }
7031                        // ...and the highest-priority default browser match
7032                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7033                            if (defaultBrowserMatch == null
7034                                    || (defaultBrowserMatch.priority < info.priority)) {
7035                                if (debug) {
7036                                    Slog.v(TAG, "Considering default browser match " + info);
7037                                }
7038                                defaultBrowserMatch = info;
7039                            }
7040                        }
7041                    }
7042                    if (defaultBrowserMatch != null
7043                            && defaultBrowserMatch.priority >= maxMatchPrio
7044                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7045                    {
7046                        if (debug) {
7047                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7048                        }
7049                        result.add(defaultBrowserMatch);
7050                    } else {
7051                        result.addAll(matchAllList);
7052                    }
7053                }
7054
7055                // If there is nothing selected, add all candidates and remove the ones that the user
7056                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7057                if (result.size() == 0) {
7058                    result.addAll(candidates);
7059                    result.removeAll(neverList);
7060                }
7061            }
7062        }
7063        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7064            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7065                    result.size());
7066            for (ResolveInfo info : result) {
7067                Slog.v(TAG, "  + " + info.activityInfo);
7068            }
7069        }
7070        return result;
7071    }
7072
7073    // Returns a packed value as a long:
7074    //
7075    // high 'int'-sized word: link status: undefined/ask/never/always.
7076    // low 'int'-sized word: relative priority among 'always' results.
7077    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7078        long result = ps.getDomainVerificationStatusForUser(userId);
7079        // if none available, get the master status
7080        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7081            if (ps.getIntentFilterVerificationInfo() != null) {
7082                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7083            }
7084        }
7085        return result;
7086    }
7087
7088    private ResolveInfo querySkipCurrentProfileIntents(
7089            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7090            int flags, int sourceUserId) {
7091        if (matchingFilters != null) {
7092            int size = matchingFilters.size();
7093            for (int i = 0; i < size; i ++) {
7094                CrossProfileIntentFilter filter = matchingFilters.get(i);
7095                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7096                    // Checking if there are activities in the target user that can handle the
7097                    // intent.
7098                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7099                            resolvedType, flags, sourceUserId);
7100                    if (resolveInfo != null) {
7101                        return resolveInfo;
7102                    }
7103                }
7104            }
7105        }
7106        return null;
7107    }
7108
7109    // Return matching ResolveInfo in target user if any.
7110    private ResolveInfo queryCrossProfileIntents(
7111            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7112            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7113        if (matchingFilters != null) {
7114            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7115            // match the same intent. For performance reasons, it is better not to
7116            // run queryIntent twice for the same userId
7117            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7118            int size = matchingFilters.size();
7119            for (int i = 0; i < size; i++) {
7120                CrossProfileIntentFilter filter = matchingFilters.get(i);
7121                int targetUserId = filter.getTargetUserId();
7122                boolean skipCurrentProfile =
7123                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7124                boolean skipCurrentProfileIfNoMatchFound =
7125                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7126                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7127                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7128                    // Checking if there are activities in the target user that can handle the
7129                    // intent.
7130                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7131                            resolvedType, flags, sourceUserId);
7132                    if (resolveInfo != null) return resolveInfo;
7133                    alreadyTriedUserIds.put(targetUserId, true);
7134                }
7135            }
7136        }
7137        return null;
7138    }
7139
7140    /**
7141     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7142     * will forward the intent to the filter's target user.
7143     * Otherwise, returns null.
7144     */
7145    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7146            String resolvedType, int flags, int sourceUserId) {
7147        int targetUserId = filter.getTargetUserId();
7148        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7149                resolvedType, flags, targetUserId);
7150        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7151            // If all the matches in the target profile are suspended, return null.
7152            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7153                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7154                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7155                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7156                            targetUserId);
7157                }
7158            }
7159        }
7160        return null;
7161    }
7162
7163    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7164            int sourceUserId, int targetUserId) {
7165        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7166        long ident = Binder.clearCallingIdentity();
7167        boolean targetIsProfile;
7168        try {
7169            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7170        } finally {
7171            Binder.restoreCallingIdentity(ident);
7172        }
7173        String className;
7174        if (targetIsProfile) {
7175            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7176        } else {
7177            className = FORWARD_INTENT_TO_PARENT;
7178        }
7179        ComponentName forwardingActivityComponentName = new ComponentName(
7180                mAndroidApplication.packageName, className);
7181        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7182                sourceUserId);
7183        if (!targetIsProfile) {
7184            forwardingActivityInfo.showUserIcon = targetUserId;
7185            forwardingResolveInfo.noResourceId = true;
7186        }
7187        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7188        forwardingResolveInfo.priority = 0;
7189        forwardingResolveInfo.preferredOrder = 0;
7190        forwardingResolveInfo.match = 0;
7191        forwardingResolveInfo.isDefault = true;
7192        forwardingResolveInfo.filter = filter;
7193        forwardingResolveInfo.targetUserId = targetUserId;
7194        return forwardingResolveInfo;
7195    }
7196
7197    @Override
7198    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7199            Intent[] specifics, String[] specificTypes, Intent intent,
7200            String resolvedType, int flags, int userId) {
7201        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7202                specificTypes, intent, resolvedType, flags, userId));
7203    }
7204
7205    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7206            Intent[] specifics, String[] specificTypes, Intent intent,
7207            String resolvedType, int flags, int userId) {
7208        if (!sUserManager.exists(userId)) return Collections.emptyList();
7209        final int callingUid = Binder.getCallingUid();
7210        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7211                false /*includeInstantApps*/);
7212        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7213                false /*requireFullPermission*/, false /*checkShell*/,
7214                "query intent activity options");
7215        final String resultsAction = intent.getAction();
7216
7217        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7218                | PackageManager.GET_RESOLVED_FILTER, userId);
7219
7220        if (DEBUG_INTENT_MATCHING) {
7221            Log.v(TAG, "Query " + intent + ": " + results);
7222        }
7223
7224        int specificsPos = 0;
7225        int N;
7226
7227        // todo: note that the algorithm used here is O(N^2).  This
7228        // isn't a problem in our current environment, but if we start running
7229        // into situations where we have more than 5 or 10 matches then this
7230        // should probably be changed to something smarter...
7231
7232        // First we go through and resolve each of the specific items
7233        // that were supplied, taking care of removing any corresponding
7234        // duplicate items in the generic resolve list.
7235        if (specifics != null) {
7236            for (int i=0; i<specifics.length; i++) {
7237                final Intent sintent = specifics[i];
7238                if (sintent == null) {
7239                    continue;
7240                }
7241
7242                if (DEBUG_INTENT_MATCHING) {
7243                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7244                }
7245
7246                String action = sintent.getAction();
7247                if (resultsAction != null && resultsAction.equals(action)) {
7248                    // If this action was explicitly requested, then don't
7249                    // remove things that have it.
7250                    action = null;
7251                }
7252
7253                ResolveInfo ri = null;
7254                ActivityInfo ai = null;
7255
7256                ComponentName comp = sintent.getComponent();
7257                if (comp == null) {
7258                    ri = resolveIntent(
7259                        sintent,
7260                        specificTypes != null ? specificTypes[i] : null,
7261                            flags, userId);
7262                    if (ri == null) {
7263                        continue;
7264                    }
7265                    if (ri == mResolveInfo) {
7266                        // ACK!  Must do something better with this.
7267                    }
7268                    ai = ri.activityInfo;
7269                    comp = new ComponentName(ai.applicationInfo.packageName,
7270                            ai.name);
7271                } else {
7272                    ai = getActivityInfo(comp, flags, userId);
7273                    if (ai == null) {
7274                        continue;
7275                    }
7276                }
7277
7278                // Look for any generic query activities that are duplicates
7279                // of this specific one, and remove them from the results.
7280                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7281                N = results.size();
7282                int j;
7283                for (j=specificsPos; j<N; j++) {
7284                    ResolveInfo sri = results.get(j);
7285                    if ((sri.activityInfo.name.equals(comp.getClassName())
7286                            && sri.activityInfo.applicationInfo.packageName.equals(
7287                                    comp.getPackageName()))
7288                        || (action != null && sri.filter.matchAction(action))) {
7289                        results.remove(j);
7290                        if (DEBUG_INTENT_MATCHING) Log.v(
7291                            TAG, "Removing duplicate item from " + j
7292                            + " due to specific " + specificsPos);
7293                        if (ri == null) {
7294                            ri = sri;
7295                        }
7296                        j--;
7297                        N--;
7298                    }
7299                }
7300
7301                // Add this specific item to its proper place.
7302                if (ri == null) {
7303                    ri = new ResolveInfo();
7304                    ri.activityInfo = ai;
7305                }
7306                results.add(specificsPos, ri);
7307                ri.specificIndex = i;
7308                specificsPos++;
7309            }
7310        }
7311
7312        // Now we go through the remaining generic results and remove any
7313        // duplicate actions that are found here.
7314        N = results.size();
7315        for (int i=specificsPos; i<N-1; i++) {
7316            final ResolveInfo rii = results.get(i);
7317            if (rii.filter == null) {
7318                continue;
7319            }
7320
7321            // Iterate over all of the actions of this result's intent
7322            // filter...  typically this should be just one.
7323            final Iterator<String> it = rii.filter.actionsIterator();
7324            if (it == null) {
7325                continue;
7326            }
7327            while (it.hasNext()) {
7328                final String action = it.next();
7329                if (resultsAction != null && resultsAction.equals(action)) {
7330                    // If this action was explicitly requested, then don't
7331                    // remove things that have it.
7332                    continue;
7333                }
7334                for (int j=i+1; j<N; j++) {
7335                    final ResolveInfo rij = results.get(j);
7336                    if (rij.filter != null && rij.filter.hasAction(action)) {
7337                        results.remove(j);
7338                        if (DEBUG_INTENT_MATCHING) Log.v(
7339                            TAG, "Removing duplicate item from " + j
7340                            + " due to action " + action + " at " + i);
7341                        j--;
7342                        N--;
7343                    }
7344                }
7345            }
7346
7347            // If the caller didn't request filter information, drop it now
7348            // so we don't have to marshall/unmarshall it.
7349            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7350                rii.filter = null;
7351            }
7352        }
7353
7354        // Filter out the caller activity if so requested.
7355        if (caller != null) {
7356            N = results.size();
7357            for (int i=0; i<N; i++) {
7358                ActivityInfo ainfo = results.get(i).activityInfo;
7359                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7360                        && caller.getClassName().equals(ainfo.name)) {
7361                    results.remove(i);
7362                    break;
7363                }
7364            }
7365        }
7366
7367        // If the caller didn't request filter information,
7368        // drop them now so we don't have to
7369        // marshall/unmarshall it.
7370        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7371            N = results.size();
7372            for (int i=0; i<N; i++) {
7373                results.get(i).filter = null;
7374            }
7375        }
7376
7377        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7378        return results;
7379    }
7380
7381    @Override
7382    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7383            String resolvedType, int flags, int userId) {
7384        return new ParceledListSlice<>(
7385                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7386                        false /*allowDynamicSplits*/));
7387    }
7388
7389    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7390            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7391        if (!sUserManager.exists(userId)) return Collections.emptyList();
7392        final int callingUid = Binder.getCallingUid();
7393        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7394                false /*requireFullPermission*/, false /*checkShell*/,
7395                "query intent receivers");
7396        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7397        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7398                false /*includeInstantApps*/);
7399        ComponentName comp = intent.getComponent();
7400        if (comp == null) {
7401            if (intent.getSelector() != null) {
7402                intent = intent.getSelector();
7403                comp = intent.getComponent();
7404            }
7405        }
7406        if (comp != null) {
7407            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7408            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7409            if (ai != null) {
7410                // When specifying an explicit component, we prevent the activity from being
7411                // used when either 1) the calling package is normal and the activity is within
7412                // an instant application or 2) the calling package is ephemeral and the
7413                // activity is not visible to instant applications.
7414                final boolean matchInstantApp =
7415                        (flags & PackageManager.MATCH_INSTANT) != 0;
7416                final boolean matchVisibleToInstantAppOnly =
7417                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7418                final boolean matchExplicitlyVisibleOnly =
7419                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7420                final boolean isCallerInstantApp =
7421                        instantAppPkgName != null;
7422                final boolean isTargetSameInstantApp =
7423                        comp.getPackageName().equals(instantAppPkgName);
7424                final boolean isTargetInstantApp =
7425                        (ai.applicationInfo.privateFlags
7426                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7427                final boolean isTargetVisibleToInstantApp =
7428                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7429                final boolean isTargetExplicitlyVisibleToInstantApp =
7430                        isTargetVisibleToInstantApp
7431                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7432                final boolean isTargetHiddenFromInstantApp =
7433                        !isTargetVisibleToInstantApp
7434                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7435                final boolean blockResolution =
7436                        !isTargetSameInstantApp
7437                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7438                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7439                                        && isTargetHiddenFromInstantApp));
7440                if (!blockResolution) {
7441                    ResolveInfo ri = new ResolveInfo();
7442                    ri.activityInfo = ai;
7443                    list.add(ri);
7444                }
7445            }
7446            return applyPostResolutionFilter(
7447                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7448        }
7449
7450        // reader
7451        synchronized (mPackages) {
7452            String pkgName = intent.getPackage();
7453            if (pkgName == null) {
7454                final List<ResolveInfo> result =
7455                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7456                return applyPostResolutionFilter(
7457                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7458            }
7459            final PackageParser.Package pkg = mPackages.get(pkgName);
7460            if (pkg != null) {
7461                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7462                        intent, resolvedType, flags, pkg.receivers, userId);
7463                return applyPostResolutionFilter(
7464                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7465            }
7466            return Collections.emptyList();
7467        }
7468    }
7469
7470    @Override
7471    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7472        final int callingUid = Binder.getCallingUid();
7473        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7474    }
7475
7476    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7477            int userId, int callingUid) {
7478        if (!sUserManager.exists(userId)) return null;
7479        flags = updateFlagsForResolve(
7480                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7481        List<ResolveInfo> query = queryIntentServicesInternal(
7482                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7483        if (query != null) {
7484            if (query.size() >= 1) {
7485                // If there is more than one service with the same priority,
7486                // just arbitrarily pick the first one.
7487                return query.get(0);
7488            }
7489        }
7490        return null;
7491    }
7492
7493    @Override
7494    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7495            String resolvedType, int flags, int userId) {
7496        final int callingUid = Binder.getCallingUid();
7497        return new ParceledListSlice<>(queryIntentServicesInternal(
7498                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7499    }
7500
7501    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7502            String resolvedType, int flags, int userId, int callingUid,
7503            boolean includeInstantApps) {
7504        if (!sUserManager.exists(userId)) return Collections.emptyList();
7505        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7506                false /*requireFullPermission*/, false /*checkShell*/,
7507                "query intent receivers");
7508        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7509        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7510        ComponentName comp = intent.getComponent();
7511        if (comp == null) {
7512            if (intent.getSelector() != null) {
7513                intent = intent.getSelector();
7514                comp = intent.getComponent();
7515            }
7516        }
7517        if (comp != null) {
7518            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7519            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7520            if (si != null) {
7521                // When specifying an explicit component, we prevent the service from being
7522                // used when either 1) the service is in an instant application and the
7523                // caller is not the same instant application or 2) the calling package is
7524                // ephemeral and the activity is not visible to ephemeral applications.
7525                final boolean matchInstantApp =
7526                        (flags & PackageManager.MATCH_INSTANT) != 0;
7527                final boolean matchVisibleToInstantAppOnly =
7528                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7529                final boolean isCallerInstantApp =
7530                        instantAppPkgName != null;
7531                final boolean isTargetSameInstantApp =
7532                        comp.getPackageName().equals(instantAppPkgName);
7533                final boolean isTargetInstantApp =
7534                        (si.applicationInfo.privateFlags
7535                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7536                final boolean isTargetHiddenFromInstantApp =
7537                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7538                final boolean blockResolution =
7539                        !isTargetSameInstantApp
7540                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7541                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7542                                        && isTargetHiddenFromInstantApp));
7543                if (!blockResolution) {
7544                    final ResolveInfo ri = new ResolveInfo();
7545                    ri.serviceInfo = si;
7546                    list.add(ri);
7547                }
7548            }
7549            return list;
7550        }
7551
7552        // reader
7553        synchronized (mPackages) {
7554            String pkgName = intent.getPackage();
7555            if (pkgName == null) {
7556                return applyPostServiceResolutionFilter(
7557                        mServices.queryIntent(intent, resolvedType, flags, userId),
7558                        instantAppPkgName);
7559            }
7560            final PackageParser.Package pkg = mPackages.get(pkgName);
7561            if (pkg != null) {
7562                return applyPostServiceResolutionFilter(
7563                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7564                                userId),
7565                        instantAppPkgName);
7566            }
7567            return Collections.emptyList();
7568        }
7569    }
7570
7571    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7572            String instantAppPkgName) {
7573        if (instantAppPkgName == null) {
7574            return resolveInfos;
7575        }
7576        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7577            final ResolveInfo info = resolveInfos.get(i);
7578            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7579            // allow services that are defined in the provided package
7580            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7581                if (info.serviceInfo.splitName != null
7582                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7583                                info.serviceInfo.splitName)) {
7584                    // requested service is defined in a split that hasn't been installed yet.
7585                    // add the installer to the resolve list
7586                    if (DEBUG_INSTANT) {
7587                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7588                    }
7589                    final ResolveInfo installerInfo = new ResolveInfo(
7590                            mInstantAppInstallerInfo);
7591                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7592                            null /* installFailureActivity */,
7593                            info.serviceInfo.packageName,
7594                            info.serviceInfo.applicationInfo.versionCode,
7595                            info.serviceInfo.splitName);
7596                    // make sure this resolver is the default
7597                    installerInfo.isDefault = true;
7598                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7599                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7600                    // add a non-generic filter
7601                    installerInfo.filter = new IntentFilter();
7602                    // load resources from the correct package
7603                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7604                    resolveInfos.set(i, installerInfo);
7605                }
7606                continue;
7607            }
7608            // allow services that have been explicitly exposed to ephemeral apps
7609            if (!isEphemeralApp
7610                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7611                continue;
7612            }
7613            resolveInfos.remove(i);
7614        }
7615        return resolveInfos;
7616    }
7617
7618    @Override
7619    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7620            String resolvedType, int flags, int userId) {
7621        return new ParceledListSlice<>(
7622                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7623    }
7624
7625    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7626            Intent intent, String resolvedType, int flags, int userId) {
7627        if (!sUserManager.exists(userId)) return Collections.emptyList();
7628        final int callingUid = Binder.getCallingUid();
7629        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7630        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7631                false /*includeInstantApps*/);
7632        ComponentName comp = intent.getComponent();
7633        if (comp == null) {
7634            if (intent.getSelector() != null) {
7635                intent = intent.getSelector();
7636                comp = intent.getComponent();
7637            }
7638        }
7639        if (comp != null) {
7640            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7641            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7642            if (pi != null) {
7643                // When specifying an explicit component, we prevent the provider from being
7644                // used when either 1) the provider is in an instant application and the
7645                // caller is not the same instant application or 2) the calling package is an
7646                // instant application and the provider is not visible to instant applications.
7647                final boolean matchInstantApp =
7648                        (flags & PackageManager.MATCH_INSTANT) != 0;
7649                final boolean matchVisibleToInstantAppOnly =
7650                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7651                final boolean isCallerInstantApp =
7652                        instantAppPkgName != null;
7653                final boolean isTargetSameInstantApp =
7654                        comp.getPackageName().equals(instantAppPkgName);
7655                final boolean isTargetInstantApp =
7656                        (pi.applicationInfo.privateFlags
7657                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7658                final boolean isTargetHiddenFromInstantApp =
7659                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7660                final boolean blockResolution =
7661                        !isTargetSameInstantApp
7662                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7663                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7664                                        && isTargetHiddenFromInstantApp));
7665                if (!blockResolution) {
7666                    final ResolveInfo ri = new ResolveInfo();
7667                    ri.providerInfo = pi;
7668                    list.add(ri);
7669                }
7670            }
7671            return list;
7672        }
7673
7674        // reader
7675        synchronized (mPackages) {
7676            String pkgName = intent.getPackage();
7677            if (pkgName == null) {
7678                return applyPostContentProviderResolutionFilter(
7679                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7680                        instantAppPkgName);
7681            }
7682            final PackageParser.Package pkg = mPackages.get(pkgName);
7683            if (pkg != null) {
7684                return applyPostContentProviderResolutionFilter(
7685                        mProviders.queryIntentForPackage(
7686                        intent, resolvedType, flags, pkg.providers, userId),
7687                        instantAppPkgName);
7688            }
7689            return Collections.emptyList();
7690        }
7691    }
7692
7693    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7694            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7695        if (instantAppPkgName == null) {
7696            return resolveInfos;
7697        }
7698        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7699            final ResolveInfo info = resolveInfos.get(i);
7700            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7701            // allow providers that are defined in the provided package
7702            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7703                if (info.providerInfo.splitName != null
7704                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7705                                info.providerInfo.splitName)) {
7706                    // requested provider is defined in a split that hasn't been installed yet.
7707                    // add the installer to the resolve list
7708                    if (DEBUG_INSTANT) {
7709                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7710                    }
7711                    final ResolveInfo installerInfo = new ResolveInfo(
7712                            mInstantAppInstallerInfo);
7713                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7714                            null /*failureActivity*/,
7715                            info.providerInfo.packageName,
7716                            info.providerInfo.applicationInfo.versionCode,
7717                            info.providerInfo.splitName);
7718                    // make sure this resolver is the default
7719                    installerInfo.isDefault = true;
7720                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7721                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7722                    // add a non-generic filter
7723                    installerInfo.filter = new IntentFilter();
7724                    // load resources from the correct package
7725                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7726                    resolveInfos.set(i, installerInfo);
7727                }
7728                continue;
7729            }
7730            // allow providers that have been explicitly exposed to instant applications
7731            if (!isEphemeralApp
7732                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7733                continue;
7734            }
7735            resolveInfos.remove(i);
7736        }
7737        return resolveInfos;
7738    }
7739
7740    @Override
7741    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7742        final int callingUid = Binder.getCallingUid();
7743        if (getInstantAppPackageName(callingUid) != null) {
7744            return ParceledListSlice.emptyList();
7745        }
7746        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7747        flags = updateFlagsForPackage(flags, userId, null);
7748        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7749        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7750                true /* requireFullPermission */, false /* checkShell */,
7751                "get installed packages");
7752
7753        // writer
7754        synchronized (mPackages) {
7755            ArrayList<PackageInfo> list;
7756            if (listUninstalled) {
7757                list = new ArrayList<>(mSettings.mPackages.size());
7758                for (PackageSetting ps : mSettings.mPackages.values()) {
7759                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7760                        continue;
7761                    }
7762                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7763                        continue;
7764                    }
7765                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7766                    if (pi != null) {
7767                        list.add(pi);
7768                    }
7769                }
7770            } else {
7771                list = new ArrayList<>(mPackages.size());
7772                for (PackageParser.Package p : mPackages.values()) {
7773                    final PackageSetting ps = (PackageSetting) p.mExtras;
7774                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7775                        continue;
7776                    }
7777                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7778                        continue;
7779                    }
7780                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7781                            p.mExtras, flags, userId);
7782                    if (pi != null) {
7783                        list.add(pi);
7784                    }
7785                }
7786            }
7787
7788            return new ParceledListSlice<>(list);
7789        }
7790    }
7791
7792    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7793            String[] permissions, boolean[] tmp, int flags, int userId) {
7794        int numMatch = 0;
7795        final PermissionsState permissionsState = ps.getPermissionsState();
7796        for (int i=0; i<permissions.length; i++) {
7797            final String permission = permissions[i];
7798            if (permissionsState.hasPermission(permission, userId)) {
7799                tmp[i] = true;
7800                numMatch++;
7801            } else {
7802                tmp[i] = false;
7803            }
7804        }
7805        if (numMatch == 0) {
7806            return;
7807        }
7808        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7809
7810        // The above might return null in cases of uninstalled apps or install-state
7811        // skew across users/profiles.
7812        if (pi != null) {
7813            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7814                if (numMatch == permissions.length) {
7815                    pi.requestedPermissions = permissions;
7816                } else {
7817                    pi.requestedPermissions = new String[numMatch];
7818                    numMatch = 0;
7819                    for (int i=0; i<permissions.length; i++) {
7820                        if (tmp[i]) {
7821                            pi.requestedPermissions[numMatch] = permissions[i];
7822                            numMatch++;
7823                        }
7824                    }
7825                }
7826            }
7827            list.add(pi);
7828        }
7829    }
7830
7831    @Override
7832    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7833            String[] permissions, int flags, int userId) {
7834        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7835        flags = updateFlagsForPackage(flags, userId, permissions);
7836        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7837                true /* requireFullPermission */, false /* checkShell */,
7838                "get packages holding permissions");
7839        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7840
7841        // writer
7842        synchronized (mPackages) {
7843            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7844            boolean[] tmpBools = new boolean[permissions.length];
7845            if (listUninstalled) {
7846                for (PackageSetting ps : mSettings.mPackages.values()) {
7847                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7848                            userId);
7849                }
7850            } else {
7851                for (PackageParser.Package pkg : mPackages.values()) {
7852                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7853                    if (ps != null) {
7854                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7855                                userId);
7856                    }
7857                }
7858            }
7859
7860            return new ParceledListSlice<PackageInfo>(list);
7861        }
7862    }
7863
7864    @Override
7865    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7866        final int callingUid = Binder.getCallingUid();
7867        if (getInstantAppPackageName(callingUid) != null) {
7868            return ParceledListSlice.emptyList();
7869        }
7870        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7871        flags = updateFlagsForApplication(flags, userId, null);
7872        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7873
7874        // writer
7875        synchronized (mPackages) {
7876            ArrayList<ApplicationInfo> list;
7877            if (listUninstalled) {
7878                list = new ArrayList<>(mSettings.mPackages.size());
7879                for (PackageSetting ps : mSettings.mPackages.values()) {
7880                    ApplicationInfo ai;
7881                    int effectiveFlags = flags;
7882                    if (ps.isSystem()) {
7883                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7884                    }
7885                    if (ps.pkg != null) {
7886                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7887                            continue;
7888                        }
7889                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7890                            continue;
7891                        }
7892                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7893                                ps.readUserState(userId), userId);
7894                        if (ai != null) {
7895                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7896                        }
7897                    } else {
7898                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7899                        // and already converts to externally visible package name
7900                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7901                                callingUid, effectiveFlags, userId);
7902                    }
7903                    if (ai != null) {
7904                        list.add(ai);
7905                    }
7906                }
7907            } else {
7908                list = new ArrayList<>(mPackages.size());
7909                for (PackageParser.Package p : mPackages.values()) {
7910                    if (p.mExtras != null) {
7911                        PackageSetting ps = (PackageSetting) p.mExtras;
7912                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7913                            continue;
7914                        }
7915                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7916                            continue;
7917                        }
7918                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7919                                ps.readUserState(userId), userId);
7920                        if (ai != null) {
7921                            ai.packageName = resolveExternalPackageNameLPr(p);
7922                            list.add(ai);
7923                        }
7924                    }
7925                }
7926            }
7927
7928            return new ParceledListSlice<>(list);
7929        }
7930    }
7931
7932    @Override
7933    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7934        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7935            return null;
7936        }
7937        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7938            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7939                    "getEphemeralApplications");
7940        }
7941        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7942                true /* requireFullPermission */, false /* checkShell */,
7943                "getEphemeralApplications");
7944        synchronized (mPackages) {
7945            List<InstantAppInfo> instantApps = mInstantAppRegistry
7946                    .getInstantAppsLPr(userId);
7947            if (instantApps != null) {
7948                return new ParceledListSlice<>(instantApps);
7949            }
7950        }
7951        return null;
7952    }
7953
7954    @Override
7955    public boolean isInstantApp(String packageName, int userId) {
7956        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7957                true /* requireFullPermission */, false /* checkShell */,
7958                "isInstantApp");
7959        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7960            return false;
7961        }
7962
7963        synchronized (mPackages) {
7964            int callingUid = Binder.getCallingUid();
7965            if (Process.isIsolated(callingUid)) {
7966                callingUid = mIsolatedOwners.get(callingUid);
7967            }
7968            final PackageSetting ps = mSettings.mPackages.get(packageName);
7969            PackageParser.Package pkg = mPackages.get(packageName);
7970            final boolean returnAllowed =
7971                    ps != null
7972                    && (isCallerSameApp(packageName, callingUid)
7973                            || canViewInstantApps(callingUid, userId)
7974                            || mInstantAppRegistry.isInstantAccessGranted(
7975                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7976            if (returnAllowed) {
7977                return ps.getInstantApp(userId);
7978            }
7979        }
7980        return false;
7981    }
7982
7983    @Override
7984    public byte[] getInstantAppCookie(String packageName, int userId) {
7985        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7986            return null;
7987        }
7988
7989        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7990                true /* requireFullPermission */, false /* checkShell */,
7991                "getInstantAppCookie");
7992        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7993            return null;
7994        }
7995        synchronized (mPackages) {
7996            return mInstantAppRegistry.getInstantAppCookieLPw(
7997                    packageName, userId);
7998        }
7999    }
8000
8001    @Override
8002    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8003        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8004            return true;
8005        }
8006
8007        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8008                true /* requireFullPermission */, true /* checkShell */,
8009                "setInstantAppCookie");
8010        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8011            return false;
8012        }
8013        synchronized (mPackages) {
8014            return mInstantAppRegistry.setInstantAppCookieLPw(
8015                    packageName, cookie, userId);
8016        }
8017    }
8018
8019    @Override
8020    public Bitmap getInstantAppIcon(String packageName, int userId) {
8021        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8022            return null;
8023        }
8024
8025        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8026            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8027                    "getInstantAppIcon");
8028        }
8029        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8030                true /* requireFullPermission */, false /* checkShell */,
8031                "getInstantAppIcon");
8032
8033        synchronized (mPackages) {
8034            return mInstantAppRegistry.getInstantAppIconLPw(
8035                    packageName, userId);
8036        }
8037    }
8038
8039    private boolean isCallerSameApp(String packageName, int uid) {
8040        PackageParser.Package pkg = mPackages.get(packageName);
8041        return pkg != null
8042                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8043    }
8044
8045    @Override
8046    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8047        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8048            return ParceledListSlice.emptyList();
8049        }
8050        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8051    }
8052
8053    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8054        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8055
8056        // reader
8057        synchronized (mPackages) {
8058            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8059            final int userId = UserHandle.getCallingUserId();
8060            while (i.hasNext()) {
8061                final PackageParser.Package p = i.next();
8062                if (p.applicationInfo == null) continue;
8063
8064                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8065                        && !p.applicationInfo.isDirectBootAware();
8066                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8067                        && p.applicationInfo.isDirectBootAware();
8068
8069                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8070                        && (!mSafeMode || isSystemApp(p))
8071                        && (matchesUnaware || matchesAware)) {
8072                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8073                    if (ps != null) {
8074                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8075                                ps.readUserState(userId), userId);
8076                        if (ai != null) {
8077                            finalList.add(ai);
8078                        }
8079                    }
8080                }
8081            }
8082        }
8083
8084        return finalList;
8085    }
8086
8087    @Override
8088    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8089        return resolveContentProviderInternal(name, flags, userId);
8090    }
8091
8092    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8093        if (!sUserManager.exists(userId)) return null;
8094        flags = updateFlagsForComponent(flags, userId, name);
8095        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8096        // reader
8097        synchronized (mPackages) {
8098            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8099            PackageSetting ps = provider != null
8100                    ? mSettings.mPackages.get(provider.owner.packageName)
8101                    : null;
8102            if (ps != null) {
8103                final boolean isInstantApp = ps.getInstantApp(userId);
8104                // normal application; filter out instant application provider
8105                if (instantAppPkgName == null && isInstantApp) {
8106                    return null;
8107                }
8108                // instant application; filter out other instant applications
8109                if (instantAppPkgName != null
8110                        && isInstantApp
8111                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8112                    return null;
8113                }
8114                // instant application; filter out non-exposed provider
8115                if (instantAppPkgName != null
8116                        && !isInstantApp
8117                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8118                    return null;
8119                }
8120                // provider not enabled
8121                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8122                    return null;
8123                }
8124                return PackageParser.generateProviderInfo(
8125                        provider, flags, ps.readUserState(userId), userId);
8126            }
8127            return null;
8128        }
8129    }
8130
8131    /**
8132     * @deprecated
8133     */
8134    @Deprecated
8135    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8136        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8137            return;
8138        }
8139        // reader
8140        synchronized (mPackages) {
8141            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8142                    .entrySet().iterator();
8143            final int userId = UserHandle.getCallingUserId();
8144            while (i.hasNext()) {
8145                Map.Entry<String, PackageParser.Provider> entry = i.next();
8146                PackageParser.Provider p = entry.getValue();
8147                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8148
8149                if (ps != null && p.syncable
8150                        && (!mSafeMode || (p.info.applicationInfo.flags
8151                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8152                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8153                            ps.readUserState(userId), userId);
8154                    if (info != null) {
8155                        outNames.add(entry.getKey());
8156                        outInfo.add(info);
8157                    }
8158                }
8159            }
8160        }
8161    }
8162
8163    @Override
8164    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8165            int uid, int flags, String metaDataKey) {
8166        final int callingUid = Binder.getCallingUid();
8167        final int userId = processName != null ? UserHandle.getUserId(uid)
8168                : UserHandle.getCallingUserId();
8169        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8170        flags = updateFlagsForComponent(flags, userId, processName);
8171        ArrayList<ProviderInfo> finalList = null;
8172        // reader
8173        synchronized (mPackages) {
8174            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8175            while (i.hasNext()) {
8176                final PackageParser.Provider p = i.next();
8177                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8178                if (ps != null && p.info.authority != null
8179                        && (processName == null
8180                                || (p.info.processName.equals(processName)
8181                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8182                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8183
8184                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8185                    // parameter.
8186                    if (metaDataKey != null
8187                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8188                        continue;
8189                    }
8190                    final ComponentName component =
8191                            new ComponentName(p.info.packageName, p.info.name);
8192                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8193                        continue;
8194                    }
8195                    if (finalList == null) {
8196                        finalList = new ArrayList<ProviderInfo>(3);
8197                    }
8198                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8199                            ps.readUserState(userId), userId);
8200                    if (info != null) {
8201                        finalList.add(info);
8202                    }
8203                }
8204            }
8205        }
8206
8207        if (finalList != null) {
8208            Collections.sort(finalList, mProviderInitOrderSorter);
8209            return new ParceledListSlice<ProviderInfo>(finalList);
8210        }
8211
8212        return ParceledListSlice.emptyList();
8213    }
8214
8215    @Override
8216    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8217        // reader
8218        synchronized (mPackages) {
8219            final int callingUid = Binder.getCallingUid();
8220            final int callingUserId = UserHandle.getUserId(callingUid);
8221            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8222            if (ps == null) return null;
8223            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8224                return null;
8225            }
8226            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8227            return PackageParser.generateInstrumentationInfo(i, flags);
8228        }
8229    }
8230
8231    @Override
8232    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8233            String targetPackage, int flags) {
8234        final int callingUid = Binder.getCallingUid();
8235        final int callingUserId = UserHandle.getUserId(callingUid);
8236        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8237        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8238            return ParceledListSlice.emptyList();
8239        }
8240        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8241    }
8242
8243    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8244            int flags) {
8245        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8246
8247        // reader
8248        synchronized (mPackages) {
8249            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8250            while (i.hasNext()) {
8251                final PackageParser.Instrumentation p = i.next();
8252                if (targetPackage == null
8253                        || targetPackage.equals(p.info.targetPackage)) {
8254                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8255                            flags);
8256                    if (ii != null) {
8257                        finalList.add(ii);
8258                    }
8259                }
8260            }
8261        }
8262
8263        return finalList;
8264    }
8265
8266    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8267        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8268        try {
8269            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8270        } finally {
8271            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8272        }
8273    }
8274
8275    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8276        final File[] files = scanDir.listFiles();
8277        if (ArrayUtils.isEmpty(files)) {
8278            Log.d(TAG, "No files in app dir " + scanDir);
8279            return;
8280        }
8281
8282        if (DEBUG_PACKAGE_SCANNING) {
8283            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8284                    + " flags=0x" + Integer.toHexString(parseFlags));
8285        }
8286        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8287                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8288                mParallelPackageParserCallback)) {
8289            // Submit files for parsing in parallel
8290            int fileCount = 0;
8291            for (File file : files) {
8292                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8293                        && !PackageInstallerService.isStageName(file.getName());
8294                if (!isPackage) {
8295                    // Ignore entries which are not packages
8296                    continue;
8297                }
8298                parallelPackageParser.submit(file, parseFlags);
8299                fileCount++;
8300            }
8301
8302            // Process results one by one
8303            for (; fileCount > 0; fileCount--) {
8304                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8305                Throwable throwable = parseResult.throwable;
8306                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8307
8308                if (throwable == null) {
8309                    // TODO(toddke): move lower in the scan chain
8310                    // Static shared libraries have synthetic package names
8311                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8312                        renameStaticSharedLibraryPackage(parseResult.pkg);
8313                    }
8314                    try {
8315                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8316                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8317                                    currentTime, null);
8318                        }
8319                    } catch (PackageManagerException e) {
8320                        errorCode = e.error;
8321                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8322                    }
8323                } else if (throwable instanceof PackageParser.PackageParserException) {
8324                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8325                            throwable;
8326                    errorCode = e.error;
8327                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8328                } else {
8329                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8330                            + parseResult.scanFile, throwable);
8331                }
8332
8333                // Delete invalid userdata apps
8334                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8335                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8336                    logCriticalInfo(Log.WARN,
8337                            "Deleting invalid package at " + parseResult.scanFile);
8338                    removeCodePathLI(parseResult.scanFile);
8339                }
8340            }
8341        }
8342    }
8343
8344    public static void reportSettingsProblem(int priority, String msg) {
8345        logCriticalInfo(priority, msg);
8346    }
8347
8348    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8349            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8350        // When upgrading from pre-N MR1, verify the package time stamp using the package
8351        // directory and not the APK file.
8352        final long lastModifiedTime = mIsPreNMR1Upgrade
8353                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8354        if (ps != null && !forceCollect
8355                && ps.codePathString.equals(pkg.codePath)
8356                && ps.timeStamp == lastModifiedTime
8357                && !isCompatSignatureUpdateNeeded(pkg)
8358                && !isRecoverSignatureUpdateNeeded(pkg)) {
8359            if (ps.signatures.mSigningDetails.signatures != null
8360                    && ps.signatures.mSigningDetails.signatures.length != 0
8361                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8362                            != SignatureSchemeVersion.UNKNOWN) {
8363                // Optimization: reuse the existing cached signing data
8364                // if the package appears to be unchanged.
8365                pkg.mSigningDetails =
8366                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8367                return;
8368            }
8369
8370            Slog.w(TAG, "PackageSetting for " + ps.name
8371                    + " is missing signatures.  Collecting certs again to recover them.");
8372        } else {
8373            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8374                    (forceCollect ? " (forced)" : ""));
8375        }
8376
8377        try {
8378            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8379            PackageParser.collectCertificates(pkg, skipVerify);
8380        } catch (PackageParserException e) {
8381            throw PackageManagerException.from(e);
8382        } finally {
8383            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8384        }
8385    }
8386
8387    /**
8388     *  Traces a package scan.
8389     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8390     */
8391    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8392            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8393        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8394        try {
8395            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8396        } finally {
8397            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8398        }
8399    }
8400
8401    /**
8402     *  Scans a package and returns the newly parsed package.
8403     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8404     */
8405    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8406            long currentTime, UserHandle user) throws PackageManagerException {
8407        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8408        PackageParser pp = new PackageParser();
8409        pp.setSeparateProcesses(mSeparateProcesses);
8410        pp.setOnlyCoreApps(mOnlyCore);
8411        pp.setDisplayMetrics(mMetrics);
8412        pp.setCallback(mPackageParserCallback);
8413
8414        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8415        final PackageParser.Package pkg;
8416        try {
8417            pkg = pp.parsePackage(scanFile, parseFlags);
8418        } catch (PackageParserException e) {
8419            throw PackageManagerException.from(e);
8420        } finally {
8421            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8422        }
8423
8424        // Static shared libraries have synthetic package names
8425        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8426            renameStaticSharedLibraryPackage(pkg);
8427        }
8428
8429        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8430    }
8431
8432    /**
8433     *  Scans a package and returns the newly parsed package.
8434     *  @throws PackageManagerException on a parse error.
8435     */
8436    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8437            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8438            @Nullable UserHandle user)
8439                    throws PackageManagerException {
8440        // If the package has children and this is the first dive in the function
8441        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8442        // packages (parent and children) would be successfully scanned before the
8443        // actual scan since scanning mutates internal state and we want to atomically
8444        // install the package and its children.
8445        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8446            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8447                scanFlags |= SCAN_CHECK_ONLY;
8448            }
8449        } else {
8450            scanFlags &= ~SCAN_CHECK_ONLY;
8451        }
8452
8453        // Scan the parent
8454        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8455                scanFlags, currentTime, user);
8456
8457        // Scan the children
8458        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8459        for (int i = 0; i < childCount; i++) {
8460            PackageParser.Package childPackage = pkg.childPackages.get(i);
8461            addForInitLI(childPackage, parseFlags, scanFlags,
8462                    currentTime, user);
8463        }
8464
8465
8466        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8467            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8468        }
8469
8470        return scannedPkg;
8471    }
8472
8473    /**
8474     * Returns if full apk verification can be skipped for the whole package, including the splits.
8475     */
8476    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8477        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8478            return false;
8479        }
8480        // TODO: Allow base and splits to be verified individually.
8481        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8482            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8483                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8484                    return false;
8485                }
8486            }
8487        }
8488        return true;
8489    }
8490
8491    /**
8492     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8493     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8494     * match one in a trusted source, and should be done separately.
8495     */
8496    private boolean canSkipFullApkVerification(String apkPath) {
8497        byte[] rootHashObserved = null;
8498        try {
8499            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8500            if (rootHashObserved == null) {
8501                return false;  // APK does not contain Merkle tree root hash.
8502            }
8503            synchronized (mInstallLock) {
8504                // Returns whether the observed root hash matches what kernel has.
8505                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8506                return true;
8507            }
8508        } catch (InstallerException | IOException | DigestException |
8509                NoSuchAlgorithmException e) {
8510            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8511        }
8512        return false;
8513    }
8514
8515    // Temporary to catch potential issues with refactoring
8516    private static boolean REFACTOR_DEBUG = true;
8517    /**
8518     * Adds a new package to the internal data structures during platform initialization.
8519     * <p>After adding, the package is known to the system and available for querying.
8520     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8521     * etc...], additional checks are performed. Basic verification [such as ensuring
8522     * matching signatures, checking version codes, etc...] occurs if the package is
8523     * identical to a previously known package. If the package fails a signature check,
8524     * the version installed on /data will be removed. If the version of the new package
8525     * is less than or equal than the version on /data, it will be ignored.
8526     * <p>Regardless of the package location, the results are applied to the internal
8527     * structures and the package is made available to the rest of the system.
8528     * <p>NOTE: The return value should be removed. It's the passed in package object.
8529     */
8530    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8531            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8532            @Nullable UserHandle user)
8533                    throws PackageManagerException {
8534        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8535        final String renamedPkgName;
8536        final PackageSetting disabledPkgSetting;
8537        final boolean isSystemPkgUpdated;
8538        final boolean pkgAlreadyExists;
8539        PackageSetting pkgSetting;
8540
8541        // NOTE: installPackageLI() has the same code to setup the package's
8542        // application info. This probably should be done lower in the call
8543        // stack [such as scanPackageOnly()]. However, we verify the application
8544        // info prior to that [in scanPackageNew()] and thus have to setup
8545        // the application info early.
8546        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8547        pkg.setApplicationInfoCodePath(pkg.codePath);
8548        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8549        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8550        pkg.setApplicationInfoResourcePath(pkg.codePath);
8551        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8552        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8553
8554        synchronized (mPackages) {
8555            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8556            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8557if (REFACTOR_DEBUG) {
8558Slog.e("TODD",
8559        "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName));
8560}
8561            if (realPkgName != null) {
8562                ensurePackageRenamed(pkg, renamedPkgName);
8563            }
8564            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8565            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8566            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8567            pkgAlreadyExists = pkgSetting != null;
8568            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8569            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8570            isSystemPkgUpdated = disabledPkgSetting != null;
8571
8572            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8573                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8574            }
8575if (REFACTOR_DEBUG) {
8576Slog.e("TODD",
8577        "SSP? " + scanSystemPartition
8578        + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"")
8579        + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():""));
8580}
8581
8582            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8583                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8584                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8585                    : null;
8586            if (DEBUG_PACKAGE_SCANNING
8587                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8588                    && sharedUserSetting != null) {
8589                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8590                        + " (uid=" + sharedUserSetting.userId + "):"
8591                        + " packages=" + sharedUserSetting.packages);
8592if (REFACTOR_DEBUG) {
8593Slog.e("TODD",
8594        "Shared UserID " + pkg.mSharedUserId
8595        + " (uid=" + sharedUserSetting.userId + "):"
8596        + " packages=" + sharedUserSetting.packages);
8597}
8598            }
8599
8600            if (scanSystemPartition) {
8601                // Potentially prune child packages. If the application on the /system
8602                // partition has been updated via OTA, but, is still disabled by a
8603                // version on /data, cycle through all of its children packages and
8604                // remove children that are no longer defined.
8605                if (isSystemPkgUpdated) {
8606if (REFACTOR_DEBUG) {
8607Slog.e("TODD",
8608        "Disable child packages");
8609}
8610                    final int scannedChildCount = (pkg.childPackages != null)
8611                            ? pkg.childPackages.size() : 0;
8612                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8613                            ? disabledPkgSetting.childPackageNames.size() : 0;
8614                    for (int i = 0; i < disabledChildCount; i++) {
8615                        String disabledChildPackageName =
8616                                disabledPkgSetting.childPackageNames.get(i);
8617                        boolean disabledPackageAvailable = false;
8618                        for (int j = 0; j < scannedChildCount; j++) {
8619                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8620                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8621if (REFACTOR_DEBUG) {
8622Slog.e("TODD",
8623        "Ignore " + disabledChildPackageName);
8624}
8625                                disabledPackageAvailable = true;
8626                                break;
8627                            }
8628                        }
8629                        if (!disabledPackageAvailable) {
8630if (REFACTOR_DEBUG) {
8631Slog.e("TODD",
8632        "Disable " + disabledChildPackageName);
8633}
8634                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8635                        }
8636                    }
8637                    // we're updating the disabled package, so, scan it as the package setting
8638                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8639                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8640                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8641                            (pkg == mPlatformPackage), user);
8642if (REFACTOR_DEBUG) {
8643Slog.e("TODD",
8644        "Scan disabled system package");
8645Slog.e("TODD",
8646        "Pre: " + request.pkgSetting.dumpState_temp());
8647}
8648final ScanResult result =
8649                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8650if (REFACTOR_DEBUG) {
8651Slog.e("TODD",
8652        "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan"));
8653}
8654                }
8655            }
8656        }
8657
8658        final boolean newPkgChangedPaths =
8659                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8660if (REFACTOR_DEBUG) {
8661Slog.e("TODD",
8662        "paths changed? " + newPkgChangedPaths
8663        + "; old: " + pkg.codePath
8664        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString));
8665}
8666        final boolean newPkgVersionGreater =
8667                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8668if (REFACTOR_DEBUG) {
8669Slog.e("TODD",
8670        "version greater? " + newPkgVersionGreater
8671        + "; old: " + pkg.getLongVersionCode()
8672        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode));
8673}
8674        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8675                && newPkgChangedPaths && newPkgVersionGreater;
8676if (REFACTOR_DEBUG) {
8677    Slog.e("TODD",
8678            "system better? " + isSystemPkgBetter);
8679}
8680        if (isSystemPkgBetter) {
8681            // The version of the application on /system is greater than the version on
8682            // /data. Switch back to the application on /system.
8683            // It's safe to assume the application on /system will correctly scan. If not,
8684            // there won't be a working copy of the application.
8685            synchronized (mPackages) {
8686                // just remove the loaded entries from package lists
8687                mPackages.remove(pkgSetting.name);
8688            }
8689
8690            logCriticalInfo(Log.WARN,
8691                    "System package updated;"
8692                    + " name: " + pkgSetting.name
8693                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8694                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8695if (REFACTOR_DEBUG) {
8696Slog.e("TODD",
8697        "System package changed;"
8698        + " name: " + pkgSetting.name
8699        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8700        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8701}
8702
8703            final InstallArgs args = createInstallArgsForExisting(
8704                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8705                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8706            args.cleanUpResourcesLI();
8707            synchronized (mPackages) {
8708                mSettings.enableSystemPackageLPw(pkgSetting.name);
8709            }
8710        }
8711
8712        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8713if (REFACTOR_DEBUG) {
8714Slog.e("TODD",
8715        "THROW exception; system pkg version not good enough");
8716}
8717            // The version of the application on the /system partition is less than or
8718            // equal to the version on the /data partition. Throw an exception and use
8719            // the application already installed on the /data partition.
8720            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8721                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8722                    + " better than this " + pkg.getLongVersionCode());
8723        }
8724
8725        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8726        // force re-collecting certificate.
8727        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8728                disabledPkgSetting);
8729        // Full APK verification can be skipped during certificate collection, only if the file is
8730        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8731        // cases, only data in Signing Block is verified instead of the whole file.
8732        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8733                (forceCollect && canSkipFullPackageVerification(pkg));
8734        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8735
8736        boolean shouldHideSystemApp = false;
8737        // A new application appeared on /system, but, we already have a copy of
8738        // the application installed on /data.
8739        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8740                && !pkgSetting.isSystem()) {
8741
8742            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8743                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8744                logCriticalInfo(Log.WARN,
8745                        "System package signature mismatch;"
8746                        + " name: " + pkgSetting.name);
8747if (REFACTOR_DEBUG) {
8748Slog.e("TODD",
8749        "System package signature mismatch;"
8750        + " name: " + pkgSetting.name);
8751}
8752                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8753                        "scanPackageInternalLI")) {
8754                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8755                }
8756                pkgSetting = null;
8757            } else if (newPkgVersionGreater) {
8758                // The application on /system is newer than the application on /data.
8759                // Simply remove the application on /data [keeping application data]
8760                // and replace it with the version on /system.
8761                logCriticalInfo(Log.WARN,
8762                        "System package enabled;"
8763                        + " name: " + pkgSetting.name
8764                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8765                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8766if (REFACTOR_DEBUG) {
8767Slog.e("TODD",
8768        "System package enabled;"
8769        + " name: " + pkgSetting.name
8770        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8771        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8772}
8773                InstallArgs args = createInstallArgsForExisting(
8774                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8775                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8776                synchronized (mInstallLock) {
8777                    args.cleanUpResourcesLI();
8778                }
8779            } else {
8780                // The application on /system is older than the application on /data. Hide
8781                // the application on /system and the version on /data will be scanned later
8782                // and re-added like an update.
8783                shouldHideSystemApp = true;
8784                logCriticalInfo(Log.INFO,
8785                        "System package disabled;"
8786                        + " name: " + pkgSetting.name
8787                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8788                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8789if (REFACTOR_DEBUG) {
8790Slog.e("TODD",
8791        "System package disabled;"
8792        + " name: " + pkgSetting.name
8793        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8794        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8795}
8796            }
8797        }
8798
8799if (REFACTOR_DEBUG) {
8800Slog.e("TODD",
8801        "Scan package");
8802Slog.e("TODD",
8803        "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8804}
8805        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8806                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8807if (REFACTOR_DEBUG) {
8808pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8809Slog.e("TODD",
8810        "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8811}
8812
8813        if (shouldHideSystemApp) {
8814if (REFACTOR_DEBUG) {
8815Slog.e("TODD",
8816        "Disable package: " + pkg.packageName);
8817}
8818            synchronized (mPackages) {
8819                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8820            }
8821        }
8822        return scannedPkg;
8823    }
8824
8825    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8826        // Derive the new package synthetic package name
8827        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8828                + pkg.staticSharedLibVersion);
8829    }
8830
8831    private static String fixProcessName(String defProcessName,
8832            String processName) {
8833        if (processName == null) {
8834            return defProcessName;
8835        }
8836        return processName;
8837    }
8838
8839    /**
8840     * Enforces that only the system UID or root's UID can call a method exposed
8841     * via Binder.
8842     *
8843     * @param message used as message if SecurityException is thrown
8844     * @throws SecurityException if the caller is not system or root
8845     */
8846    private static final void enforceSystemOrRoot(String message) {
8847        final int uid = Binder.getCallingUid();
8848        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8849            throw new SecurityException(message);
8850        }
8851    }
8852
8853    @Override
8854    public void performFstrimIfNeeded() {
8855        enforceSystemOrRoot("Only the system can request fstrim");
8856
8857        // Before everything else, see whether we need to fstrim.
8858        try {
8859            IStorageManager sm = PackageHelper.getStorageManager();
8860            if (sm != null) {
8861                boolean doTrim = false;
8862                final long interval = android.provider.Settings.Global.getLong(
8863                        mContext.getContentResolver(),
8864                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8865                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8866                if (interval > 0) {
8867                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8868                    if (timeSinceLast > interval) {
8869                        doTrim = true;
8870                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8871                                + "; running immediately");
8872                    }
8873                }
8874                if (doTrim) {
8875                    final boolean dexOptDialogShown;
8876                    synchronized (mPackages) {
8877                        dexOptDialogShown = mDexOptDialogShown;
8878                    }
8879                    if (!isFirstBoot() && dexOptDialogShown) {
8880                        try {
8881                            ActivityManager.getService().showBootMessage(
8882                                    mContext.getResources().getString(
8883                                            R.string.android_upgrading_fstrim), true);
8884                        } catch (RemoteException e) {
8885                        }
8886                    }
8887                    sm.runMaintenance();
8888                }
8889            } else {
8890                Slog.e(TAG, "storageManager service unavailable!");
8891            }
8892        } catch (RemoteException e) {
8893            // Can't happen; StorageManagerService is local
8894        }
8895    }
8896
8897    @Override
8898    public void updatePackagesIfNeeded() {
8899        enforceSystemOrRoot("Only the system can request package update");
8900
8901        // We need to re-extract after an OTA.
8902        boolean causeUpgrade = isUpgrade();
8903
8904        // First boot or factory reset.
8905        // Note: we also handle devices that are upgrading to N right now as if it is their
8906        //       first boot, as they do not have profile data.
8907        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8908
8909        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8910        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8911
8912        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8913            return;
8914        }
8915
8916        List<PackageParser.Package> pkgs;
8917        synchronized (mPackages) {
8918            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8919        }
8920
8921        final long startTime = System.nanoTime();
8922        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8923                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8924                    false /* bootComplete */);
8925
8926        final int elapsedTimeSeconds =
8927                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8928
8929        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8930        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8931        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8932        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8933        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8934    }
8935
8936    /*
8937     * Return the prebuilt profile path given a package base code path.
8938     */
8939    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8940        return pkg.baseCodePath + ".prof";
8941    }
8942
8943    /**
8944     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8945     * containing statistics about the invocation. The array consists of three elements,
8946     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8947     * and {@code numberOfPackagesFailed}.
8948     */
8949    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8950            final String compilerFilter, boolean bootComplete) {
8951
8952        int numberOfPackagesVisited = 0;
8953        int numberOfPackagesOptimized = 0;
8954        int numberOfPackagesSkipped = 0;
8955        int numberOfPackagesFailed = 0;
8956        final int numberOfPackagesToDexopt = pkgs.size();
8957
8958        for (PackageParser.Package pkg : pkgs) {
8959            numberOfPackagesVisited++;
8960
8961            boolean useProfileForDexopt = false;
8962
8963            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8964                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8965                // that are already compiled.
8966                File profileFile = new File(getPrebuildProfilePath(pkg));
8967                // Copy profile if it exists.
8968                if (profileFile.exists()) {
8969                    try {
8970                        // We could also do this lazily before calling dexopt in
8971                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8972                        // is that we don't have a good way to say "do this only once".
8973                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8974                                pkg.applicationInfo.uid, pkg.packageName,
8975                                ArtManager.getProfileName(null))) {
8976                            Log.e(TAG, "Installer failed to copy system profile!");
8977                        } else {
8978                            // Disabled as this causes speed-profile compilation during first boot
8979                            // even if things are already compiled.
8980                            // useProfileForDexopt = true;
8981                        }
8982                    } catch (Exception e) {
8983                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8984                                e);
8985                    }
8986                } else {
8987                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8988                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8989                    // minimize the number off apps being speed-profile compiled during first boot.
8990                    // The other paths will not change the filter.
8991                    if (disabledPs != null && disabledPs.pkg.isStub) {
8992                        // The package is the stub one, remove the stub suffix to get the normal
8993                        // package and APK names.
8994                        String systemProfilePath =
8995                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8996                        profileFile = new File(systemProfilePath);
8997                        // If we have a profile for a compressed APK, copy it to the reference
8998                        // location.
8999                        // Note that copying the profile here will cause it to override the
9000                        // reference profile every OTA even though the existing reference profile
9001                        // may have more data. We can't copy during decompression since the
9002                        // directories are not set up at that point.
9003                        if (profileFile.exists()) {
9004                            try {
9005                                // We could also do this lazily before calling dexopt in
9006                                // PackageDexOptimizer to prevent this happening on first boot. The
9007                                // issue is that we don't have a good way to say "do this only
9008                                // once".
9009                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9010                                        pkg.applicationInfo.uid, pkg.packageName,
9011                                        ArtManager.getProfileName(null))) {
9012                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9013                                } else {
9014                                    useProfileForDexopt = true;
9015                                }
9016                            } catch (Exception e) {
9017                                Log.e(TAG, "Failed to copy profile " +
9018                                        profileFile.getAbsolutePath() + " ", e);
9019                            }
9020                        }
9021                    }
9022                }
9023            }
9024
9025            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9026                if (DEBUG_DEXOPT) {
9027                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9028                }
9029                numberOfPackagesSkipped++;
9030                continue;
9031            }
9032
9033            if (DEBUG_DEXOPT) {
9034                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9035                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9036            }
9037
9038            if (showDialog) {
9039                try {
9040                    ActivityManager.getService().showBootMessage(
9041                            mContext.getResources().getString(R.string.android_upgrading_apk,
9042                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9043                } catch (RemoteException e) {
9044                }
9045                synchronized (mPackages) {
9046                    mDexOptDialogShown = true;
9047                }
9048            }
9049
9050            String pkgCompilerFilter = compilerFilter;
9051            if (useProfileForDexopt) {
9052                // Use background dexopt mode to try and use the profile. Note that this does not
9053                // guarantee usage of the profile.
9054                pkgCompilerFilter =
9055                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9056                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9057            }
9058
9059            // checkProfiles is false to avoid merging profiles during boot which
9060            // might interfere with background compilation (b/28612421).
9061            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9062            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9063            // trade-off worth doing to save boot time work.
9064            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9065            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9066                    pkg.packageName,
9067                    pkgCompilerFilter,
9068                    dexoptFlags));
9069
9070            switch (primaryDexOptStaus) {
9071                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9072                    numberOfPackagesOptimized++;
9073                    break;
9074                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9075                    numberOfPackagesSkipped++;
9076                    break;
9077                case PackageDexOptimizer.DEX_OPT_FAILED:
9078                    numberOfPackagesFailed++;
9079                    break;
9080                default:
9081                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9082                    break;
9083            }
9084        }
9085
9086        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9087                numberOfPackagesFailed };
9088    }
9089
9090    @Override
9091    public void notifyPackageUse(String packageName, int reason) {
9092        synchronized (mPackages) {
9093            final int callingUid = Binder.getCallingUid();
9094            final int callingUserId = UserHandle.getUserId(callingUid);
9095            if (getInstantAppPackageName(callingUid) != null) {
9096                if (!isCallerSameApp(packageName, callingUid)) {
9097                    return;
9098                }
9099            } else {
9100                if (isInstantApp(packageName, callingUserId)) {
9101                    return;
9102                }
9103            }
9104            notifyPackageUseLocked(packageName, reason);
9105        }
9106    }
9107
9108    private void notifyPackageUseLocked(String packageName, int reason) {
9109        final PackageParser.Package p = mPackages.get(packageName);
9110        if (p == null) {
9111            return;
9112        }
9113        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9114    }
9115
9116    @Override
9117    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9118            List<String> classPaths, String loaderIsa) {
9119        int userId = UserHandle.getCallingUserId();
9120        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9121        if (ai == null) {
9122            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9123                + loadingPackageName + ", user=" + userId);
9124            return;
9125        }
9126        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9127    }
9128
9129    @Override
9130    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9131            IDexModuleRegisterCallback callback) {
9132        int userId = UserHandle.getCallingUserId();
9133        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9134        DexManager.RegisterDexModuleResult result;
9135        if (ai == null) {
9136            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9137                     " calling user. package=" + packageName + ", user=" + userId);
9138            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9139        } else {
9140            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9141        }
9142
9143        if (callback != null) {
9144            mHandler.post(() -> {
9145                try {
9146                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9147                } catch (RemoteException e) {
9148                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9149                }
9150            });
9151        }
9152    }
9153
9154    /**
9155     * Ask the package manager to perform a dex-opt with the given compiler filter.
9156     *
9157     * Note: exposed only for the shell command to allow moving packages explicitly to a
9158     *       definite state.
9159     */
9160    @Override
9161    public boolean performDexOptMode(String packageName,
9162            boolean checkProfiles, String targetCompilerFilter, boolean force,
9163            boolean bootComplete, String splitName) {
9164        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9165                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9166                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9167        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9168                splitName, flags));
9169    }
9170
9171    /**
9172     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9173     * secondary dex files belonging to the given package.
9174     *
9175     * Note: exposed only for the shell command to allow moving packages explicitly to a
9176     *       definite state.
9177     */
9178    @Override
9179    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9180            boolean force) {
9181        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9182                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9183                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9184                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9185        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9186    }
9187
9188    /*package*/ boolean performDexOpt(DexoptOptions options) {
9189        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9190            return false;
9191        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9192            return false;
9193        }
9194
9195        if (options.isDexoptOnlySecondaryDex()) {
9196            return mDexManager.dexoptSecondaryDex(options);
9197        } else {
9198            int dexoptStatus = performDexOptWithStatus(options);
9199            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9200        }
9201    }
9202
9203    /**
9204     * Perform dexopt on the given package and return one of following result:
9205     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9206     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9207     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9208     */
9209    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9210        return performDexOptTraced(options);
9211    }
9212
9213    private int performDexOptTraced(DexoptOptions options) {
9214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9215        try {
9216            return performDexOptInternal(options);
9217        } finally {
9218            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9219        }
9220    }
9221
9222    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9223    // if the package can now be considered up to date for the given filter.
9224    private int performDexOptInternal(DexoptOptions options) {
9225        PackageParser.Package p;
9226        synchronized (mPackages) {
9227            p = mPackages.get(options.getPackageName());
9228            if (p == null) {
9229                // Package could not be found. Report failure.
9230                return PackageDexOptimizer.DEX_OPT_FAILED;
9231            }
9232            mPackageUsage.maybeWriteAsync(mPackages);
9233            mCompilerStats.maybeWriteAsync();
9234        }
9235        long callingId = Binder.clearCallingIdentity();
9236        try {
9237            synchronized (mInstallLock) {
9238                return performDexOptInternalWithDependenciesLI(p, options);
9239            }
9240        } finally {
9241            Binder.restoreCallingIdentity(callingId);
9242        }
9243    }
9244
9245    public ArraySet<String> getOptimizablePackages() {
9246        ArraySet<String> pkgs = new ArraySet<String>();
9247        synchronized (mPackages) {
9248            for (PackageParser.Package p : mPackages.values()) {
9249                if (PackageDexOptimizer.canOptimizePackage(p)) {
9250                    pkgs.add(p.packageName);
9251                }
9252            }
9253        }
9254        return pkgs;
9255    }
9256
9257    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9258            DexoptOptions options) {
9259        // Select the dex optimizer based on the force parameter.
9260        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9261        //       allocate an object here.
9262        PackageDexOptimizer pdo = options.isForce()
9263                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9264                : mPackageDexOptimizer;
9265
9266        // Dexopt all dependencies first. Note: we ignore the return value and march on
9267        // on errors.
9268        // Note that we are going to call performDexOpt on those libraries as many times as
9269        // they are referenced in packages. When we do a batch of performDexOpt (for example
9270        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9271        // and the first package that uses the library will dexopt it. The
9272        // others will see that the compiled code for the library is up to date.
9273        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9274        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9275        if (!deps.isEmpty()) {
9276            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9277                    options.getCompilerFilter(), options.getSplitName(),
9278                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9279            for (PackageParser.Package depPackage : deps) {
9280                // TODO: Analyze and investigate if we (should) profile libraries.
9281                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9282                        getOrCreateCompilerPackageStats(depPackage),
9283                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9284            }
9285        }
9286        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9287                getOrCreateCompilerPackageStats(p),
9288                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9289    }
9290
9291    /**
9292     * Reconcile the information we have about the secondary dex files belonging to
9293     * {@code packagName} and the actual dex files. For all dex files that were
9294     * deleted, update the internal records and delete the generated oat files.
9295     */
9296    @Override
9297    public void reconcileSecondaryDexFiles(String packageName) {
9298        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9299            return;
9300        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9301            return;
9302        }
9303        mDexManager.reconcileSecondaryDexFiles(packageName);
9304    }
9305
9306    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9307    // a reference there.
9308    /*package*/ DexManager getDexManager() {
9309        return mDexManager;
9310    }
9311
9312    /**
9313     * Execute the background dexopt job immediately.
9314     */
9315    @Override
9316    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9317        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9318            return false;
9319        }
9320        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9321    }
9322
9323    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9324        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9325                || p.usesStaticLibraries != null) {
9326            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9327            Set<String> collectedNames = new HashSet<>();
9328            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9329
9330            retValue.remove(p);
9331
9332            return retValue;
9333        } else {
9334            return Collections.emptyList();
9335        }
9336    }
9337
9338    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9339            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9340        if (!collectedNames.contains(p.packageName)) {
9341            collectedNames.add(p.packageName);
9342            collected.add(p);
9343
9344            if (p.usesLibraries != null) {
9345                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9346                        null, collected, collectedNames);
9347            }
9348            if (p.usesOptionalLibraries != null) {
9349                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9350                        null, collected, collectedNames);
9351            }
9352            if (p.usesStaticLibraries != null) {
9353                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9354                        p.usesStaticLibrariesVersions, collected, collectedNames);
9355            }
9356        }
9357    }
9358
9359    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9360            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9361        final int libNameCount = libs.size();
9362        for (int i = 0; i < libNameCount; i++) {
9363            String libName = libs.get(i);
9364            long version = (versions != null && versions.length == libNameCount)
9365                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9366            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9367            if (libPkg != null) {
9368                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9369            }
9370        }
9371    }
9372
9373    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9374        synchronized (mPackages) {
9375            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9376            if (libEntry != null) {
9377                return mPackages.get(libEntry.apk);
9378            }
9379            return null;
9380        }
9381    }
9382
9383    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9384        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9385        if (versionedLib == null) {
9386            return null;
9387        }
9388        return versionedLib.get(version);
9389    }
9390
9391    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9392        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9393                pkg.staticSharedLibName);
9394        if (versionedLib == null) {
9395            return null;
9396        }
9397        long previousLibVersion = -1;
9398        final int versionCount = versionedLib.size();
9399        for (int i = 0; i < versionCount; i++) {
9400            final long libVersion = versionedLib.keyAt(i);
9401            if (libVersion < pkg.staticSharedLibVersion) {
9402                previousLibVersion = Math.max(previousLibVersion, libVersion);
9403            }
9404        }
9405        if (previousLibVersion >= 0) {
9406            return versionedLib.get(previousLibVersion);
9407        }
9408        return null;
9409    }
9410
9411    public void shutdown() {
9412        mPackageUsage.writeNow(mPackages);
9413        mCompilerStats.writeNow();
9414        mDexManager.writePackageDexUsageNow();
9415    }
9416
9417    @Override
9418    public void dumpProfiles(String packageName) {
9419        PackageParser.Package pkg;
9420        synchronized (mPackages) {
9421            pkg = mPackages.get(packageName);
9422            if (pkg == null) {
9423                throw new IllegalArgumentException("Unknown package: " + packageName);
9424            }
9425        }
9426        /* Only the shell, root, or the app user should be able to dump profiles. */
9427        int callingUid = Binder.getCallingUid();
9428        if (callingUid != Process.SHELL_UID &&
9429            callingUid != Process.ROOT_UID &&
9430            callingUid != pkg.applicationInfo.uid) {
9431            throw new SecurityException("dumpProfiles");
9432        }
9433
9434        synchronized (mInstallLock) {
9435            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9436            mArtManagerService.dumpProfiles(pkg);
9437            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9438        }
9439    }
9440
9441    @Override
9442    public void forceDexOpt(String packageName) {
9443        enforceSystemOrRoot("forceDexOpt");
9444
9445        PackageParser.Package pkg;
9446        synchronized (mPackages) {
9447            pkg = mPackages.get(packageName);
9448            if (pkg == null) {
9449                throw new IllegalArgumentException("Unknown package: " + packageName);
9450            }
9451        }
9452
9453        synchronized (mInstallLock) {
9454            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9455
9456            // Whoever is calling forceDexOpt wants a compiled package.
9457            // Don't use profiles since that may cause compilation to be skipped.
9458            final int res = performDexOptInternalWithDependenciesLI(
9459                    pkg,
9460                    new DexoptOptions(packageName,
9461                            getDefaultCompilerFilter(),
9462                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9463
9464            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9465            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9466                throw new IllegalStateException("Failed to dexopt: " + res);
9467            }
9468        }
9469    }
9470
9471    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9472        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9473            Slog.w(TAG, "Unable to update from " + oldPkg.name
9474                    + " to " + newPkg.packageName
9475                    + ": old package not in system partition");
9476            return false;
9477        } else if (mPackages.get(oldPkg.name) != null) {
9478            Slog.w(TAG, "Unable to update from " + oldPkg.name
9479                    + " to " + newPkg.packageName
9480                    + ": old package still exists");
9481            return false;
9482        }
9483        return true;
9484    }
9485
9486    void removeCodePathLI(File codePath) {
9487        if (codePath.isDirectory()) {
9488            try {
9489                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9490            } catch (InstallerException e) {
9491                Slog.w(TAG, "Failed to remove code path", e);
9492            }
9493        } else {
9494            codePath.delete();
9495        }
9496    }
9497
9498    private int[] resolveUserIds(int userId) {
9499        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9500    }
9501
9502    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9503        if (pkg == null) {
9504            Slog.wtf(TAG, "Package was null!", new Throwable());
9505            return;
9506        }
9507        clearAppDataLeafLIF(pkg, userId, flags);
9508        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9509        for (int i = 0; i < childCount; i++) {
9510            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9511        }
9512
9513        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9514    }
9515
9516    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9517        final PackageSetting ps;
9518        synchronized (mPackages) {
9519            ps = mSettings.mPackages.get(pkg.packageName);
9520        }
9521        for (int realUserId : resolveUserIds(userId)) {
9522            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9523            try {
9524                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9525                        ceDataInode);
9526            } catch (InstallerException e) {
9527                Slog.w(TAG, String.valueOf(e));
9528            }
9529        }
9530    }
9531
9532    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9533        if (pkg == null) {
9534            Slog.wtf(TAG, "Package was null!", new Throwable());
9535            return;
9536        }
9537        destroyAppDataLeafLIF(pkg, userId, flags);
9538        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9539        for (int i = 0; i < childCount; i++) {
9540            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9541        }
9542    }
9543
9544    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9545        final PackageSetting ps;
9546        synchronized (mPackages) {
9547            ps = mSettings.mPackages.get(pkg.packageName);
9548        }
9549        for (int realUserId : resolveUserIds(userId)) {
9550            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9551            try {
9552                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9553                        ceDataInode);
9554            } catch (InstallerException e) {
9555                Slog.w(TAG, String.valueOf(e));
9556            }
9557            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9558        }
9559    }
9560
9561    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9562        if (pkg == null) {
9563            Slog.wtf(TAG, "Package was null!", new Throwable());
9564            return;
9565        }
9566        destroyAppProfilesLeafLIF(pkg);
9567        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9568        for (int i = 0; i < childCount; i++) {
9569            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9570        }
9571    }
9572
9573    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9574        try {
9575            mInstaller.destroyAppProfiles(pkg.packageName);
9576        } catch (InstallerException e) {
9577            Slog.w(TAG, String.valueOf(e));
9578        }
9579    }
9580
9581    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9582        if (pkg == null) {
9583            Slog.wtf(TAG, "Package was null!", new Throwable());
9584            return;
9585        }
9586        mArtManagerService.clearAppProfiles(pkg);
9587        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9588        for (int i = 0; i < childCount; i++) {
9589            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9590        }
9591    }
9592
9593    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9594            long lastUpdateTime) {
9595        // Set parent install/update time
9596        PackageSetting ps = (PackageSetting) pkg.mExtras;
9597        if (ps != null) {
9598            ps.firstInstallTime = firstInstallTime;
9599            ps.lastUpdateTime = lastUpdateTime;
9600        }
9601        // Set children install/update time
9602        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9603        for (int i = 0; i < childCount; i++) {
9604            PackageParser.Package childPkg = pkg.childPackages.get(i);
9605            ps = (PackageSetting) childPkg.mExtras;
9606            if (ps != null) {
9607                ps.firstInstallTime = firstInstallTime;
9608                ps.lastUpdateTime = lastUpdateTime;
9609            }
9610        }
9611    }
9612
9613    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9614            SharedLibraryEntry file,
9615            PackageParser.Package changingLib) {
9616        if (file.path != null) {
9617            usesLibraryFiles.add(file.path);
9618            return;
9619        }
9620        PackageParser.Package p = mPackages.get(file.apk);
9621        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9622            // If we are doing this while in the middle of updating a library apk,
9623            // then we need to make sure to use that new apk for determining the
9624            // dependencies here.  (We haven't yet finished committing the new apk
9625            // to the package manager state.)
9626            if (p == null || p.packageName.equals(changingLib.packageName)) {
9627                p = changingLib;
9628            }
9629        }
9630        if (p != null) {
9631            usesLibraryFiles.addAll(p.getAllCodePaths());
9632            if (p.usesLibraryFiles != null) {
9633                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9634            }
9635        }
9636    }
9637
9638    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9639            PackageParser.Package changingLib) throws PackageManagerException {
9640        if (pkg == null) {
9641            return;
9642        }
9643        // The collection used here must maintain the order of addition (so
9644        // that libraries are searched in the correct order) and must have no
9645        // duplicates.
9646        Set<String> usesLibraryFiles = null;
9647        if (pkg.usesLibraries != null) {
9648            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9649                    null, null, pkg.packageName, changingLib, true,
9650                    pkg.applicationInfo.targetSdkVersion, null);
9651        }
9652        if (pkg.usesStaticLibraries != null) {
9653            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9654                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9655                    pkg.packageName, changingLib, true,
9656                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9657        }
9658        if (pkg.usesOptionalLibraries != null) {
9659            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9660                    null, null, pkg.packageName, changingLib, false,
9661                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9662        }
9663        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9664            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9665        } else {
9666            pkg.usesLibraryFiles = null;
9667        }
9668    }
9669
9670    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9671            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9672            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9673            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9674            throws PackageManagerException {
9675        final int libCount = requestedLibraries.size();
9676        for (int i = 0; i < libCount; i++) {
9677            final String libName = requestedLibraries.get(i);
9678            final long libVersion = requiredVersions != null ? requiredVersions[i]
9679                    : SharedLibraryInfo.VERSION_UNDEFINED;
9680            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9681            if (libEntry == null) {
9682                if (required) {
9683                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9684                            "Package " + packageName + " requires unavailable shared library "
9685                                    + libName + "; failing!");
9686                } else if (DEBUG_SHARED_LIBRARIES) {
9687                    Slog.i(TAG, "Package " + packageName
9688                            + " desires unavailable shared library "
9689                            + libName + "; ignoring!");
9690                }
9691            } else {
9692                if (requiredVersions != null && requiredCertDigests != null) {
9693                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9694                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9695                            "Package " + packageName + " requires unavailable static shared"
9696                                    + " library " + libName + " version "
9697                                    + libEntry.info.getLongVersion() + "; failing!");
9698                    }
9699
9700                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9701                    if (libPkg == null) {
9702                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9703                                "Package " + packageName + " requires unavailable static shared"
9704                                        + " library; failing!");
9705                    }
9706
9707                    final String[] expectedCertDigests = requiredCertDigests[i];
9708
9709
9710                    if (expectedCertDigests.length > 1) {
9711
9712                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9713                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9714                                ? PackageUtils.computeSignaturesSha256Digests(
9715                                libPkg.mSigningDetails.signatures)
9716                                : PackageUtils.computeSignaturesSha256Digests(
9717                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9718
9719                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9720                        // target O we don't parse the "additional-certificate" tags similarly
9721                        // how we only consider all certs only for apps targeting O (see above).
9722                        // Therefore, the size check is safe to make.
9723                        if (expectedCertDigests.length != libCertDigests.length) {
9724                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9725                                    "Package " + packageName + " requires differently signed" +
9726                                            " static shared library; failing!");
9727                        }
9728
9729                        // Use a predictable order as signature order may vary
9730                        Arrays.sort(libCertDigests);
9731                        Arrays.sort(expectedCertDigests);
9732
9733                        final int certCount = libCertDigests.length;
9734                        for (int j = 0; j < certCount; j++) {
9735                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9736                                throw new PackageManagerException(
9737                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9738                                        "Package " + packageName + " requires differently signed" +
9739                                                " static shared library; failing!");
9740                            }
9741                        }
9742                    } else {
9743
9744                        // lib signing cert could have rotated beyond the one expected, check to see
9745                        // if the new one has been blessed by the old
9746                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9747                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9748                            throw new PackageManagerException(
9749                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9750                                    "Package " + packageName + " requires differently signed" +
9751                                            " static shared library; failing!");
9752                        }
9753                    }
9754                }
9755
9756                if (outUsedLibraries == null) {
9757                    // Use LinkedHashSet to preserve the order of files added to
9758                    // usesLibraryFiles while eliminating duplicates.
9759                    outUsedLibraries = new LinkedHashSet<>();
9760                }
9761                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9762            }
9763        }
9764        return outUsedLibraries;
9765    }
9766
9767    private static boolean hasString(List<String> list, List<String> which) {
9768        if (list == null) {
9769            return false;
9770        }
9771        for (int i=list.size()-1; i>=0; i--) {
9772            for (int j=which.size()-1; j>=0; j--) {
9773                if (which.get(j).equals(list.get(i))) {
9774                    return true;
9775                }
9776            }
9777        }
9778        return false;
9779    }
9780
9781    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9782            PackageParser.Package changingPkg) {
9783        ArrayList<PackageParser.Package> res = null;
9784        for (PackageParser.Package pkg : mPackages.values()) {
9785            if (changingPkg != null
9786                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9787                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9788                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9789                            changingPkg.staticSharedLibName)) {
9790                return null;
9791            }
9792            if (res == null) {
9793                res = new ArrayList<>();
9794            }
9795            res.add(pkg);
9796            try {
9797                updateSharedLibrariesLPr(pkg, changingPkg);
9798            } catch (PackageManagerException e) {
9799                // If a system app update or an app and a required lib missing we
9800                // delete the package and for updated system apps keep the data as
9801                // it is better for the user to reinstall than to be in an limbo
9802                // state. Also libs disappearing under an app should never happen
9803                // - just in case.
9804                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9805                    final int flags = pkg.isUpdatedSystemApp()
9806                            ? PackageManager.DELETE_KEEP_DATA : 0;
9807                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9808                            flags , null, true, null);
9809                }
9810                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9811            }
9812        }
9813        return res;
9814    }
9815
9816    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9817            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9818            @Nullable UserHandle user) throws PackageManagerException {
9819        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9820        // If the package has children and this is the first dive in the function
9821        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9822        // whether all packages (parent and children) would be successfully scanned
9823        // before the actual scan since scanning mutates internal state and we want
9824        // to atomically install the package and its children.
9825        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9826            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9827                scanFlags |= SCAN_CHECK_ONLY;
9828            }
9829        } else {
9830            scanFlags &= ~SCAN_CHECK_ONLY;
9831        }
9832
9833        final PackageParser.Package scannedPkg;
9834        try {
9835            // Scan the parent
9836            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9837            // Scan the children
9838            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9839            for (int i = 0; i < childCount; i++) {
9840                PackageParser.Package childPkg = pkg.childPackages.get(i);
9841                scanPackageNewLI(childPkg, parseFlags,
9842                        scanFlags, currentTime, user);
9843            }
9844        } finally {
9845            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9846        }
9847
9848        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9849            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9850        }
9851
9852        return scannedPkg;
9853    }
9854
9855    /** The result of a package scan. */
9856    private static class ScanResult {
9857        /** Whether or not the package scan was successful */
9858        public final boolean success;
9859        /**
9860         * The final package settings. This may be the same object passed in
9861         * the {@link ScanRequest}, but, with modified values.
9862         */
9863        @Nullable public final PackageSetting pkgSetting;
9864        /** ABI code paths that have changed in the package scan */
9865        @Nullable public final List<String> changedAbiCodePath;
9866        public ScanResult(
9867                boolean success,
9868                @Nullable PackageSetting pkgSetting,
9869                @Nullable List<String> changedAbiCodePath) {
9870            this.success = success;
9871            this.pkgSetting = pkgSetting;
9872            this.changedAbiCodePath = changedAbiCodePath;
9873        }
9874    }
9875
9876    /** A package to be scanned */
9877    private static class ScanRequest {
9878        /** The parsed package */
9879        @NonNull public final PackageParser.Package pkg;
9880        /** Shared user settings, if the package has a shared user */
9881        @Nullable public final SharedUserSetting sharedUserSetting;
9882        /**
9883         * Package settings of the currently installed version.
9884         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9885         * during scan.
9886         */
9887        @Nullable public final PackageSetting pkgSetting;
9888        /** A copy of the settings for the currently installed version */
9889        @Nullable public final PackageSetting oldPkgSetting;
9890        /** Package settings for the disabled version on the /system partition */
9891        @Nullable public final PackageSetting disabledPkgSetting;
9892        /** Package settings for the installed version under its original package name */
9893        @Nullable public final PackageSetting originalPkgSetting;
9894        /** The real package name of a renamed application */
9895        @Nullable public final String realPkgName;
9896        public final @ParseFlags int parseFlags;
9897        public final @ScanFlags int scanFlags;
9898        /** The user for which the package is being scanned */
9899        @Nullable public final UserHandle user;
9900        /** Whether or not the platform package is being scanned */
9901        public final boolean isPlatformPackage;
9902        public ScanRequest(
9903                @NonNull PackageParser.Package pkg,
9904                @Nullable SharedUserSetting sharedUserSetting,
9905                @Nullable PackageSetting pkgSetting,
9906                @Nullable PackageSetting disabledPkgSetting,
9907                @Nullable PackageSetting originalPkgSetting,
9908                @Nullable String realPkgName,
9909                @ParseFlags int parseFlags,
9910                @ScanFlags int scanFlags,
9911                boolean isPlatformPackage,
9912                @Nullable UserHandle user) {
9913            this.pkg = pkg;
9914            this.pkgSetting = pkgSetting;
9915            this.sharedUserSetting = sharedUserSetting;
9916            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9917            this.disabledPkgSetting = disabledPkgSetting;
9918            this.originalPkgSetting = originalPkgSetting;
9919            this.realPkgName = realPkgName;
9920            this.parseFlags = parseFlags;
9921            this.scanFlags = scanFlags;
9922            this.isPlatformPackage = isPlatformPackage;
9923            this.user = user;
9924        }
9925    }
9926
9927    /**
9928     * Returns the actual scan flags depending upon the state of the other settings.
9929     * <p>Updated system applications will not have the following flags set
9930     * by default and need to be adjusted after the fact:
9931     * <ul>
9932     * <li>{@link #SCAN_AS_SYSTEM}</li>
9933     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9934     * <li>{@link #SCAN_AS_OEM}</li>
9935     * <li>{@link #SCAN_AS_VENDOR}</li>
9936     * <li>{@link #SCAN_AS_PRODUCT}</li>
9937     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9938     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9939     * </ul>
9940     */
9941    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9942            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9943            PackageParser.Package pkg) {
9944        if (disabledPkgSetting != null) {
9945            // updated system application, must at least have SCAN_AS_SYSTEM
9946            scanFlags |= SCAN_AS_SYSTEM;
9947            if ((disabledPkgSetting.pkgPrivateFlags
9948                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9949                scanFlags |= SCAN_AS_PRIVILEGED;
9950            }
9951            if ((disabledPkgSetting.pkgPrivateFlags
9952                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9953                scanFlags |= SCAN_AS_OEM;
9954            }
9955            if ((disabledPkgSetting.pkgPrivateFlags
9956                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9957                scanFlags |= SCAN_AS_VENDOR;
9958            }
9959            if ((disabledPkgSetting.pkgPrivateFlags
9960                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9961                scanFlags |= SCAN_AS_PRODUCT;
9962            }
9963        }
9964        if (pkgSetting != null) {
9965            final int userId = ((user == null) ? 0 : user.getIdentifier());
9966            if (pkgSetting.getInstantApp(userId)) {
9967                scanFlags |= SCAN_AS_INSTANT_APP;
9968            }
9969            if (pkgSetting.getVirtulalPreload(userId)) {
9970                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9971            }
9972        }
9973
9974        // Scan as privileged apps that share a user with a priv-app.
9975        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9976                && (pkg.mSharedUserId != null)) {
9977            SharedUserSetting sharedUserSetting = null;
9978            try {
9979                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9980            } catch (PackageManagerException ignore) {}
9981            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9982                // Exempt SharedUsers signed with the platform key.
9983                // TODO(b/72378145) Fix this exemption. Force signature apps
9984                // to whitelist their privileged permissions just like other
9985                // priv-apps.
9986                synchronized (mPackages) {
9987                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9988                    if (!pkg.packageName.equals("android")
9989                            && (compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9990                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9991                        scanFlags |= SCAN_AS_PRIVILEGED;
9992                    }
9993                }
9994            }
9995        }
9996
9997        return scanFlags;
9998    }
9999
10000    @GuardedBy("mInstallLock")
10001    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10002            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10003            @Nullable UserHandle user) throws PackageManagerException {
10004
10005        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10006        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10007        if (realPkgName != null) {
10008            ensurePackageRenamed(pkg, renamedPkgName);
10009        }
10010        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10011        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10012        final PackageSetting disabledPkgSetting =
10013                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10014
10015        if (mTransferedPackages.contains(pkg.packageName)) {
10016            Slog.w(TAG, "Package " + pkg.packageName
10017                    + " was transferred to another, but its .apk remains");
10018        }
10019
10020        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10021        synchronized (mPackages) {
10022            applyPolicy(pkg, parseFlags, scanFlags);
10023            assertPackageIsValid(pkg, parseFlags, scanFlags);
10024
10025            SharedUserSetting sharedUserSetting = null;
10026            if (pkg.mSharedUserId != null) {
10027                // SIDE EFFECTS; may potentially allocate a new shared user
10028                sharedUserSetting = mSettings.getSharedUserLPw(
10029                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10030                if (DEBUG_PACKAGE_SCANNING) {
10031                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10032                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10033                                + " (uid=" + sharedUserSetting.userId + "):"
10034                                + " packages=" + sharedUserSetting.packages);
10035                }
10036            }
10037
10038            boolean scanSucceeded = false;
10039            try {
10040                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10041                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10042                        (pkg == mPlatformPackage), user);
10043                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10044                if (result.success) {
10045                    commitScanResultsLocked(request, result);
10046                }
10047                scanSucceeded = true;
10048            } finally {
10049                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10050                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10051                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10052                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10053                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10054                  }
10055            }
10056        }
10057        return pkg;
10058    }
10059
10060    /**
10061     * Commits the package scan and modifies system state.
10062     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10063     * of committing the package, leaving the system in an inconsistent state.
10064     * This needs to be fixed so, once we get to this point, no errors are
10065     * possible and the system is not left in an inconsistent state.
10066     */
10067    @GuardedBy("mPackages")
10068    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10069            throws PackageManagerException {
10070        final PackageParser.Package pkg = request.pkg;
10071        final @ParseFlags int parseFlags = request.parseFlags;
10072        final @ScanFlags int scanFlags = request.scanFlags;
10073        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10074        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10075        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10076        final UserHandle user = request.user;
10077        final String realPkgName = request.realPkgName;
10078        final PackageSetting pkgSetting = result.pkgSetting;
10079        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10080        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10081
10082        if (newPkgSettingCreated) {
10083            if (originalPkgSetting != null) {
10084                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10085            }
10086            // THROWS: when we can't allocate a user id. add call to check if there's
10087            // enough space to ensure we won't throw; otherwise, don't modify state
10088            mSettings.addUserToSettingLPw(pkgSetting);
10089
10090            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10091                mTransferedPackages.add(originalPkgSetting.name);
10092            }
10093        }
10094        // TODO(toddke): Consider a method specifically for modifying the Package object
10095        // post scan; or, moving this stuff out of the Package object since it has nothing
10096        // to do with the package on disk.
10097        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10098        // for creating the application ID. If we did this earlier, we would be saving the
10099        // correct ID.
10100        pkg.applicationInfo.uid = pkgSetting.appId;
10101
10102        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10103
10104        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10105            mTransferedPackages.add(pkg.packageName);
10106        }
10107
10108        // THROWS: when requested libraries that can't be found. it only changes
10109        // the state of the passed in pkg object, so, move to the top of the method
10110        // and allow it to abort
10111        if ((scanFlags & SCAN_BOOTING) == 0
10112                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10113            // Check all shared libraries and map to their actual file path.
10114            // We only do this here for apps not on a system dir, because those
10115            // are the only ones that can fail an install due to this.  We
10116            // will take care of the system apps by updating all of their
10117            // library paths after the scan is done. Also during the initial
10118            // scan don't update any libs as we do this wholesale after all
10119            // apps are scanned to avoid dependency based scanning.
10120            updateSharedLibrariesLPr(pkg, null);
10121        }
10122
10123        // All versions of a static shared library are referenced with the same
10124        // package name. Internally, we use a synthetic package name to allow
10125        // multiple versions of the same shared library to be installed. So,
10126        // we need to generate the synthetic package name of the latest shared
10127        // library in order to compare signatures.
10128        PackageSetting signatureCheckPs = pkgSetting;
10129        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10130            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10131            if (libraryEntry != null) {
10132                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10133            }
10134        }
10135
10136        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10137        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10138            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10139                // We just determined the app is signed correctly, so bring
10140                // over the latest parsed certs.
10141                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10142            } else {
10143                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10144                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10145                            "Package " + pkg.packageName + " upgrade keys do not match the "
10146                                    + "previously installed version");
10147                } else {
10148                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10149                    String msg = "System package " + pkg.packageName
10150                            + " signature changed; retaining data.";
10151                    reportSettingsProblem(Log.WARN, msg);
10152                }
10153            }
10154        } else {
10155            try {
10156                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10157                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10158                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10159                        pkg.mSigningDetails, compareCompat, compareRecover);
10160                // The new KeySets will be re-added later in the scanning process.
10161                if (compatMatch) {
10162                    synchronized (mPackages) {
10163                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10164                    }
10165                }
10166                // We just determined the app is signed correctly, so bring
10167                // over the latest parsed certs.
10168                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10169
10170
10171                // if this is is a sharedUser, check to see if the new package is signed by a newer
10172                // signing certificate than the existing one, and if so, copy over the new details
10173                if (signatureCheckPs.sharedUser != null
10174                        && pkg.mSigningDetails.hasAncestor(
10175                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10176                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10177                }
10178            } catch (PackageManagerException e) {
10179                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10180                    throw e;
10181                }
10182                // The signature has changed, but this package is in the system
10183                // image...  let's recover!
10184                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10185                // However...  if this package is part of a shared user, but it
10186                // doesn't match the signature of the shared user, let's fail.
10187                // What this means is that you can't change the signatures
10188                // associated with an overall shared user, which doesn't seem all
10189                // that unreasonable.
10190                if (signatureCheckPs.sharedUser != null) {
10191                    if (compareSignatures(
10192                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10193                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10194                        throw new PackageManagerException(
10195                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10196                                "Signature mismatch for shared user: "
10197                                        + pkgSetting.sharedUser);
10198                    }
10199                }
10200                // File a report about this.
10201                String msg = "System package " + pkg.packageName
10202                        + " signature changed; retaining data.";
10203                reportSettingsProblem(Log.WARN, msg);
10204            } catch (IllegalArgumentException e) {
10205
10206                // should never happen: certs matched when checking, but not when comparing
10207                // old to new for sharedUser
10208                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10209                        "Signing certificates comparison made on incomparable signing details"
10210                        + " but somehow passed verifySignatures!");
10211            }
10212        }
10213
10214        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10215            // This package wants to adopt ownership of permissions from
10216            // another package.
10217            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10218                final String origName = pkg.mAdoptPermissions.get(i);
10219                final PackageSetting orig = mSettings.getPackageLPr(origName);
10220                if (orig != null) {
10221                    if (verifyPackageUpdateLPr(orig, pkg)) {
10222                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10223                                + pkg.packageName);
10224                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10225                    }
10226                }
10227            }
10228        }
10229
10230        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10231            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10232                final String codePathString = changedAbiCodePath.get(i);
10233                try {
10234                    mInstaller.rmdex(codePathString,
10235                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10236                } catch (InstallerException ignored) {
10237                }
10238            }
10239        }
10240
10241        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10242            if (oldPkgSetting != null) {
10243                synchronized (mPackages) {
10244                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10245                }
10246            }
10247        } else {
10248            final int userId = user == null ? 0 : user.getIdentifier();
10249            // Modify state for the given package setting
10250            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10251                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10252            if (pkgSetting.getInstantApp(userId)) {
10253                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10254            }
10255        }
10256    }
10257
10258    /**
10259     * Returns the "real" name of the package.
10260     * <p>This may differ from the package's actual name if the application has already
10261     * been installed under one of this package's original names.
10262     */
10263    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10264            @Nullable String renamedPkgName) {
10265        if (isPackageRenamed(pkg, renamedPkgName)) {
10266            return pkg.mRealPackage;
10267        }
10268        return null;
10269    }
10270
10271    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10272    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10273            @Nullable String renamedPkgName) {
10274        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10275    }
10276
10277    /**
10278     * Returns the original package setting.
10279     * <p>A package can migrate its name during an update. In this scenario, a package
10280     * designates a set of names that it considers as one of its original names.
10281     * <p>An original package must be signed identically and it must have the same
10282     * shared user [if any].
10283     */
10284    @GuardedBy("mPackages")
10285    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10286            @Nullable String renamedPkgName) {
10287        if (!isPackageRenamed(pkg, renamedPkgName)) {
10288            return null;
10289        }
10290        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10291            final PackageSetting originalPs =
10292                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10293            if (originalPs != null) {
10294                // the package is already installed under its original name...
10295                // but, should we use it?
10296                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10297                    // the new package is incompatible with the original
10298                    continue;
10299                } else if (originalPs.sharedUser != null) {
10300                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10301                        // the shared user id is incompatible with the original
10302                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10303                                + " to " + pkg.packageName + ": old uid "
10304                                + originalPs.sharedUser.name
10305                                + " differs from " + pkg.mSharedUserId);
10306                        continue;
10307                    }
10308                    // TODO: Add case when shared user id is added [b/28144775]
10309                } else {
10310                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10311                            + pkg.packageName + " to old name " + originalPs.name);
10312                }
10313                return originalPs;
10314            }
10315        }
10316        return null;
10317    }
10318
10319    /**
10320     * Renames the package if it was installed under a different name.
10321     * <p>When we've already installed the package under an original name, update
10322     * the new package so we can continue to have the old name.
10323     */
10324    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10325            @NonNull String renamedPackageName) {
10326        if (pkg.mOriginalPackages == null
10327                || !pkg.mOriginalPackages.contains(renamedPackageName)
10328                || pkg.packageName.equals(renamedPackageName)) {
10329            return;
10330        }
10331        pkg.setPackageName(renamedPackageName);
10332    }
10333
10334    /**
10335     * Just scans the package without any side effects.
10336     * <p>Not entirely true at the moment. There is still one side effect -- this
10337     * method potentially modifies a live {@link PackageSetting} object representing
10338     * the package being scanned. This will be resolved in the future.
10339     *
10340     * @param request Information about the package to be scanned
10341     * @param isUnderFactoryTest Whether or not the device is under factory test
10342     * @param currentTime The current time, in millis
10343     * @return The results of the scan
10344     */
10345    @GuardedBy("mInstallLock")
10346    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10347            boolean isUnderFactoryTest, long currentTime)
10348                    throws PackageManagerException {
10349        final PackageParser.Package pkg = request.pkg;
10350        PackageSetting pkgSetting = request.pkgSetting;
10351        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10352        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10353        final @ParseFlags int parseFlags = request.parseFlags;
10354        final @ScanFlags int scanFlags = request.scanFlags;
10355        final String realPkgName = request.realPkgName;
10356        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10357        final UserHandle user = request.user;
10358        final boolean isPlatformPackage = request.isPlatformPackage;
10359
10360        List<String> changedAbiCodePath = null;
10361
10362        if (DEBUG_PACKAGE_SCANNING) {
10363            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10364                Log.d(TAG, "Scanning package " + pkg.packageName);
10365        }
10366
10367        if (Build.IS_DEBUGGABLE &&
10368                pkg.isPrivileged() &&
10369                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10370            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10371        }
10372
10373        // Initialize package source and resource directories
10374        final File scanFile = new File(pkg.codePath);
10375        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10376        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10377
10378        // We keep references to the derived CPU Abis from settings in oder to reuse
10379        // them in the case where we're not upgrading or booting for the first time.
10380        String primaryCpuAbiFromSettings = null;
10381        String secondaryCpuAbiFromSettings = null;
10382        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10383
10384        if (!needToDeriveAbi) {
10385            if (pkgSetting != null) {
10386                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10387                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10388            } else {
10389                // Re-scanning a system package after uninstalling updates; need to derive ABI
10390                needToDeriveAbi = true;
10391            }
10392        }
10393
10394        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10395            PackageManagerService.reportSettingsProblem(Log.WARN,
10396                    "Package " + pkg.packageName + " shared user changed from "
10397                            + (pkgSetting.sharedUser != null
10398                            ? pkgSetting.sharedUser.name : "<nothing>")
10399                            + " to "
10400                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10401                            + "; replacing with new");
10402            pkgSetting = null;
10403        }
10404
10405        String[] usesStaticLibraries = null;
10406        if (pkg.usesStaticLibraries != null) {
10407            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10408            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10409        }
10410        final boolean createNewPackage = (pkgSetting == null);
10411        if (createNewPackage) {
10412            final String parentPackageName = (pkg.parentPackage != null)
10413                    ? pkg.parentPackage.packageName : null;
10414            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10415            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10416            // REMOVE SharedUserSetting from method; update in a separate call
10417            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10418                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10419                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10420                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10421                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10422                    user, true /*allowInstall*/, instantApp, virtualPreload,
10423                    parentPackageName, pkg.getChildPackageNames(),
10424                    UserManagerService.getInstance(), usesStaticLibraries,
10425                    pkg.usesStaticLibrariesVersions);
10426        } else {
10427            // REMOVE SharedUserSetting from method; update in a separate call.
10428            //
10429            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10430            // secondaryCpuAbi are not known at this point so we always update them
10431            // to null here, only to reset them at a later point.
10432            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10433                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10434                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10435                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10436                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10437                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10438        }
10439        if (createNewPackage && originalPkgSetting != null) {
10440            // This is the initial transition from the original package, so,
10441            // fix up the new package's name now. We must do this after looking
10442            // up the package under its new name, so getPackageLP takes care of
10443            // fiddling things correctly.
10444            pkg.setPackageName(originalPkgSetting.name);
10445
10446            // File a report about this.
10447            String msg = "New package " + pkgSetting.realName
10448                    + " renamed to replace old package " + pkgSetting.name;
10449            reportSettingsProblem(Log.WARN, msg);
10450        }
10451
10452        if (disabledPkgSetting != null) {
10453            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10454        }
10455
10456        SELinuxMMAC.assignSeInfoValue(pkg);
10457
10458        pkg.mExtras = pkgSetting;
10459        pkg.applicationInfo.processName = fixProcessName(
10460                pkg.applicationInfo.packageName,
10461                pkg.applicationInfo.processName);
10462
10463        if (!isPlatformPackage) {
10464            // Get all of our default paths setup
10465            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10466        }
10467
10468        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10469
10470        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10471            if (needToDeriveAbi) {
10472                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10473                final boolean extractNativeLibs = !pkg.isLibrary();
10474                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10475                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10476
10477                // Some system apps still use directory structure for native libraries
10478                // in which case we might end up not detecting abi solely based on apk
10479                // structure. Try to detect abi based on directory structure.
10480                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10481                        pkg.applicationInfo.primaryCpuAbi == null) {
10482                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10483                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10484                }
10485            } else {
10486                // This is not a first boot or an upgrade, don't bother deriving the
10487                // ABI during the scan. Instead, trust the value that was stored in the
10488                // package setting.
10489                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10490                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10491
10492                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10493
10494                if (DEBUG_ABI_SELECTION) {
10495                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10496                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10497                            pkg.applicationInfo.secondaryCpuAbi);
10498                }
10499            }
10500        } else {
10501            if ((scanFlags & SCAN_MOVE) != 0) {
10502                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10503                // but we already have this packages package info in the PackageSetting. We just
10504                // use that and derive the native library path based on the new codepath.
10505                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10506                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10507            }
10508
10509            // Set native library paths again. For moves, the path will be updated based on the
10510            // ABIs we've determined above. For non-moves, the path will be updated based on the
10511            // ABIs we determined during compilation, but the path will depend on the final
10512            // package path (after the rename away from the stage path).
10513            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10514        }
10515
10516        // This is a special case for the "system" package, where the ABI is
10517        // dictated by the zygote configuration (and init.rc). We should keep track
10518        // of this ABI so that we can deal with "normal" applications that run under
10519        // the same UID correctly.
10520        if (isPlatformPackage) {
10521            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10522                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10523        }
10524
10525        // If there's a mismatch between the abi-override in the package setting
10526        // and the abiOverride specified for the install. Warn about this because we
10527        // would've already compiled the app without taking the package setting into
10528        // account.
10529        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10530            if (cpuAbiOverride == null && pkg.packageName != null) {
10531                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10532                        " for package " + pkg.packageName);
10533            }
10534        }
10535
10536        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10537        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10538        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10539
10540        // Copy the derived override back to the parsed package, so that we can
10541        // update the package settings accordingly.
10542        pkg.cpuAbiOverride = cpuAbiOverride;
10543
10544        if (DEBUG_ABI_SELECTION) {
10545            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10546                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10547                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10548        }
10549
10550        // Push the derived path down into PackageSettings so we know what to
10551        // clean up at uninstall time.
10552        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10553
10554        if (DEBUG_ABI_SELECTION) {
10555            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10556                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10557                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10558        }
10559
10560        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10561            // We don't do this here during boot because we can do it all
10562            // at once after scanning all existing packages.
10563            //
10564            // We also do this *before* we perform dexopt on this package, so that
10565            // we can avoid redundant dexopts, and also to make sure we've got the
10566            // code and package path correct.
10567            changedAbiCodePath =
10568                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10569        }
10570
10571        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10572                android.Manifest.permission.FACTORY_TEST)) {
10573            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10574        }
10575
10576        if (isSystemApp(pkg)) {
10577            pkgSetting.isOrphaned = true;
10578        }
10579
10580        // Take care of first install / last update times.
10581        final long scanFileTime = getLastModifiedTime(pkg);
10582        if (currentTime != 0) {
10583            if (pkgSetting.firstInstallTime == 0) {
10584                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10585            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10586                pkgSetting.lastUpdateTime = currentTime;
10587            }
10588        } else if (pkgSetting.firstInstallTime == 0) {
10589            // We need *something*.  Take time time stamp of the file.
10590            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10591        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10592            if (scanFileTime != pkgSetting.timeStamp) {
10593                // A package on the system image has changed; consider this
10594                // to be an update.
10595                pkgSetting.lastUpdateTime = scanFileTime;
10596            }
10597        }
10598        pkgSetting.setTimeStamp(scanFileTime);
10599
10600        pkgSetting.pkg = pkg;
10601        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10602        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10603            pkgSetting.versionCode = pkg.getLongVersionCode();
10604        }
10605        // Update volume if needed
10606        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10607        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10608            Slog.i(PackageManagerService.TAG,
10609                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10610                    + " package " + pkg.packageName
10611                    + " volume from " + pkgSetting.volumeUuid
10612                    + " to " + volumeUuid);
10613            pkgSetting.volumeUuid = volumeUuid;
10614        }
10615
10616        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10617    }
10618
10619    /**
10620     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10621     */
10622    private static boolean apkHasCode(String fileName) {
10623        StrictJarFile jarFile = null;
10624        try {
10625            jarFile = new StrictJarFile(fileName,
10626                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10627            return jarFile.findEntry("classes.dex") != null;
10628        } catch (IOException ignore) {
10629        } finally {
10630            try {
10631                if (jarFile != null) {
10632                    jarFile.close();
10633                }
10634            } catch (IOException ignore) {}
10635        }
10636        return false;
10637    }
10638
10639    /**
10640     * Enforces code policy for the package. This ensures that if an APK has
10641     * declared hasCode="true" in its manifest that the APK actually contains
10642     * code.
10643     *
10644     * @throws PackageManagerException If bytecode could not be found when it should exist
10645     */
10646    private static void assertCodePolicy(PackageParser.Package pkg)
10647            throws PackageManagerException {
10648        final boolean shouldHaveCode =
10649                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10650        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10651            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10652                    "Package " + pkg.baseCodePath + " code is missing");
10653        }
10654
10655        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10656            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10657                final boolean splitShouldHaveCode =
10658                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10659                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10660                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10661                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10662                }
10663            }
10664        }
10665    }
10666
10667    /**
10668     * Applies policy to the parsed package based upon the given policy flags.
10669     * Ensures the package is in a good state.
10670     * <p>
10671     * Implementation detail: This method must NOT have any side effect. It would
10672     * ideally be static, but, it requires locks to read system state.
10673     */
10674    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10675            final @ScanFlags int scanFlags) {
10676        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10677            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10678            if (pkg.applicationInfo.isDirectBootAware()) {
10679                // we're direct boot aware; set for all components
10680                for (PackageParser.Service s : pkg.services) {
10681                    s.info.encryptionAware = s.info.directBootAware = true;
10682                }
10683                for (PackageParser.Provider p : pkg.providers) {
10684                    p.info.encryptionAware = p.info.directBootAware = true;
10685                }
10686                for (PackageParser.Activity a : pkg.activities) {
10687                    a.info.encryptionAware = a.info.directBootAware = true;
10688                }
10689                for (PackageParser.Activity r : pkg.receivers) {
10690                    r.info.encryptionAware = r.info.directBootAware = true;
10691                }
10692            }
10693            if (compressedFileExists(pkg.codePath)) {
10694                pkg.isStub = true;
10695            }
10696        } else {
10697            // non system apps can't be flagged as core
10698            pkg.coreApp = false;
10699            // clear flags not applicable to regular apps
10700            pkg.applicationInfo.flags &=
10701                    ~ApplicationInfo.FLAG_PERSISTENT;
10702            pkg.applicationInfo.privateFlags &=
10703                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10704            pkg.applicationInfo.privateFlags &=
10705                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10706            // clear protected broadcasts
10707            pkg.protectedBroadcasts = null;
10708            // cap permission priorities
10709            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10710                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10711                    pkg.permissionGroups.get(i).info.priority = 0;
10712                }
10713            }
10714        }
10715        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10716            // ignore export request for single user receivers
10717            if (pkg.receivers != null) {
10718                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10719                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10720                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10721                        receiver.info.exported = false;
10722                    }
10723                }
10724            }
10725            // ignore export request for single user services
10726            if (pkg.services != null) {
10727                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10728                    final PackageParser.Service service = pkg.services.get(i);
10729                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10730                        service.info.exported = false;
10731                    }
10732                }
10733            }
10734            // ignore export request for single user providers
10735            if (pkg.providers != null) {
10736                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10737                    final PackageParser.Provider provider = pkg.providers.get(i);
10738                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10739                        provider.info.exported = false;
10740                    }
10741                }
10742            }
10743        }
10744
10745        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10746            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10747        }
10748
10749        if ((scanFlags & SCAN_AS_OEM) != 0) {
10750            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10751        }
10752
10753        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10754            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10755        }
10756
10757        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10758            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10759        }
10760
10761        if (!isSystemApp(pkg)) {
10762            // Only system apps can use these features.
10763            pkg.mOriginalPackages = null;
10764            pkg.mRealPackage = null;
10765            pkg.mAdoptPermissions = null;
10766        }
10767    }
10768
10769    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10770            throws PackageManagerException {
10771        if (object == null) {
10772            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10773        }
10774        return object;
10775    }
10776
10777    /**
10778     * Asserts the parsed package is valid according to the given policy. If the
10779     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10780     * <p>
10781     * Implementation detail: This method must NOT have any side effects. It would
10782     * ideally be static, but, it requires locks to read system state.
10783     *
10784     * @throws PackageManagerException If the package fails any of the validation checks
10785     */
10786    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10787            final @ScanFlags int scanFlags)
10788                    throws PackageManagerException {
10789        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10790            assertCodePolicy(pkg);
10791        }
10792
10793        if (pkg.applicationInfo.getCodePath() == null ||
10794                pkg.applicationInfo.getResourcePath() == null) {
10795            // Bail out. The resource and code paths haven't been set.
10796            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10797                    "Code and resource paths haven't been set correctly");
10798        }
10799
10800        // Make sure we're not adding any bogus keyset info
10801        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10802        ksms.assertScannedPackageValid(pkg);
10803
10804        synchronized (mPackages) {
10805            // The special "android" package can only be defined once
10806            if (pkg.packageName.equals("android")) {
10807                if (mAndroidApplication != null) {
10808                    Slog.w(TAG, "*************************************************");
10809                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10810                    Slog.w(TAG, " codePath=" + pkg.codePath);
10811                    Slog.w(TAG, "*************************************************");
10812                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10813                            "Core android package being redefined.  Skipping.");
10814                }
10815            }
10816
10817            // A package name must be unique; don't allow duplicates
10818            if (mPackages.containsKey(pkg.packageName)) {
10819                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10820                        "Application package " + pkg.packageName
10821                        + " already installed.  Skipping duplicate.");
10822            }
10823
10824            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10825                // Static libs have a synthetic package name containing the version
10826                // but we still want the base name to be unique.
10827                if (mPackages.containsKey(pkg.manifestPackageName)) {
10828                    throw new PackageManagerException(
10829                            "Duplicate static shared lib provider package");
10830                }
10831
10832                // Static shared libraries should have at least O target SDK
10833                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10834                    throw new PackageManagerException(
10835                            "Packages declaring static-shared libs must target O SDK or higher");
10836                }
10837
10838                // Package declaring static a shared lib cannot be instant apps
10839                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10840                    throw new PackageManagerException(
10841                            "Packages declaring static-shared libs cannot be instant apps");
10842                }
10843
10844                // Package declaring static a shared lib cannot be renamed since the package
10845                // name is synthetic and apps can't code around package manager internals.
10846                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10847                    throw new PackageManagerException(
10848                            "Packages declaring static-shared libs cannot be renamed");
10849                }
10850
10851                // Package declaring static a shared lib cannot declare child packages
10852                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10853                    throw new PackageManagerException(
10854                            "Packages declaring static-shared libs cannot have child packages");
10855                }
10856
10857                // Package declaring static a shared lib cannot declare dynamic libs
10858                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10859                    throw new PackageManagerException(
10860                            "Packages declaring static-shared libs cannot declare dynamic libs");
10861                }
10862
10863                // Package declaring static a shared lib cannot declare shared users
10864                if (pkg.mSharedUserId != null) {
10865                    throw new PackageManagerException(
10866                            "Packages declaring static-shared libs cannot declare shared users");
10867                }
10868
10869                // Static shared libs cannot declare activities
10870                if (!pkg.activities.isEmpty()) {
10871                    throw new PackageManagerException(
10872                            "Static shared libs cannot declare activities");
10873                }
10874
10875                // Static shared libs cannot declare services
10876                if (!pkg.services.isEmpty()) {
10877                    throw new PackageManagerException(
10878                            "Static shared libs cannot declare services");
10879                }
10880
10881                // Static shared libs cannot declare providers
10882                if (!pkg.providers.isEmpty()) {
10883                    throw new PackageManagerException(
10884                            "Static shared libs cannot declare content providers");
10885                }
10886
10887                // Static shared libs cannot declare receivers
10888                if (!pkg.receivers.isEmpty()) {
10889                    throw new PackageManagerException(
10890                            "Static shared libs cannot declare broadcast receivers");
10891                }
10892
10893                // Static shared libs cannot declare permission groups
10894                if (!pkg.permissionGroups.isEmpty()) {
10895                    throw new PackageManagerException(
10896                            "Static shared libs cannot declare permission groups");
10897                }
10898
10899                // Static shared libs cannot declare permissions
10900                if (!pkg.permissions.isEmpty()) {
10901                    throw new PackageManagerException(
10902                            "Static shared libs cannot declare permissions");
10903                }
10904
10905                // Static shared libs cannot declare protected broadcasts
10906                if (pkg.protectedBroadcasts != null) {
10907                    throw new PackageManagerException(
10908                            "Static shared libs cannot declare protected broadcasts");
10909                }
10910
10911                // Static shared libs cannot be overlay targets
10912                if (pkg.mOverlayTarget != null) {
10913                    throw new PackageManagerException(
10914                            "Static shared libs cannot be overlay targets");
10915                }
10916
10917                // The version codes must be ordered as lib versions
10918                long minVersionCode = Long.MIN_VALUE;
10919                long maxVersionCode = Long.MAX_VALUE;
10920
10921                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10922                        pkg.staticSharedLibName);
10923                if (versionedLib != null) {
10924                    final int versionCount = versionedLib.size();
10925                    for (int i = 0; i < versionCount; i++) {
10926                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10927                        final long libVersionCode = libInfo.getDeclaringPackage()
10928                                .getLongVersionCode();
10929                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10930                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10931                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10932                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10933                        } else {
10934                            minVersionCode = maxVersionCode = libVersionCode;
10935                            break;
10936                        }
10937                    }
10938                }
10939                if (pkg.getLongVersionCode() < minVersionCode
10940                        || pkg.getLongVersionCode() > maxVersionCode) {
10941                    throw new PackageManagerException("Static shared"
10942                            + " lib version codes must be ordered as lib versions");
10943                }
10944            }
10945
10946            // Only privileged apps and updated privileged apps can add child packages.
10947            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10948                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10949                    throw new PackageManagerException("Only privileged apps can add child "
10950                            + "packages. Ignoring package " + pkg.packageName);
10951                }
10952                final int childCount = pkg.childPackages.size();
10953                for (int i = 0; i < childCount; i++) {
10954                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10955                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10956                            childPkg.packageName)) {
10957                        throw new PackageManagerException("Can't override child of "
10958                                + "another disabled app. Ignoring package " + pkg.packageName);
10959                    }
10960                }
10961            }
10962
10963            // If we're only installing presumed-existing packages, require that the
10964            // scanned APK is both already known and at the path previously established
10965            // for it.  Previously unknown packages we pick up normally, but if we have an
10966            // a priori expectation about this package's install presence, enforce it.
10967            // With a singular exception for new system packages. When an OTA contains
10968            // a new system package, we allow the codepath to change from a system location
10969            // to the user-installed location. If we don't allow this change, any newer,
10970            // user-installed version of the application will be ignored.
10971            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10972                if (mExpectingBetter.containsKey(pkg.packageName)) {
10973                    logCriticalInfo(Log.WARN,
10974                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10975                } else {
10976                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10977                    if (known != null) {
10978                        if (DEBUG_PACKAGE_SCANNING) {
10979                            Log.d(TAG, "Examining " + pkg.codePath
10980                                    + " and requiring known paths " + known.codePathString
10981                                    + " & " + known.resourcePathString);
10982                        }
10983                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10984                                || !pkg.applicationInfo.getResourcePath().equals(
10985                                        known.resourcePathString)) {
10986                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10987                                    "Application package " + pkg.packageName
10988                                    + " found at " + pkg.applicationInfo.getCodePath()
10989                                    + " but expected at " + known.codePathString
10990                                    + "; ignoring.");
10991                        }
10992                    } else {
10993                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10994                                "Application package " + pkg.packageName
10995                                + " not found; ignoring.");
10996                    }
10997                }
10998            }
10999
11000            // Verify that this new package doesn't have any content providers
11001            // that conflict with existing packages.  Only do this if the
11002            // package isn't already installed, since we don't want to break
11003            // things that are installed.
11004            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11005                final int N = pkg.providers.size();
11006                int i;
11007                for (i=0; i<N; i++) {
11008                    PackageParser.Provider p = pkg.providers.get(i);
11009                    if (p.info.authority != null) {
11010                        String names[] = p.info.authority.split(";");
11011                        for (int j = 0; j < names.length; j++) {
11012                            if (mProvidersByAuthority.containsKey(names[j])) {
11013                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11014                                final String otherPackageName =
11015                                        ((other != null && other.getComponentName() != null) ?
11016                                                other.getComponentName().getPackageName() : "?");
11017                                throw new PackageManagerException(
11018                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11019                                        "Can't install because provider name " + names[j]
11020                                                + " (in package " + pkg.applicationInfo.packageName
11021                                                + ") is already used by " + otherPackageName);
11022                            }
11023                        }
11024                    }
11025                }
11026            }
11027
11028            // Verify that packages sharing a user with a privileged app are marked as privileged.
11029            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11030                SharedUserSetting sharedUserSetting = null;
11031                try {
11032                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11033                } catch (PackageManagerException ignore) {}
11034                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11035                    // Exempt SharedUsers signed with the platform key.
11036                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11037                    if ((platformPkgSetting.signatures.mSigningDetails
11038                            != PackageParser.SigningDetails.UNKNOWN)
11039                            && (compareSignatures(
11040                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11041                                    pkg.mSigningDetails.signatures)
11042                                            != PackageManager.SIGNATURE_MATCH)) {
11043                        throw new PackageManagerException("Apps that share a user with a " +
11044                                "privileged app must themselves be marked as privileged. " +
11045                                pkg.packageName + " shares privileged user " +
11046                                pkg.mSharedUserId + ".");
11047                    }
11048                }
11049            }
11050
11051            // Apply policies specific for runtime resource overlays (RROs).
11052            if (pkg.mOverlayTarget != null) {
11053                // System overlays have some restrictions on their use of the 'static' state.
11054                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11055                    // We are scanning a system overlay. This can be the first scan of the
11056                    // system/vendor/oem partition, or an update to the system overlay.
11057                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11058                        // This must be an update to a system overlay.
11059                        final PackageSetting previousPkg = assertNotNull(
11060                                mSettings.getPackageLPr(pkg.packageName),
11061                                "previous package state not present");
11062
11063                        // Static overlays cannot be updated.
11064                        if (previousPkg.pkg.mOverlayIsStatic) {
11065                            throw new PackageManagerException("Overlay " + pkg.packageName +
11066                                    " is static and cannot be upgraded.");
11067                        // Non-static overlays cannot be converted to static overlays.
11068                        } else if (pkg.mOverlayIsStatic) {
11069                            throw new PackageManagerException("Overlay " + pkg.packageName +
11070                                    " cannot be upgraded into a static overlay.");
11071                        }
11072                    }
11073                } else {
11074                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11075                    if (pkg.mOverlayIsStatic) {
11076                        throw new PackageManagerException("Overlay " + pkg.packageName +
11077                                " is static but not pre-installed.");
11078                    }
11079
11080                    // The only case where we allow installation of a non-system overlay is when
11081                    // its signature is signed with the platform certificate.
11082                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11083                    if ((platformPkgSetting.signatures.mSigningDetails
11084                            != PackageParser.SigningDetails.UNKNOWN)
11085                            && (compareSignatures(
11086                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11087                                    pkg.mSigningDetails.signatures)
11088                                            != PackageManager.SIGNATURE_MATCH)) {
11089                        throw new PackageManagerException("Overlay " + pkg.packageName +
11090                                " must be signed with the platform certificate.");
11091                    }
11092                }
11093            }
11094        }
11095    }
11096
11097    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11098            int type, String declaringPackageName, long declaringVersionCode) {
11099        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11100        if (versionedLib == null) {
11101            versionedLib = new LongSparseArray<>();
11102            mSharedLibraries.put(name, versionedLib);
11103            if (type == SharedLibraryInfo.TYPE_STATIC) {
11104                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11105            }
11106        } else if (versionedLib.indexOfKey(version) >= 0) {
11107            return false;
11108        }
11109        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11110                version, type, declaringPackageName, declaringVersionCode);
11111        versionedLib.put(version, libEntry);
11112        return true;
11113    }
11114
11115    private boolean removeSharedLibraryLPw(String name, long version) {
11116        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11117        if (versionedLib == null) {
11118            return false;
11119        }
11120        final int libIdx = versionedLib.indexOfKey(version);
11121        if (libIdx < 0) {
11122            return false;
11123        }
11124        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11125        versionedLib.remove(version);
11126        if (versionedLib.size() <= 0) {
11127            mSharedLibraries.remove(name);
11128            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11129                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11130                        .getPackageName());
11131            }
11132        }
11133        return true;
11134    }
11135
11136    /**
11137     * Adds a scanned package to the system. When this method is finished, the package will
11138     * be available for query, resolution, etc...
11139     */
11140    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11141            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11142        final String pkgName = pkg.packageName;
11143        if (mCustomResolverComponentName != null &&
11144                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11145            setUpCustomResolverActivity(pkg);
11146        }
11147
11148        if (pkg.packageName.equals("android")) {
11149            synchronized (mPackages) {
11150                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11151                    // Set up information for our fall-back user intent resolution activity.
11152                    mPlatformPackage = pkg;
11153                    pkg.mVersionCode = mSdkVersion;
11154                    pkg.mVersionCodeMajor = 0;
11155                    mAndroidApplication = pkg.applicationInfo;
11156                    if (!mResolverReplaced) {
11157                        mResolveActivity.applicationInfo = mAndroidApplication;
11158                        mResolveActivity.name = ResolverActivity.class.getName();
11159                        mResolveActivity.packageName = mAndroidApplication.packageName;
11160                        mResolveActivity.processName = "system:ui";
11161                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11162                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11163                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11164                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11165                        mResolveActivity.exported = true;
11166                        mResolveActivity.enabled = true;
11167                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11168                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11169                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11170                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11171                                | ActivityInfo.CONFIG_ORIENTATION
11172                                | ActivityInfo.CONFIG_KEYBOARD
11173                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11174                        mResolveInfo.activityInfo = mResolveActivity;
11175                        mResolveInfo.priority = 0;
11176                        mResolveInfo.preferredOrder = 0;
11177                        mResolveInfo.match = 0;
11178                        mResolveComponentName = new ComponentName(
11179                                mAndroidApplication.packageName, mResolveActivity.name);
11180                    }
11181                }
11182            }
11183        }
11184
11185        ArrayList<PackageParser.Package> clientLibPkgs = null;
11186        // writer
11187        synchronized (mPackages) {
11188            boolean hasStaticSharedLibs = false;
11189
11190            // Any app can add new static shared libraries
11191            if (pkg.staticSharedLibName != null) {
11192                // Static shared libs don't allow renaming as they have synthetic package
11193                // names to allow install of multiple versions, so use name from manifest.
11194                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11195                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11196                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11197                    hasStaticSharedLibs = true;
11198                } else {
11199                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11200                                + pkg.staticSharedLibName + " already exists; skipping");
11201                }
11202                // Static shared libs cannot be updated once installed since they
11203                // use synthetic package name which includes the version code, so
11204                // not need to update other packages's shared lib dependencies.
11205            }
11206
11207            if (!hasStaticSharedLibs
11208                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11209                // Only system apps can add new dynamic shared libraries.
11210                if (pkg.libraryNames != null) {
11211                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11212                        String name = pkg.libraryNames.get(i);
11213                        boolean allowed = false;
11214                        if (pkg.isUpdatedSystemApp()) {
11215                            // New library entries can only be added through the
11216                            // system image.  This is important to get rid of a lot
11217                            // of nasty edge cases: for example if we allowed a non-
11218                            // system update of the app to add a library, then uninstalling
11219                            // the update would make the library go away, and assumptions
11220                            // we made such as through app install filtering would now
11221                            // have allowed apps on the device which aren't compatible
11222                            // with it.  Better to just have the restriction here, be
11223                            // conservative, and create many fewer cases that can negatively
11224                            // impact the user experience.
11225                            final PackageSetting sysPs = mSettings
11226                                    .getDisabledSystemPkgLPr(pkg.packageName);
11227                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11228                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11229                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11230                                        allowed = true;
11231                                        break;
11232                                    }
11233                                }
11234                            }
11235                        } else {
11236                            allowed = true;
11237                        }
11238                        if (allowed) {
11239                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11240                                    SharedLibraryInfo.VERSION_UNDEFINED,
11241                                    SharedLibraryInfo.TYPE_DYNAMIC,
11242                                    pkg.packageName, pkg.getLongVersionCode())) {
11243                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11244                                        + name + " already exists; skipping");
11245                            }
11246                        } else {
11247                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11248                                    + name + " that is not declared on system image; skipping");
11249                        }
11250                    }
11251
11252                    if ((scanFlags & SCAN_BOOTING) == 0) {
11253                        // If we are not booting, we need to update any applications
11254                        // that are clients of our shared library.  If we are booting,
11255                        // this will all be done once the scan is complete.
11256                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11257                    }
11258                }
11259            }
11260        }
11261
11262        if ((scanFlags & SCAN_BOOTING) != 0) {
11263            // No apps can run during boot scan, so they don't need to be frozen
11264        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11265            // Caller asked to not kill app, so it's probably not frozen
11266        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11267            // Caller asked us to ignore frozen check for some reason; they
11268            // probably didn't know the package name
11269        } else {
11270            // We're doing major surgery on this package, so it better be frozen
11271            // right now to keep it from launching
11272            checkPackageFrozen(pkgName);
11273        }
11274
11275        // Also need to kill any apps that are dependent on the library.
11276        if (clientLibPkgs != null) {
11277            for (int i=0; i<clientLibPkgs.size(); i++) {
11278                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11279                killApplication(clientPkg.applicationInfo.packageName,
11280                        clientPkg.applicationInfo.uid, "update lib");
11281            }
11282        }
11283
11284        // writer
11285        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11286
11287        synchronized (mPackages) {
11288            // We don't expect installation to fail beyond this point
11289
11290            // Add the new setting to mSettings
11291            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11292            // Add the new setting to mPackages
11293            mPackages.put(pkg.applicationInfo.packageName, pkg);
11294            // Make sure we don't accidentally delete its data.
11295            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11296            while (iter.hasNext()) {
11297                PackageCleanItem item = iter.next();
11298                if (pkgName.equals(item.packageName)) {
11299                    iter.remove();
11300                }
11301            }
11302
11303            // Add the package's KeySets to the global KeySetManagerService
11304            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11305            ksms.addScannedPackageLPw(pkg);
11306
11307            int N = pkg.providers.size();
11308            StringBuilder r = null;
11309            int i;
11310            for (i=0; i<N; i++) {
11311                PackageParser.Provider p = pkg.providers.get(i);
11312                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11313                        p.info.processName);
11314                mProviders.addProvider(p);
11315                p.syncable = p.info.isSyncable;
11316                if (p.info.authority != null) {
11317                    String names[] = p.info.authority.split(";");
11318                    p.info.authority = null;
11319                    for (int j = 0; j < names.length; j++) {
11320                        if (j == 1 && p.syncable) {
11321                            // We only want the first authority for a provider to possibly be
11322                            // syncable, so if we already added this provider using a different
11323                            // authority clear the syncable flag. We copy the provider before
11324                            // changing it because the mProviders object contains a reference
11325                            // to a provider that we don't want to change.
11326                            // Only do this for the second authority since the resulting provider
11327                            // object can be the same for all future authorities for this provider.
11328                            p = new PackageParser.Provider(p);
11329                            p.syncable = false;
11330                        }
11331                        if (!mProvidersByAuthority.containsKey(names[j])) {
11332                            mProvidersByAuthority.put(names[j], p);
11333                            if (p.info.authority == null) {
11334                                p.info.authority = names[j];
11335                            } else {
11336                                p.info.authority = p.info.authority + ";" + names[j];
11337                            }
11338                            if (DEBUG_PACKAGE_SCANNING) {
11339                                if (chatty)
11340                                    Log.d(TAG, "Registered content provider: " + names[j]
11341                                            + ", className = " + p.info.name + ", isSyncable = "
11342                                            + p.info.isSyncable);
11343                            }
11344                        } else {
11345                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11346                            Slog.w(TAG, "Skipping provider name " + names[j] +
11347                                    " (in package " + pkg.applicationInfo.packageName +
11348                                    "): name already used by "
11349                                    + ((other != null && other.getComponentName() != null)
11350                                            ? other.getComponentName().getPackageName() : "?"));
11351                        }
11352                    }
11353                }
11354                if (chatty) {
11355                    if (r == null) {
11356                        r = new StringBuilder(256);
11357                    } else {
11358                        r.append(' ');
11359                    }
11360                    r.append(p.info.name);
11361                }
11362            }
11363            if (r != null) {
11364                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11365            }
11366
11367            N = pkg.services.size();
11368            r = null;
11369            for (i=0; i<N; i++) {
11370                PackageParser.Service s = pkg.services.get(i);
11371                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11372                        s.info.processName);
11373                mServices.addService(s);
11374                if (chatty) {
11375                    if (r == null) {
11376                        r = new StringBuilder(256);
11377                    } else {
11378                        r.append(' ');
11379                    }
11380                    r.append(s.info.name);
11381                }
11382            }
11383            if (r != null) {
11384                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11385            }
11386
11387            N = pkg.receivers.size();
11388            r = null;
11389            for (i=0; i<N; i++) {
11390                PackageParser.Activity a = pkg.receivers.get(i);
11391                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11392                        a.info.processName);
11393                mReceivers.addActivity(a, "receiver");
11394                if (chatty) {
11395                    if (r == null) {
11396                        r = new StringBuilder(256);
11397                    } else {
11398                        r.append(' ');
11399                    }
11400                    r.append(a.info.name);
11401                }
11402            }
11403            if (r != null) {
11404                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11405            }
11406
11407            N = pkg.activities.size();
11408            r = null;
11409            for (i=0; i<N; i++) {
11410                PackageParser.Activity a = pkg.activities.get(i);
11411                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11412                        a.info.processName);
11413                mActivities.addActivity(a, "activity");
11414                if (chatty) {
11415                    if (r == null) {
11416                        r = new StringBuilder(256);
11417                    } else {
11418                        r.append(' ');
11419                    }
11420                    r.append(a.info.name);
11421                }
11422            }
11423            if (r != null) {
11424                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11425            }
11426
11427            // Don't allow ephemeral applications to define new permissions groups.
11428            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11429                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11430                        + " ignored: instant apps cannot define new permission groups.");
11431            } else {
11432                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11433            }
11434
11435            // Don't allow ephemeral applications to define new permissions.
11436            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11437                Slog.w(TAG, "Permissions from package " + pkg.packageName
11438                        + " ignored: instant apps cannot define new permissions.");
11439            } else {
11440                mPermissionManager.addAllPermissions(pkg, chatty);
11441            }
11442
11443            N = pkg.instrumentation.size();
11444            r = null;
11445            for (i=0; i<N; i++) {
11446                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11447                a.info.packageName = pkg.applicationInfo.packageName;
11448                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11449                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11450                a.info.splitNames = pkg.splitNames;
11451                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11452                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11453                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11454                a.info.dataDir = pkg.applicationInfo.dataDir;
11455                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11456                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11457                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11458                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11459                mInstrumentation.put(a.getComponentName(), a);
11460                if (chatty) {
11461                    if (r == null) {
11462                        r = new StringBuilder(256);
11463                    } else {
11464                        r.append(' ');
11465                    }
11466                    r.append(a.info.name);
11467                }
11468            }
11469            if (r != null) {
11470                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11471            }
11472
11473            if (pkg.protectedBroadcasts != null) {
11474                N = pkg.protectedBroadcasts.size();
11475                synchronized (mProtectedBroadcasts) {
11476                    for (i = 0; i < N; i++) {
11477                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11478                    }
11479                }
11480            }
11481        }
11482
11483        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11484    }
11485
11486    /**
11487     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11488     * is derived purely on the basis of the contents of {@code scanFile} and
11489     * {@code cpuAbiOverride}.
11490     *
11491     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11492     */
11493    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11494            boolean extractLibs)
11495                    throws PackageManagerException {
11496        // Give ourselves some initial paths; we'll come back for another
11497        // pass once we've determined ABI below.
11498        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11499
11500        // We would never need to extract libs for forward-locked and external packages,
11501        // since the container service will do it for us. We shouldn't attempt to
11502        // extract libs from system app when it was not updated.
11503        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11504                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11505            extractLibs = false;
11506        }
11507
11508        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11509        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11510
11511        NativeLibraryHelper.Handle handle = null;
11512        try {
11513            handle = NativeLibraryHelper.Handle.create(pkg);
11514            // TODO(multiArch): This can be null for apps that didn't go through the
11515            // usual installation process. We can calculate it again, like we
11516            // do during install time.
11517            //
11518            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11519            // unnecessary.
11520            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11521
11522            // Null out the abis so that they can be recalculated.
11523            pkg.applicationInfo.primaryCpuAbi = null;
11524            pkg.applicationInfo.secondaryCpuAbi = null;
11525            if (isMultiArch(pkg.applicationInfo)) {
11526                // Warn if we've set an abiOverride for multi-lib packages..
11527                // By definition, we need to copy both 32 and 64 bit libraries for
11528                // such packages.
11529                if (pkg.cpuAbiOverride != null
11530                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11531                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11532                }
11533
11534                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11535                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11536                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11537                    if (extractLibs) {
11538                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11539                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11540                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11541                                useIsaSpecificSubdirs);
11542                    } else {
11543                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11544                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11545                    }
11546                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11547                }
11548
11549                // Shared library native code should be in the APK zip aligned
11550                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11551                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11552                            "Shared library native lib extraction not supported");
11553                }
11554
11555                maybeThrowExceptionForMultiArchCopy(
11556                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11557
11558                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11559                    if (extractLibs) {
11560                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11561                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11562                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11563                                useIsaSpecificSubdirs);
11564                    } else {
11565                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11566                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11567                    }
11568                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11569                }
11570
11571                maybeThrowExceptionForMultiArchCopy(
11572                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11573
11574                if (abi64 >= 0) {
11575                    // Shared library native libs should be in the APK zip aligned
11576                    if (extractLibs && pkg.isLibrary()) {
11577                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11578                                "Shared library native lib extraction not supported");
11579                    }
11580                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11581                }
11582
11583                if (abi32 >= 0) {
11584                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11585                    if (abi64 >= 0) {
11586                        if (pkg.use32bitAbi) {
11587                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11588                            pkg.applicationInfo.primaryCpuAbi = abi;
11589                        } else {
11590                            pkg.applicationInfo.secondaryCpuAbi = abi;
11591                        }
11592                    } else {
11593                        pkg.applicationInfo.primaryCpuAbi = abi;
11594                    }
11595                }
11596            } else {
11597                String[] abiList = (cpuAbiOverride != null) ?
11598                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11599
11600                // Enable gross and lame hacks for apps that are built with old
11601                // SDK tools. We must scan their APKs for renderscript bitcode and
11602                // not launch them if it's present. Don't bother checking on devices
11603                // that don't have 64 bit support.
11604                boolean needsRenderScriptOverride = false;
11605                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11606                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11607                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11608                    needsRenderScriptOverride = true;
11609                }
11610
11611                final int copyRet;
11612                if (extractLibs) {
11613                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11614                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11615                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11616                } else {
11617                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11618                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11619                }
11620                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11621
11622                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11623                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11624                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11625                }
11626
11627                if (copyRet >= 0) {
11628                    // Shared libraries that have native libs must be multi-architecture
11629                    if (pkg.isLibrary()) {
11630                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11631                                "Shared library with native libs must be multiarch");
11632                    }
11633                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11634                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11635                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11636                } else if (needsRenderScriptOverride) {
11637                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11638                }
11639            }
11640        } catch (IOException ioe) {
11641            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11642        } finally {
11643            IoUtils.closeQuietly(handle);
11644        }
11645
11646        // Now that we've calculated the ABIs and determined if it's an internal app,
11647        // we will go ahead and populate the nativeLibraryPath.
11648        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11649    }
11650
11651    /**
11652     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11653     * i.e, so that all packages can be run inside a single process if required.
11654     *
11655     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11656     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11657     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11658     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11659     * updating a package that belongs to a shared user.
11660     *
11661     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11662     * adds unnecessary complexity.
11663     */
11664    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11665            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11666        List<String> changedAbiCodePath = null;
11667        String requiredInstructionSet = null;
11668        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11669            requiredInstructionSet = VMRuntime.getInstructionSet(
11670                     scannedPackage.applicationInfo.primaryCpuAbi);
11671        }
11672
11673        PackageSetting requirer = null;
11674        for (PackageSetting ps : packagesForUser) {
11675            // If packagesForUser contains scannedPackage, we skip it. This will happen
11676            // when scannedPackage is an update of an existing package. Without this check,
11677            // we will never be able to change the ABI of any package belonging to a shared
11678            // user, even if it's compatible with other packages.
11679            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11680                if (ps.primaryCpuAbiString == null) {
11681                    continue;
11682                }
11683
11684                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11685                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11686                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11687                    // this but there's not much we can do.
11688                    String errorMessage = "Instruction set mismatch, "
11689                            + ((requirer == null) ? "[caller]" : requirer)
11690                            + " requires " + requiredInstructionSet + " whereas " + ps
11691                            + " requires " + instructionSet;
11692                    Slog.w(TAG, errorMessage);
11693                }
11694
11695                if (requiredInstructionSet == null) {
11696                    requiredInstructionSet = instructionSet;
11697                    requirer = ps;
11698                }
11699            }
11700        }
11701
11702        if (requiredInstructionSet != null) {
11703            String adjustedAbi;
11704            if (requirer != null) {
11705                // requirer != null implies that either scannedPackage was null or that scannedPackage
11706                // did not require an ABI, in which case we have to adjust scannedPackage to match
11707                // the ABI of the set (which is the same as requirer's ABI)
11708                adjustedAbi = requirer.primaryCpuAbiString;
11709                if (scannedPackage != null) {
11710                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11711                }
11712            } else {
11713                // requirer == null implies that we're updating all ABIs in the set to
11714                // match scannedPackage.
11715                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11716            }
11717
11718            for (PackageSetting ps : packagesForUser) {
11719                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11720                    if (ps.primaryCpuAbiString != null) {
11721                        continue;
11722                    }
11723
11724                    ps.primaryCpuAbiString = adjustedAbi;
11725                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11726                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11727                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11728                        if (DEBUG_ABI_SELECTION) {
11729                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11730                                    + " (requirer="
11731                                    + (requirer != null ? requirer.pkg : "null")
11732                                    + ", scannedPackage="
11733                                    + (scannedPackage != null ? scannedPackage : "null")
11734                                    + ")");
11735                        }
11736                        if (changedAbiCodePath == null) {
11737                            changedAbiCodePath = new ArrayList<>();
11738                        }
11739                        changedAbiCodePath.add(ps.codePathString);
11740                    }
11741                }
11742            }
11743        }
11744        return changedAbiCodePath;
11745    }
11746
11747    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11748        synchronized (mPackages) {
11749            mResolverReplaced = true;
11750            // Set up information for custom user intent resolution activity.
11751            mResolveActivity.applicationInfo = pkg.applicationInfo;
11752            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11753            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11754            mResolveActivity.processName = pkg.applicationInfo.packageName;
11755            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11756            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11757                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11758            mResolveActivity.theme = 0;
11759            mResolveActivity.exported = true;
11760            mResolveActivity.enabled = true;
11761            mResolveInfo.activityInfo = mResolveActivity;
11762            mResolveInfo.priority = 0;
11763            mResolveInfo.preferredOrder = 0;
11764            mResolveInfo.match = 0;
11765            mResolveComponentName = mCustomResolverComponentName;
11766            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11767                    mResolveComponentName);
11768        }
11769    }
11770
11771    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11772        if (installerActivity == null) {
11773            if (DEBUG_INSTANT) {
11774                Slog.d(TAG, "Clear ephemeral installer activity");
11775            }
11776            mInstantAppInstallerActivity = null;
11777            return;
11778        }
11779
11780        if (DEBUG_INSTANT) {
11781            Slog.d(TAG, "Set ephemeral installer activity: "
11782                    + installerActivity.getComponentName());
11783        }
11784        // Set up information for ephemeral installer activity
11785        mInstantAppInstallerActivity = installerActivity;
11786        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11787                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11788        mInstantAppInstallerActivity.exported = true;
11789        mInstantAppInstallerActivity.enabled = true;
11790        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11791        mInstantAppInstallerInfo.priority = 1;
11792        mInstantAppInstallerInfo.preferredOrder = 1;
11793        mInstantAppInstallerInfo.isDefault = true;
11794        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11795                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11796    }
11797
11798    private static String calculateBundledApkRoot(final String codePathString) {
11799        final File codePath = new File(codePathString);
11800        final File codeRoot;
11801        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11802            codeRoot = Environment.getRootDirectory();
11803        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11804            codeRoot = Environment.getOemDirectory();
11805        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11806            codeRoot = Environment.getVendorDirectory();
11807        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11808            codeRoot = Environment.getProductDirectory();
11809        } else {
11810            // Unrecognized code path; take its top real segment as the apk root:
11811            // e.g. /something/app/blah.apk => /something
11812            try {
11813                File f = codePath.getCanonicalFile();
11814                File parent = f.getParentFile();    // non-null because codePath is a file
11815                File tmp;
11816                while ((tmp = parent.getParentFile()) != null) {
11817                    f = parent;
11818                    parent = tmp;
11819                }
11820                codeRoot = f;
11821                Slog.w(TAG, "Unrecognized code path "
11822                        + codePath + " - using " + codeRoot);
11823            } catch (IOException e) {
11824                // Can't canonicalize the code path -- shenanigans?
11825                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11826                return Environment.getRootDirectory().getPath();
11827            }
11828        }
11829        return codeRoot.getPath();
11830    }
11831
11832    /**
11833     * Derive and set the location of native libraries for the given package,
11834     * which varies depending on where and how the package was installed.
11835     */
11836    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11837        final ApplicationInfo info = pkg.applicationInfo;
11838        final String codePath = pkg.codePath;
11839        final File codeFile = new File(codePath);
11840        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11841        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11842
11843        info.nativeLibraryRootDir = null;
11844        info.nativeLibraryRootRequiresIsa = false;
11845        info.nativeLibraryDir = null;
11846        info.secondaryNativeLibraryDir = null;
11847
11848        if (isApkFile(codeFile)) {
11849            // Monolithic install
11850            if (bundledApp) {
11851                // If "/system/lib64/apkname" exists, assume that is the per-package
11852                // native library directory to use; otherwise use "/system/lib/apkname".
11853                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11854                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11855                        getPrimaryInstructionSet(info));
11856
11857                // This is a bundled system app so choose the path based on the ABI.
11858                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11859                // is just the default path.
11860                final String apkName = deriveCodePathName(codePath);
11861                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11862                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11863                        apkName).getAbsolutePath();
11864
11865                if (info.secondaryCpuAbi != null) {
11866                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11867                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11868                            secondaryLibDir, apkName).getAbsolutePath();
11869                }
11870            } else if (asecApp) {
11871                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11872                        .getAbsolutePath();
11873            } else {
11874                final String apkName = deriveCodePathName(codePath);
11875                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11876                        .getAbsolutePath();
11877            }
11878
11879            info.nativeLibraryRootRequiresIsa = false;
11880            info.nativeLibraryDir = info.nativeLibraryRootDir;
11881        } else {
11882            // Cluster install
11883            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11884            info.nativeLibraryRootRequiresIsa = true;
11885
11886            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11887                    getPrimaryInstructionSet(info)).getAbsolutePath();
11888
11889            if (info.secondaryCpuAbi != null) {
11890                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11891                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11892            }
11893        }
11894    }
11895
11896    /**
11897     * Calculate the abis and roots for a bundled app. These can uniquely
11898     * be determined from the contents of the system partition, i.e whether
11899     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11900     * of this information, and instead assume that the system was built
11901     * sensibly.
11902     */
11903    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11904                                           PackageSetting pkgSetting) {
11905        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11906
11907        // If "/system/lib64/apkname" exists, assume that is the per-package
11908        // native library directory to use; otherwise use "/system/lib/apkname".
11909        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11910        setBundledAppAbi(pkg, apkRoot, apkName);
11911        // pkgSetting might be null during rescan following uninstall of updates
11912        // to a bundled app, so accommodate that possibility.  The settings in
11913        // that case will be established later from the parsed package.
11914        //
11915        // If the settings aren't null, sync them up with what we've just derived.
11916        // note that apkRoot isn't stored in the package settings.
11917        if (pkgSetting != null) {
11918            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11919            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11920        }
11921    }
11922
11923    /**
11924     * Deduces the ABI of a bundled app and sets the relevant fields on the
11925     * parsed pkg object.
11926     *
11927     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11928     *        under which system libraries are installed.
11929     * @param apkName the name of the installed package.
11930     */
11931    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11932        final File codeFile = new File(pkg.codePath);
11933
11934        final boolean has64BitLibs;
11935        final boolean has32BitLibs;
11936        if (isApkFile(codeFile)) {
11937            // Monolithic install
11938            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11939            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11940        } else {
11941            // Cluster install
11942            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11943            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11944                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11945                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11946                has64BitLibs = (new File(rootDir, isa)).exists();
11947            } else {
11948                has64BitLibs = false;
11949            }
11950            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11951                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11952                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11953                has32BitLibs = (new File(rootDir, isa)).exists();
11954            } else {
11955                has32BitLibs = false;
11956            }
11957        }
11958
11959        if (has64BitLibs && !has32BitLibs) {
11960            // The package has 64 bit libs, but not 32 bit libs. Its primary
11961            // ABI should be 64 bit. We can safely assume here that the bundled
11962            // native libraries correspond to the most preferred ABI in the list.
11963
11964            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11965            pkg.applicationInfo.secondaryCpuAbi = null;
11966        } else if (has32BitLibs && !has64BitLibs) {
11967            // The package has 32 bit libs but not 64 bit libs. Its primary
11968            // ABI should be 32 bit.
11969
11970            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11971            pkg.applicationInfo.secondaryCpuAbi = null;
11972        } else if (has32BitLibs && has64BitLibs) {
11973            // The application has both 64 and 32 bit bundled libraries. We check
11974            // here that the app declares multiArch support, and warn if it doesn't.
11975            //
11976            // We will be lenient here and record both ABIs. The primary will be the
11977            // ABI that's higher on the list, i.e, a device that's configured to prefer
11978            // 64 bit apps will see a 64 bit primary ABI,
11979
11980            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11981                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11982            }
11983
11984            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11985                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11986                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11987            } else {
11988                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11989                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11990            }
11991        } else {
11992            pkg.applicationInfo.primaryCpuAbi = null;
11993            pkg.applicationInfo.secondaryCpuAbi = null;
11994        }
11995    }
11996
11997    private void killApplication(String pkgName, int appId, String reason) {
11998        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11999    }
12000
12001    private void killApplication(String pkgName, int appId, int userId, String reason) {
12002        // Request the ActivityManager to kill the process(only for existing packages)
12003        // so that we do not end up in a confused state while the user is still using the older
12004        // version of the application while the new one gets installed.
12005        final long token = Binder.clearCallingIdentity();
12006        try {
12007            IActivityManager am = ActivityManager.getService();
12008            if (am != null) {
12009                try {
12010                    am.killApplication(pkgName, appId, userId, reason);
12011                } catch (RemoteException e) {
12012                }
12013            }
12014        } finally {
12015            Binder.restoreCallingIdentity(token);
12016        }
12017    }
12018
12019    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12020        // Remove the parent package setting
12021        PackageSetting ps = (PackageSetting) pkg.mExtras;
12022        if (ps != null) {
12023            removePackageLI(ps, chatty);
12024        }
12025        // Remove the child package setting
12026        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12027        for (int i = 0; i < childCount; i++) {
12028            PackageParser.Package childPkg = pkg.childPackages.get(i);
12029            ps = (PackageSetting) childPkg.mExtras;
12030            if (ps != null) {
12031                removePackageLI(ps, chatty);
12032            }
12033        }
12034    }
12035
12036    void removePackageLI(PackageSetting ps, boolean chatty) {
12037        if (DEBUG_INSTALL) {
12038            if (chatty)
12039                Log.d(TAG, "Removing package " + ps.name);
12040        }
12041
12042        // writer
12043        synchronized (mPackages) {
12044            mPackages.remove(ps.name);
12045            final PackageParser.Package pkg = ps.pkg;
12046            if (pkg != null) {
12047                cleanPackageDataStructuresLILPw(pkg, chatty);
12048            }
12049        }
12050    }
12051
12052    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12053        if (DEBUG_INSTALL) {
12054            if (chatty)
12055                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12056        }
12057
12058        // writer
12059        synchronized (mPackages) {
12060            // Remove the parent package
12061            mPackages.remove(pkg.applicationInfo.packageName);
12062            cleanPackageDataStructuresLILPw(pkg, chatty);
12063
12064            // Remove the child packages
12065            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12066            for (int i = 0; i < childCount; i++) {
12067                PackageParser.Package childPkg = pkg.childPackages.get(i);
12068                mPackages.remove(childPkg.applicationInfo.packageName);
12069                cleanPackageDataStructuresLILPw(childPkg, chatty);
12070            }
12071        }
12072    }
12073
12074    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12075        int N = pkg.providers.size();
12076        StringBuilder r = null;
12077        int i;
12078        for (i=0; i<N; i++) {
12079            PackageParser.Provider p = pkg.providers.get(i);
12080            mProviders.removeProvider(p);
12081            if (p.info.authority == null) {
12082
12083                /* There was another ContentProvider with this authority when
12084                 * this app was installed so this authority is null,
12085                 * Ignore it as we don't have to unregister the provider.
12086                 */
12087                continue;
12088            }
12089            String names[] = p.info.authority.split(";");
12090            for (int j = 0; j < names.length; j++) {
12091                if (mProvidersByAuthority.get(names[j]) == p) {
12092                    mProvidersByAuthority.remove(names[j]);
12093                    if (DEBUG_REMOVE) {
12094                        if (chatty)
12095                            Log.d(TAG, "Unregistered content provider: " + names[j]
12096                                    + ", className = " + p.info.name + ", isSyncable = "
12097                                    + p.info.isSyncable);
12098                    }
12099                }
12100            }
12101            if (DEBUG_REMOVE && chatty) {
12102                if (r == null) {
12103                    r = new StringBuilder(256);
12104                } else {
12105                    r.append(' ');
12106                }
12107                r.append(p.info.name);
12108            }
12109        }
12110        if (r != null) {
12111            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12112        }
12113
12114        N = pkg.services.size();
12115        r = null;
12116        for (i=0; i<N; i++) {
12117            PackageParser.Service s = pkg.services.get(i);
12118            mServices.removeService(s);
12119            if (chatty) {
12120                if (r == null) {
12121                    r = new StringBuilder(256);
12122                } else {
12123                    r.append(' ');
12124                }
12125                r.append(s.info.name);
12126            }
12127        }
12128        if (r != null) {
12129            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12130        }
12131
12132        N = pkg.receivers.size();
12133        r = null;
12134        for (i=0; i<N; i++) {
12135            PackageParser.Activity a = pkg.receivers.get(i);
12136            mReceivers.removeActivity(a, "receiver");
12137            if (DEBUG_REMOVE && chatty) {
12138                if (r == null) {
12139                    r = new StringBuilder(256);
12140                } else {
12141                    r.append(' ');
12142                }
12143                r.append(a.info.name);
12144            }
12145        }
12146        if (r != null) {
12147            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12148        }
12149
12150        N = pkg.activities.size();
12151        r = null;
12152        for (i=0; i<N; i++) {
12153            PackageParser.Activity a = pkg.activities.get(i);
12154            mActivities.removeActivity(a, "activity");
12155            if (DEBUG_REMOVE && chatty) {
12156                if (r == null) {
12157                    r = new StringBuilder(256);
12158                } else {
12159                    r.append(' ');
12160                }
12161                r.append(a.info.name);
12162            }
12163        }
12164        if (r != null) {
12165            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12166        }
12167
12168        mPermissionManager.removeAllPermissions(pkg, chatty);
12169
12170        N = pkg.instrumentation.size();
12171        r = null;
12172        for (i=0; i<N; i++) {
12173            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12174            mInstrumentation.remove(a.getComponentName());
12175            if (DEBUG_REMOVE && chatty) {
12176                if (r == null) {
12177                    r = new StringBuilder(256);
12178                } else {
12179                    r.append(' ');
12180                }
12181                r.append(a.info.name);
12182            }
12183        }
12184        if (r != null) {
12185            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12186        }
12187
12188        r = null;
12189        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12190            // Only system apps can hold shared libraries.
12191            if (pkg.libraryNames != null) {
12192                for (i = 0; i < pkg.libraryNames.size(); i++) {
12193                    String name = pkg.libraryNames.get(i);
12194                    if (removeSharedLibraryLPw(name, 0)) {
12195                        if (DEBUG_REMOVE && chatty) {
12196                            if (r == null) {
12197                                r = new StringBuilder(256);
12198                            } else {
12199                                r.append(' ');
12200                            }
12201                            r.append(name);
12202                        }
12203                    }
12204                }
12205            }
12206        }
12207
12208        r = null;
12209
12210        // Any package can hold static shared libraries.
12211        if (pkg.staticSharedLibName != null) {
12212            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12213                if (DEBUG_REMOVE && chatty) {
12214                    if (r == null) {
12215                        r = new StringBuilder(256);
12216                    } else {
12217                        r.append(' ');
12218                    }
12219                    r.append(pkg.staticSharedLibName);
12220                }
12221            }
12222        }
12223
12224        if (r != null) {
12225            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12226        }
12227    }
12228
12229
12230    final class ActivityIntentResolver
12231            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12232        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12233                boolean defaultOnly, int userId) {
12234            if (!sUserManager.exists(userId)) return null;
12235            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12236            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12237        }
12238
12239        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12240                int userId) {
12241            if (!sUserManager.exists(userId)) return null;
12242            mFlags = flags;
12243            return super.queryIntent(intent, resolvedType,
12244                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12245                    userId);
12246        }
12247
12248        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12249                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12250            if (!sUserManager.exists(userId)) return null;
12251            if (packageActivities == null) {
12252                return null;
12253            }
12254            mFlags = flags;
12255            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12256            final int N = packageActivities.size();
12257            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12258                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12259
12260            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12261            for (int i = 0; i < N; ++i) {
12262                intentFilters = packageActivities.get(i).intents;
12263                if (intentFilters != null && intentFilters.size() > 0) {
12264                    PackageParser.ActivityIntentInfo[] array =
12265                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12266                    intentFilters.toArray(array);
12267                    listCut.add(array);
12268                }
12269            }
12270            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12271        }
12272
12273        /**
12274         * Finds a privileged activity that matches the specified activity names.
12275         */
12276        private PackageParser.Activity findMatchingActivity(
12277                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12278            for (PackageParser.Activity sysActivity : activityList) {
12279                if (sysActivity.info.name.equals(activityInfo.name)) {
12280                    return sysActivity;
12281                }
12282                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12283                    return sysActivity;
12284                }
12285                if (sysActivity.info.targetActivity != null) {
12286                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12287                        return sysActivity;
12288                    }
12289                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12290                        return sysActivity;
12291                    }
12292                }
12293            }
12294            return null;
12295        }
12296
12297        public class IterGenerator<E> {
12298            public Iterator<E> generate(ActivityIntentInfo info) {
12299                return null;
12300            }
12301        }
12302
12303        public class ActionIterGenerator extends IterGenerator<String> {
12304            @Override
12305            public Iterator<String> generate(ActivityIntentInfo info) {
12306                return info.actionsIterator();
12307            }
12308        }
12309
12310        public class CategoriesIterGenerator extends IterGenerator<String> {
12311            @Override
12312            public Iterator<String> generate(ActivityIntentInfo info) {
12313                return info.categoriesIterator();
12314            }
12315        }
12316
12317        public class SchemesIterGenerator extends IterGenerator<String> {
12318            @Override
12319            public Iterator<String> generate(ActivityIntentInfo info) {
12320                return info.schemesIterator();
12321            }
12322        }
12323
12324        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12325            @Override
12326            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12327                return info.authoritiesIterator();
12328            }
12329        }
12330
12331        /**
12332         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12333         * MODIFIED. Do not pass in a list that should not be changed.
12334         */
12335        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12336                IterGenerator<T> generator, Iterator<T> searchIterator) {
12337            // loop through the set of actions; every one must be found in the intent filter
12338            while (searchIterator.hasNext()) {
12339                // we must have at least one filter in the list to consider a match
12340                if (intentList.size() == 0) {
12341                    break;
12342                }
12343
12344                final T searchAction = searchIterator.next();
12345
12346                // loop through the set of intent filters
12347                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12348                while (intentIter.hasNext()) {
12349                    final ActivityIntentInfo intentInfo = intentIter.next();
12350                    boolean selectionFound = false;
12351
12352                    // loop through the intent filter's selection criteria; at least one
12353                    // of them must match the searched criteria
12354                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12355                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12356                        final T intentSelection = intentSelectionIter.next();
12357                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12358                            selectionFound = true;
12359                            break;
12360                        }
12361                    }
12362
12363                    // the selection criteria wasn't found in this filter's set; this filter
12364                    // is not a potential match
12365                    if (!selectionFound) {
12366                        intentIter.remove();
12367                    }
12368                }
12369            }
12370        }
12371
12372        private boolean isProtectedAction(ActivityIntentInfo filter) {
12373            final Iterator<String> actionsIter = filter.actionsIterator();
12374            while (actionsIter != null && actionsIter.hasNext()) {
12375                final String filterAction = actionsIter.next();
12376                if (PROTECTED_ACTIONS.contains(filterAction)) {
12377                    return true;
12378                }
12379            }
12380            return false;
12381        }
12382
12383        /**
12384         * Adjusts the priority of the given intent filter according to policy.
12385         * <p>
12386         * <ul>
12387         * <li>The priority for non privileged applications is capped to '0'</li>
12388         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12389         * <li>The priority for unbundled updates to privileged applications is capped to the
12390         *      priority defined on the system partition</li>
12391         * </ul>
12392         * <p>
12393         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12394         * allowed to obtain any priority on any action.
12395         */
12396        private void adjustPriority(
12397                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12398            // nothing to do; priority is fine as-is
12399            if (intent.getPriority() <= 0) {
12400                return;
12401            }
12402
12403            final ActivityInfo activityInfo = intent.activity.info;
12404            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12405
12406            final boolean privilegedApp =
12407                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12408            if (!privilegedApp) {
12409                // non-privileged applications can never define a priority >0
12410                if (DEBUG_FILTERS) {
12411                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12412                            + " package: " + applicationInfo.packageName
12413                            + " activity: " + intent.activity.className
12414                            + " origPrio: " + intent.getPriority());
12415                }
12416                intent.setPriority(0);
12417                return;
12418            }
12419
12420            if (systemActivities == null) {
12421                // the system package is not disabled; we're parsing the system partition
12422                if (isProtectedAction(intent)) {
12423                    if (mDeferProtectedFilters) {
12424                        // We can't deal with these just yet. No component should ever obtain a
12425                        // >0 priority for a protected actions, with ONE exception -- the setup
12426                        // wizard. The setup wizard, however, cannot be known until we're able to
12427                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12428                        // until all intent filters have been processed. Chicken, meet egg.
12429                        // Let the filter temporarily have a high priority and rectify the
12430                        // priorities after all system packages have been scanned.
12431                        mProtectedFilters.add(intent);
12432                        if (DEBUG_FILTERS) {
12433                            Slog.i(TAG, "Protected action; save for later;"
12434                                    + " package: " + applicationInfo.packageName
12435                                    + " activity: " + intent.activity.className
12436                                    + " origPrio: " + intent.getPriority());
12437                        }
12438                        return;
12439                    } else {
12440                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12441                            Slog.i(TAG, "No setup wizard;"
12442                                + " All protected intents capped to priority 0");
12443                        }
12444                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12445                            if (DEBUG_FILTERS) {
12446                                Slog.i(TAG, "Found setup wizard;"
12447                                    + " allow priority " + intent.getPriority() + ";"
12448                                    + " package: " + intent.activity.info.packageName
12449                                    + " activity: " + intent.activity.className
12450                                    + " priority: " + intent.getPriority());
12451                            }
12452                            // setup wizard gets whatever it wants
12453                            return;
12454                        }
12455                        if (DEBUG_FILTERS) {
12456                            Slog.i(TAG, "Protected action; cap priority to 0;"
12457                                    + " package: " + intent.activity.info.packageName
12458                                    + " activity: " + intent.activity.className
12459                                    + " origPrio: " + intent.getPriority());
12460                        }
12461                        intent.setPriority(0);
12462                        return;
12463                    }
12464                }
12465                // privileged apps on the system image get whatever priority they request
12466                return;
12467            }
12468
12469            // privileged app unbundled update ... try to find the same activity
12470            final PackageParser.Activity foundActivity =
12471                    findMatchingActivity(systemActivities, activityInfo);
12472            if (foundActivity == null) {
12473                // this is a new activity; it cannot obtain >0 priority
12474                if (DEBUG_FILTERS) {
12475                    Slog.i(TAG, "New activity; cap priority to 0;"
12476                            + " package: " + applicationInfo.packageName
12477                            + " activity: " + intent.activity.className
12478                            + " origPrio: " + intent.getPriority());
12479                }
12480                intent.setPriority(0);
12481                return;
12482            }
12483
12484            // found activity, now check for filter equivalence
12485
12486            // a shallow copy is enough; we modify the list, not its contents
12487            final List<ActivityIntentInfo> intentListCopy =
12488                    new ArrayList<>(foundActivity.intents);
12489            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12490
12491            // find matching action subsets
12492            final Iterator<String> actionsIterator = intent.actionsIterator();
12493            if (actionsIterator != null) {
12494                getIntentListSubset(
12495                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12496                if (intentListCopy.size() == 0) {
12497                    // no more intents to match; we're not equivalent
12498                    if (DEBUG_FILTERS) {
12499                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12500                                + " package: " + applicationInfo.packageName
12501                                + " activity: " + intent.activity.className
12502                                + " origPrio: " + intent.getPriority());
12503                    }
12504                    intent.setPriority(0);
12505                    return;
12506                }
12507            }
12508
12509            // find matching category subsets
12510            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12511            if (categoriesIterator != null) {
12512                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12513                        categoriesIterator);
12514                if (intentListCopy.size() == 0) {
12515                    // no more intents to match; we're not equivalent
12516                    if (DEBUG_FILTERS) {
12517                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12518                                + " package: " + applicationInfo.packageName
12519                                + " activity: " + intent.activity.className
12520                                + " origPrio: " + intent.getPriority());
12521                    }
12522                    intent.setPriority(0);
12523                    return;
12524                }
12525            }
12526
12527            // find matching schemes subsets
12528            final Iterator<String> schemesIterator = intent.schemesIterator();
12529            if (schemesIterator != null) {
12530                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12531                        schemesIterator);
12532                if (intentListCopy.size() == 0) {
12533                    // no more intents to match; we're not equivalent
12534                    if (DEBUG_FILTERS) {
12535                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12536                                + " package: " + applicationInfo.packageName
12537                                + " activity: " + intent.activity.className
12538                                + " origPrio: " + intent.getPriority());
12539                    }
12540                    intent.setPriority(0);
12541                    return;
12542                }
12543            }
12544
12545            // find matching authorities subsets
12546            final Iterator<IntentFilter.AuthorityEntry>
12547                    authoritiesIterator = intent.authoritiesIterator();
12548            if (authoritiesIterator != null) {
12549                getIntentListSubset(intentListCopy,
12550                        new AuthoritiesIterGenerator(),
12551                        authoritiesIterator);
12552                if (intentListCopy.size() == 0) {
12553                    // no more intents to match; we're not equivalent
12554                    if (DEBUG_FILTERS) {
12555                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12556                                + " package: " + applicationInfo.packageName
12557                                + " activity: " + intent.activity.className
12558                                + " origPrio: " + intent.getPriority());
12559                    }
12560                    intent.setPriority(0);
12561                    return;
12562                }
12563            }
12564
12565            // we found matching filter(s); app gets the max priority of all intents
12566            int cappedPriority = 0;
12567            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12568                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12569            }
12570            if (intent.getPriority() > cappedPriority) {
12571                if (DEBUG_FILTERS) {
12572                    Slog.i(TAG, "Found matching filter(s);"
12573                            + " cap priority to " + cappedPriority + ";"
12574                            + " package: " + applicationInfo.packageName
12575                            + " activity: " + intent.activity.className
12576                            + " origPrio: " + intent.getPriority());
12577                }
12578                intent.setPriority(cappedPriority);
12579                return;
12580            }
12581            // all this for nothing; the requested priority was <= what was on the system
12582        }
12583
12584        public final void addActivity(PackageParser.Activity a, String type) {
12585            mActivities.put(a.getComponentName(), a);
12586            if (DEBUG_SHOW_INFO)
12587                Log.v(
12588                TAG, "  " + type + " " +
12589                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12590            if (DEBUG_SHOW_INFO)
12591                Log.v(TAG, "    Class=" + a.info.name);
12592            final int NI = a.intents.size();
12593            for (int j=0; j<NI; j++) {
12594                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12595                if ("activity".equals(type)) {
12596                    final PackageSetting ps =
12597                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12598                    final List<PackageParser.Activity> systemActivities =
12599                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12600                    adjustPriority(systemActivities, intent);
12601                }
12602                if (DEBUG_SHOW_INFO) {
12603                    Log.v(TAG, "    IntentFilter:");
12604                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12605                }
12606                if (!intent.debugCheck()) {
12607                    Log.w(TAG, "==> For Activity " + a.info.name);
12608                }
12609                addFilter(intent);
12610            }
12611        }
12612
12613        public final void removeActivity(PackageParser.Activity a, String type) {
12614            mActivities.remove(a.getComponentName());
12615            if (DEBUG_SHOW_INFO) {
12616                Log.v(TAG, "  " + type + " "
12617                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12618                                : a.info.name) + ":");
12619                Log.v(TAG, "    Class=" + a.info.name);
12620            }
12621            final int NI = a.intents.size();
12622            for (int j=0; j<NI; j++) {
12623                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12624                if (DEBUG_SHOW_INFO) {
12625                    Log.v(TAG, "    IntentFilter:");
12626                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12627                }
12628                removeFilter(intent);
12629            }
12630        }
12631
12632        @Override
12633        protected boolean allowFilterResult(
12634                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12635            ActivityInfo filterAi = filter.activity.info;
12636            for (int i=dest.size()-1; i>=0; i--) {
12637                ActivityInfo destAi = dest.get(i).activityInfo;
12638                if (destAi.name == filterAi.name
12639                        && destAi.packageName == filterAi.packageName) {
12640                    return false;
12641                }
12642            }
12643            return true;
12644        }
12645
12646        @Override
12647        protected ActivityIntentInfo[] newArray(int size) {
12648            return new ActivityIntentInfo[size];
12649        }
12650
12651        @Override
12652        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12653            if (!sUserManager.exists(userId)) return true;
12654            PackageParser.Package p = filter.activity.owner;
12655            if (p != null) {
12656                PackageSetting ps = (PackageSetting)p.mExtras;
12657                if (ps != null) {
12658                    // System apps are never considered stopped for purposes of
12659                    // filtering, because there may be no way for the user to
12660                    // actually re-launch them.
12661                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12662                            && ps.getStopped(userId);
12663                }
12664            }
12665            return false;
12666        }
12667
12668        @Override
12669        protected boolean isPackageForFilter(String packageName,
12670                PackageParser.ActivityIntentInfo info) {
12671            return packageName.equals(info.activity.owner.packageName);
12672        }
12673
12674        @Override
12675        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12676                int match, int userId) {
12677            if (!sUserManager.exists(userId)) return null;
12678            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12679                return null;
12680            }
12681            final PackageParser.Activity activity = info.activity;
12682            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12683            if (ps == null) {
12684                return null;
12685            }
12686            final PackageUserState userState = ps.readUserState(userId);
12687            ActivityInfo ai =
12688                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12689            if (ai == null) {
12690                return null;
12691            }
12692            final boolean matchExplicitlyVisibleOnly =
12693                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12694            final boolean matchVisibleToInstantApp =
12695                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12696            final boolean componentVisible =
12697                    matchVisibleToInstantApp
12698                    && info.isVisibleToInstantApp()
12699                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12700            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12701            // throw out filters that aren't visible to ephemeral apps
12702            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12703                return null;
12704            }
12705            // throw out instant app filters if we're not explicitly requesting them
12706            if (!matchInstantApp && userState.instantApp) {
12707                return null;
12708            }
12709            // throw out instant app filters if updates are available; will trigger
12710            // instant app resolution
12711            if (userState.instantApp && ps.isUpdateAvailable()) {
12712                return null;
12713            }
12714            final ResolveInfo res = new ResolveInfo();
12715            res.activityInfo = ai;
12716            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12717                res.filter = info;
12718            }
12719            if (info != null) {
12720                res.handleAllWebDataURI = info.handleAllWebDataURI();
12721            }
12722            res.priority = info.getPriority();
12723            res.preferredOrder = activity.owner.mPreferredOrder;
12724            //System.out.println("Result: " + res.activityInfo.className +
12725            //                   " = " + res.priority);
12726            res.match = match;
12727            res.isDefault = info.hasDefault;
12728            res.labelRes = info.labelRes;
12729            res.nonLocalizedLabel = info.nonLocalizedLabel;
12730            if (userNeedsBadging(userId)) {
12731                res.noResourceId = true;
12732            } else {
12733                res.icon = info.icon;
12734            }
12735            res.iconResourceId = info.icon;
12736            res.system = res.activityInfo.applicationInfo.isSystemApp();
12737            res.isInstantAppAvailable = userState.instantApp;
12738            return res;
12739        }
12740
12741        @Override
12742        protected void sortResults(List<ResolveInfo> results) {
12743            Collections.sort(results, mResolvePrioritySorter);
12744        }
12745
12746        @Override
12747        protected void dumpFilter(PrintWriter out, String prefix,
12748                PackageParser.ActivityIntentInfo filter) {
12749            out.print(prefix); out.print(
12750                    Integer.toHexString(System.identityHashCode(filter.activity)));
12751                    out.print(' ');
12752                    filter.activity.printComponentShortName(out);
12753                    out.print(" filter ");
12754                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12755        }
12756
12757        @Override
12758        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12759            return filter.activity;
12760        }
12761
12762        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12763            PackageParser.Activity activity = (PackageParser.Activity)label;
12764            out.print(prefix); out.print(
12765                    Integer.toHexString(System.identityHashCode(activity)));
12766                    out.print(' ');
12767                    activity.printComponentShortName(out);
12768            if (count > 1) {
12769                out.print(" ("); out.print(count); out.print(" filters)");
12770            }
12771            out.println();
12772        }
12773
12774        // Keys are String (activity class name), values are Activity.
12775        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12776                = new ArrayMap<ComponentName, PackageParser.Activity>();
12777        private int mFlags;
12778    }
12779
12780    private final class ServiceIntentResolver
12781            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12782        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12783                boolean defaultOnly, int userId) {
12784            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12785            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12786        }
12787
12788        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12789                int userId) {
12790            if (!sUserManager.exists(userId)) return null;
12791            mFlags = flags;
12792            return super.queryIntent(intent, resolvedType,
12793                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12794                    userId);
12795        }
12796
12797        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12798                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12799            if (!sUserManager.exists(userId)) return null;
12800            if (packageServices == null) {
12801                return null;
12802            }
12803            mFlags = flags;
12804            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12805            final int N = packageServices.size();
12806            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12807                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12808
12809            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12810            for (int i = 0; i < N; ++i) {
12811                intentFilters = packageServices.get(i).intents;
12812                if (intentFilters != null && intentFilters.size() > 0) {
12813                    PackageParser.ServiceIntentInfo[] array =
12814                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12815                    intentFilters.toArray(array);
12816                    listCut.add(array);
12817                }
12818            }
12819            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12820        }
12821
12822        public final void addService(PackageParser.Service s) {
12823            mServices.put(s.getComponentName(), s);
12824            if (DEBUG_SHOW_INFO) {
12825                Log.v(TAG, "  "
12826                        + (s.info.nonLocalizedLabel != null
12827                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12828                Log.v(TAG, "    Class=" + s.info.name);
12829            }
12830            final int NI = s.intents.size();
12831            int j;
12832            for (j=0; j<NI; j++) {
12833                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12834                if (DEBUG_SHOW_INFO) {
12835                    Log.v(TAG, "    IntentFilter:");
12836                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12837                }
12838                if (!intent.debugCheck()) {
12839                    Log.w(TAG, "==> For Service " + s.info.name);
12840                }
12841                addFilter(intent);
12842            }
12843        }
12844
12845        public final void removeService(PackageParser.Service s) {
12846            mServices.remove(s.getComponentName());
12847            if (DEBUG_SHOW_INFO) {
12848                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12849                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12850                Log.v(TAG, "    Class=" + s.info.name);
12851            }
12852            final int NI = s.intents.size();
12853            int j;
12854            for (j=0; j<NI; j++) {
12855                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12856                if (DEBUG_SHOW_INFO) {
12857                    Log.v(TAG, "    IntentFilter:");
12858                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12859                }
12860                removeFilter(intent);
12861            }
12862        }
12863
12864        @Override
12865        protected boolean allowFilterResult(
12866                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12867            ServiceInfo filterSi = filter.service.info;
12868            for (int i=dest.size()-1; i>=0; i--) {
12869                ServiceInfo destAi = dest.get(i).serviceInfo;
12870                if (destAi.name == filterSi.name
12871                        && destAi.packageName == filterSi.packageName) {
12872                    return false;
12873                }
12874            }
12875            return true;
12876        }
12877
12878        @Override
12879        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12880            return new PackageParser.ServiceIntentInfo[size];
12881        }
12882
12883        @Override
12884        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12885            if (!sUserManager.exists(userId)) return true;
12886            PackageParser.Package p = filter.service.owner;
12887            if (p != null) {
12888                PackageSetting ps = (PackageSetting)p.mExtras;
12889                if (ps != null) {
12890                    // System apps are never considered stopped for purposes of
12891                    // filtering, because there may be no way for the user to
12892                    // actually re-launch them.
12893                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12894                            && ps.getStopped(userId);
12895                }
12896            }
12897            return false;
12898        }
12899
12900        @Override
12901        protected boolean isPackageForFilter(String packageName,
12902                PackageParser.ServiceIntentInfo info) {
12903            return packageName.equals(info.service.owner.packageName);
12904        }
12905
12906        @Override
12907        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12908                int match, int userId) {
12909            if (!sUserManager.exists(userId)) return null;
12910            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12911            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12912                return null;
12913            }
12914            final PackageParser.Service service = info.service;
12915            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12916            if (ps == null) {
12917                return null;
12918            }
12919            final PackageUserState userState = ps.readUserState(userId);
12920            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12921                    userState, userId);
12922            if (si == null) {
12923                return null;
12924            }
12925            final boolean matchVisibleToInstantApp =
12926                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12927            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12928            // throw out filters that aren't visible to ephemeral apps
12929            if (matchVisibleToInstantApp
12930                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12931                return null;
12932            }
12933            // throw out ephemeral filters if we're not explicitly requesting them
12934            if (!isInstantApp && userState.instantApp) {
12935                return null;
12936            }
12937            // throw out instant app filters if updates are available; will trigger
12938            // instant app resolution
12939            if (userState.instantApp && ps.isUpdateAvailable()) {
12940                return null;
12941            }
12942            final ResolveInfo res = new ResolveInfo();
12943            res.serviceInfo = si;
12944            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12945                res.filter = filter;
12946            }
12947            res.priority = info.getPriority();
12948            res.preferredOrder = service.owner.mPreferredOrder;
12949            res.match = match;
12950            res.isDefault = info.hasDefault;
12951            res.labelRes = info.labelRes;
12952            res.nonLocalizedLabel = info.nonLocalizedLabel;
12953            res.icon = info.icon;
12954            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12955            return res;
12956        }
12957
12958        @Override
12959        protected void sortResults(List<ResolveInfo> results) {
12960            Collections.sort(results, mResolvePrioritySorter);
12961        }
12962
12963        @Override
12964        protected void dumpFilter(PrintWriter out, String prefix,
12965                PackageParser.ServiceIntentInfo filter) {
12966            out.print(prefix); out.print(
12967                    Integer.toHexString(System.identityHashCode(filter.service)));
12968                    out.print(' ');
12969                    filter.service.printComponentShortName(out);
12970                    out.print(" filter ");
12971                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12972                    if (filter.service.info.permission != null) {
12973                        out.print(" permission "); out.println(filter.service.info.permission);
12974                    } else {
12975                        out.println();
12976                    }
12977        }
12978
12979        @Override
12980        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12981            return filter.service;
12982        }
12983
12984        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12985            PackageParser.Service service = (PackageParser.Service)label;
12986            out.print(prefix); out.print(
12987                    Integer.toHexString(System.identityHashCode(service)));
12988                    out.print(' ');
12989                    service.printComponentShortName(out);
12990            if (count > 1) {
12991                out.print(" ("); out.print(count); out.print(" filters)");
12992            }
12993            out.println();
12994        }
12995
12996//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12997//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12998//            final List<ResolveInfo> retList = Lists.newArrayList();
12999//            while (i.hasNext()) {
13000//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13001//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13002//                    retList.add(resolveInfo);
13003//                }
13004//            }
13005//            return retList;
13006//        }
13007
13008        // Keys are String (activity class name), values are Activity.
13009        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13010                = new ArrayMap<ComponentName, PackageParser.Service>();
13011        private int mFlags;
13012    }
13013
13014    private final class ProviderIntentResolver
13015            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13016        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13017                boolean defaultOnly, int userId) {
13018            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13019            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13020        }
13021
13022        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13023                int userId) {
13024            if (!sUserManager.exists(userId))
13025                return null;
13026            mFlags = flags;
13027            return super.queryIntent(intent, resolvedType,
13028                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13029                    userId);
13030        }
13031
13032        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13033                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13034            if (!sUserManager.exists(userId))
13035                return null;
13036            if (packageProviders == null) {
13037                return null;
13038            }
13039            mFlags = flags;
13040            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13041            final int N = packageProviders.size();
13042            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13043                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13044
13045            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13046            for (int i = 0; i < N; ++i) {
13047                intentFilters = packageProviders.get(i).intents;
13048                if (intentFilters != null && intentFilters.size() > 0) {
13049                    PackageParser.ProviderIntentInfo[] array =
13050                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13051                    intentFilters.toArray(array);
13052                    listCut.add(array);
13053                }
13054            }
13055            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13056        }
13057
13058        public final void addProvider(PackageParser.Provider p) {
13059            if (mProviders.containsKey(p.getComponentName())) {
13060                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13061                return;
13062            }
13063
13064            mProviders.put(p.getComponentName(), p);
13065            if (DEBUG_SHOW_INFO) {
13066                Log.v(TAG, "  "
13067                        + (p.info.nonLocalizedLabel != null
13068                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13069                Log.v(TAG, "    Class=" + p.info.name);
13070            }
13071            final int NI = p.intents.size();
13072            int j;
13073            for (j = 0; j < NI; j++) {
13074                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13075                if (DEBUG_SHOW_INFO) {
13076                    Log.v(TAG, "    IntentFilter:");
13077                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13078                }
13079                if (!intent.debugCheck()) {
13080                    Log.w(TAG, "==> For Provider " + p.info.name);
13081                }
13082                addFilter(intent);
13083            }
13084        }
13085
13086        public final void removeProvider(PackageParser.Provider p) {
13087            mProviders.remove(p.getComponentName());
13088            if (DEBUG_SHOW_INFO) {
13089                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13090                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13091                Log.v(TAG, "    Class=" + p.info.name);
13092            }
13093            final int NI = p.intents.size();
13094            int j;
13095            for (j = 0; j < NI; j++) {
13096                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13097                if (DEBUG_SHOW_INFO) {
13098                    Log.v(TAG, "    IntentFilter:");
13099                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13100                }
13101                removeFilter(intent);
13102            }
13103        }
13104
13105        @Override
13106        protected boolean allowFilterResult(
13107                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13108            ProviderInfo filterPi = filter.provider.info;
13109            for (int i = dest.size() - 1; i >= 0; i--) {
13110                ProviderInfo destPi = dest.get(i).providerInfo;
13111                if (destPi.name == filterPi.name
13112                        && destPi.packageName == filterPi.packageName) {
13113                    return false;
13114                }
13115            }
13116            return true;
13117        }
13118
13119        @Override
13120        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13121            return new PackageParser.ProviderIntentInfo[size];
13122        }
13123
13124        @Override
13125        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13126            if (!sUserManager.exists(userId))
13127                return true;
13128            PackageParser.Package p = filter.provider.owner;
13129            if (p != null) {
13130                PackageSetting ps = (PackageSetting) p.mExtras;
13131                if (ps != null) {
13132                    // System apps are never considered stopped for purposes of
13133                    // filtering, because there may be no way for the user to
13134                    // actually re-launch them.
13135                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13136                            && ps.getStopped(userId);
13137                }
13138            }
13139            return false;
13140        }
13141
13142        @Override
13143        protected boolean isPackageForFilter(String packageName,
13144                PackageParser.ProviderIntentInfo info) {
13145            return packageName.equals(info.provider.owner.packageName);
13146        }
13147
13148        @Override
13149        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13150                int match, int userId) {
13151            if (!sUserManager.exists(userId))
13152                return null;
13153            final PackageParser.ProviderIntentInfo info = filter;
13154            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13155                return null;
13156            }
13157            final PackageParser.Provider provider = info.provider;
13158            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13159            if (ps == null) {
13160                return null;
13161            }
13162            final PackageUserState userState = ps.readUserState(userId);
13163            final boolean matchVisibleToInstantApp =
13164                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13165            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13166            // throw out filters that aren't visible to instant applications
13167            if (matchVisibleToInstantApp
13168                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13169                return null;
13170            }
13171            // throw out instant application filters if we're not explicitly requesting them
13172            if (!isInstantApp && userState.instantApp) {
13173                return null;
13174            }
13175            // throw out instant application filters if updates are available; will trigger
13176            // instant application resolution
13177            if (userState.instantApp && ps.isUpdateAvailable()) {
13178                return null;
13179            }
13180            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13181                    userState, userId);
13182            if (pi == null) {
13183                return null;
13184            }
13185            final ResolveInfo res = new ResolveInfo();
13186            res.providerInfo = pi;
13187            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13188                res.filter = filter;
13189            }
13190            res.priority = info.getPriority();
13191            res.preferredOrder = provider.owner.mPreferredOrder;
13192            res.match = match;
13193            res.isDefault = info.hasDefault;
13194            res.labelRes = info.labelRes;
13195            res.nonLocalizedLabel = info.nonLocalizedLabel;
13196            res.icon = info.icon;
13197            res.system = res.providerInfo.applicationInfo.isSystemApp();
13198            return res;
13199        }
13200
13201        @Override
13202        protected void sortResults(List<ResolveInfo> results) {
13203            Collections.sort(results, mResolvePrioritySorter);
13204        }
13205
13206        @Override
13207        protected void dumpFilter(PrintWriter out, String prefix,
13208                PackageParser.ProviderIntentInfo filter) {
13209            out.print(prefix);
13210            out.print(
13211                    Integer.toHexString(System.identityHashCode(filter.provider)));
13212            out.print(' ');
13213            filter.provider.printComponentShortName(out);
13214            out.print(" filter ");
13215            out.println(Integer.toHexString(System.identityHashCode(filter)));
13216        }
13217
13218        @Override
13219        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13220            return filter.provider;
13221        }
13222
13223        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13224            PackageParser.Provider provider = (PackageParser.Provider)label;
13225            out.print(prefix); out.print(
13226                    Integer.toHexString(System.identityHashCode(provider)));
13227                    out.print(' ');
13228                    provider.printComponentShortName(out);
13229            if (count > 1) {
13230                out.print(" ("); out.print(count); out.print(" filters)");
13231            }
13232            out.println();
13233        }
13234
13235        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13236                = new ArrayMap<ComponentName, PackageParser.Provider>();
13237        private int mFlags;
13238    }
13239
13240    static final class InstantAppIntentResolver
13241            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13242            AuxiliaryResolveInfo.AuxiliaryFilter> {
13243        /**
13244         * The result that has the highest defined order. Ordering applies on a
13245         * per-package basis. Mapping is from package name to Pair of order and
13246         * EphemeralResolveInfo.
13247         * <p>
13248         * NOTE: This is implemented as a field variable for convenience and efficiency.
13249         * By having a field variable, we're able to track filter ordering as soon as
13250         * a non-zero order is defined. Otherwise, multiple loops across the result set
13251         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13252         * this needs to be contained entirely within {@link #filterResults}.
13253         */
13254        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13255
13256        @Override
13257        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13258            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13259        }
13260
13261        @Override
13262        protected boolean isPackageForFilter(String packageName,
13263                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13264            return true;
13265        }
13266
13267        @Override
13268        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13269                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13270            if (!sUserManager.exists(userId)) {
13271                return null;
13272            }
13273            final String packageName = responseObj.resolveInfo.getPackageName();
13274            final Integer order = responseObj.getOrder();
13275            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13276                    mOrderResult.get(packageName);
13277            // ordering is enabled and this item's order isn't high enough
13278            if (lastOrderResult != null && lastOrderResult.first >= order) {
13279                return null;
13280            }
13281            final InstantAppResolveInfo res = responseObj.resolveInfo;
13282            if (order > 0) {
13283                // non-zero order, enable ordering
13284                mOrderResult.put(packageName, new Pair<>(order, res));
13285            }
13286            return responseObj;
13287        }
13288
13289        @Override
13290        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13291            // only do work if ordering is enabled [most of the time it won't be]
13292            if (mOrderResult.size() == 0) {
13293                return;
13294            }
13295            int resultSize = results.size();
13296            for (int i = 0; i < resultSize; i++) {
13297                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13298                final String packageName = info.getPackageName();
13299                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13300                if (savedInfo == null) {
13301                    // package doesn't having ordering
13302                    continue;
13303                }
13304                if (savedInfo.second == info) {
13305                    // circled back to the highest ordered item; remove from order list
13306                    mOrderResult.remove(packageName);
13307                    if (mOrderResult.size() == 0) {
13308                        // no more ordered items
13309                        break;
13310                    }
13311                    continue;
13312                }
13313                // item has a worse order, remove it from the result list
13314                results.remove(i);
13315                resultSize--;
13316                i--;
13317            }
13318        }
13319    }
13320
13321    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13322            new Comparator<ResolveInfo>() {
13323        public int compare(ResolveInfo r1, ResolveInfo r2) {
13324            int v1 = r1.priority;
13325            int v2 = r2.priority;
13326            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13327            if (v1 != v2) {
13328                return (v1 > v2) ? -1 : 1;
13329            }
13330            v1 = r1.preferredOrder;
13331            v2 = r2.preferredOrder;
13332            if (v1 != v2) {
13333                return (v1 > v2) ? -1 : 1;
13334            }
13335            if (r1.isDefault != r2.isDefault) {
13336                return r1.isDefault ? -1 : 1;
13337            }
13338            v1 = r1.match;
13339            v2 = r2.match;
13340            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13341            if (v1 != v2) {
13342                return (v1 > v2) ? -1 : 1;
13343            }
13344            if (r1.system != r2.system) {
13345                return r1.system ? -1 : 1;
13346            }
13347            if (r1.activityInfo != null) {
13348                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13349            }
13350            if (r1.serviceInfo != null) {
13351                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13352            }
13353            if (r1.providerInfo != null) {
13354                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13355            }
13356            return 0;
13357        }
13358    };
13359
13360    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13361            new Comparator<ProviderInfo>() {
13362        public int compare(ProviderInfo p1, ProviderInfo p2) {
13363            final int v1 = p1.initOrder;
13364            final int v2 = p2.initOrder;
13365            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13366        }
13367    };
13368
13369    @Override
13370    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13371            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13372            final int[] userIds, int[] instantUserIds) {
13373        mHandler.post(new Runnable() {
13374            @Override
13375            public void run() {
13376                try {
13377                    final IActivityManager am = ActivityManager.getService();
13378                    if (am == null) return;
13379                    final int[] resolvedUserIds;
13380                    if (userIds == null) {
13381                        resolvedUserIds = am.getRunningUserIds();
13382                    } else {
13383                        resolvedUserIds = userIds;
13384                    }
13385                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13386                            resolvedUserIds, false);
13387                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13388                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13389                                instantUserIds, true);
13390                    }
13391                } catch (RemoteException ex) {
13392                }
13393            }
13394        });
13395    }
13396
13397    @Override
13398    public void notifyPackageAdded(String packageName) {
13399        final PackageListObserver[] observers;
13400        synchronized (mPackages) {
13401            if (mPackageListObservers.size() == 0) {
13402                return;
13403            }
13404            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13405        }
13406        for (int i = observers.length - 1; i >= 0; --i) {
13407            observers[i].onPackageAdded(packageName);
13408        }
13409    }
13410
13411    @Override
13412    public void notifyPackageRemoved(String packageName) {
13413        final PackageListObserver[] observers;
13414        synchronized (mPackages) {
13415            if (mPackageListObservers.size() == 0) {
13416                return;
13417            }
13418            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13419        }
13420        for (int i = observers.length - 1; i >= 0; --i) {
13421            observers[i].onPackageRemoved(packageName);
13422        }
13423    }
13424
13425    /**
13426     * Sends a broadcast for the given action.
13427     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13428     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13429     * the system and applications allowed to see instant applications to receive package
13430     * lifecycle events for instant applications.
13431     */
13432    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13433            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13434            int[] userIds, boolean isInstantApp)
13435                    throws RemoteException {
13436        for (int id : userIds) {
13437            final Intent intent = new Intent(action,
13438                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13439            final String[] requiredPermissions =
13440                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13441            if (extras != null) {
13442                intent.putExtras(extras);
13443            }
13444            if (targetPkg != null) {
13445                intent.setPackage(targetPkg);
13446            }
13447            // Modify the UID when posting to other users
13448            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13449            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13450                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13451                intent.putExtra(Intent.EXTRA_UID, uid);
13452            }
13453            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13454            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13455            if (DEBUG_BROADCASTS) {
13456                RuntimeException here = new RuntimeException("here");
13457                here.fillInStackTrace();
13458                Slog.d(TAG, "Sending to user " + id + ": "
13459                        + intent.toShortString(false, true, false, false)
13460                        + " " + intent.getExtras(), here);
13461            }
13462            am.broadcastIntent(null, intent, null, finishedReceiver,
13463                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13464                    null, finishedReceiver != null, false, id);
13465        }
13466    }
13467
13468    /**
13469     * Check if the external storage media is available. This is true if there
13470     * is a mounted external storage medium or if the external storage is
13471     * emulated.
13472     */
13473    private boolean isExternalMediaAvailable() {
13474        return mMediaMounted || Environment.isExternalStorageEmulated();
13475    }
13476
13477    @Override
13478    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13479        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13480            return null;
13481        }
13482        if (!isExternalMediaAvailable()) {
13483                // If the external storage is no longer mounted at this point,
13484                // the caller may not have been able to delete all of this
13485                // packages files and can not delete any more.  Bail.
13486            return null;
13487        }
13488        synchronized (mPackages) {
13489            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13490            if (lastPackage != null) {
13491                pkgs.remove(lastPackage);
13492            }
13493            if (pkgs.size() > 0) {
13494                return pkgs.get(0);
13495            }
13496        }
13497        return null;
13498    }
13499
13500    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13501        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13502                userId, andCode ? 1 : 0, packageName);
13503        if (mSystemReady) {
13504            msg.sendToTarget();
13505        } else {
13506            if (mPostSystemReadyMessages == null) {
13507                mPostSystemReadyMessages = new ArrayList<>();
13508            }
13509            mPostSystemReadyMessages.add(msg);
13510        }
13511    }
13512
13513    void startCleaningPackages() {
13514        // reader
13515        if (!isExternalMediaAvailable()) {
13516            return;
13517        }
13518        synchronized (mPackages) {
13519            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13520                return;
13521            }
13522        }
13523        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13524        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13525        IActivityManager am = ActivityManager.getService();
13526        if (am != null) {
13527            int dcsUid = -1;
13528            synchronized (mPackages) {
13529                if (!mDefaultContainerWhitelisted) {
13530                    mDefaultContainerWhitelisted = true;
13531                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13532                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13533                }
13534            }
13535            try {
13536                if (dcsUid > 0) {
13537                    am.backgroundWhitelistUid(dcsUid);
13538                }
13539                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13540                        UserHandle.USER_SYSTEM);
13541            } catch (RemoteException e) {
13542            }
13543        }
13544    }
13545
13546    /**
13547     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13548     * it is acting on behalf on an enterprise or the user).
13549     *
13550     * Note that the ordering of the conditionals in this method is important. The checks we perform
13551     * are as follows, in this order:
13552     *
13553     * 1) If the install is being performed by a system app, we can trust the app to have set the
13554     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13555     *    what it is.
13556     * 2) If the install is being performed by a device or profile owner app, the install reason
13557     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13558     *    set the install reason correctly. If the app targets an older SDK version where install
13559     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13560     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13561     * 3) In all other cases, the install is being performed by a regular app that is neither part
13562     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13563     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13564     *    set to enterprise policy and if so, change it to unknown instead.
13565     */
13566    private int fixUpInstallReason(String installerPackageName, int installerUid,
13567            int installReason) {
13568        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13569                == PERMISSION_GRANTED) {
13570            // If the install is being performed by a system app, we trust that app to have set the
13571            // install reason correctly.
13572            return installReason;
13573        }
13574
13575        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13576            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13577        if (dpm != null) {
13578            ComponentName owner = null;
13579            try {
13580                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13581                if (owner == null) {
13582                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13583                }
13584            } catch (RemoteException e) {
13585            }
13586            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13587                // If the install is being performed by a device or profile owner, the install
13588                // reason should be enterprise policy.
13589                return PackageManager.INSTALL_REASON_POLICY;
13590            }
13591        }
13592
13593        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13594            // If the install is being performed by a regular app (i.e. neither system app nor
13595            // device or profile owner), we have no reason to believe that the app is acting on
13596            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13597            // change it to unknown instead.
13598            return PackageManager.INSTALL_REASON_UNKNOWN;
13599        }
13600
13601        // If the install is being performed by a regular app and the install reason was set to any
13602        // value but enterprise policy, leave the install reason unchanged.
13603        return installReason;
13604    }
13605
13606    void installStage(String packageName, File stagedDir,
13607            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13608            String installerPackageName, int installerUid, UserHandle user,
13609            PackageParser.SigningDetails signingDetails) {
13610        if (DEBUG_INSTANT) {
13611            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13612                Slog.d(TAG, "Ephemeral install of " + packageName);
13613            }
13614        }
13615        final VerificationInfo verificationInfo = new VerificationInfo(
13616                sessionParams.originatingUri, sessionParams.referrerUri,
13617                sessionParams.originatingUid, installerUid);
13618
13619        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13620
13621        final Message msg = mHandler.obtainMessage(INIT_COPY);
13622        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13623                sessionParams.installReason);
13624        final InstallParams params = new InstallParams(origin, null, observer,
13625                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13626                verificationInfo, user, sessionParams.abiOverride,
13627                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13628        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13629        msg.obj = params;
13630
13631        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13632                System.identityHashCode(msg.obj));
13633        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13634                System.identityHashCode(msg.obj));
13635
13636        mHandler.sendMessage(msg);
13637    }
13638
13639    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13640            int userId) {
13641        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13642        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13643        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13644        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13645        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13646                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13647
13648        // Send a session commit broadcast
13649        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13650        info.installReason = pkgSetting.getInstallReason(userId);
13651        info.appPackageName = packageName;
13652        sendSessionCommitBroadcast(info, userId);
13653    }
13654
13655    @Override
13656    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13657            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13658        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13659            return;
13660        }
13661        Bundle extras = new Bundle(1);
13662        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13663        final int uid = UserHandle.getUid(
13664                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13665        extras.putInt(Intent.EXTRA_UID, uid);
13666
13667        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13668                packageName, extras, 0, null, null, userIds, instantUserIds);
13669        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13670            mHandler.post(() -> {
13671                        for (int userId : userIds) {
13672                            sendBootCompletedBroadcastToSystemApp(
13673                                    packageName, includeStopped, userId);
13674                        }
13675                    }
13676            );
13677        }
13678    }
13679
13680    /**
13681     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13682     * automatically without needing an explicit launch.
13683     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13684     */
13685    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13686            int userId) {
13687        // If user is not running, the app didn't miss any broadcast
13688        if (!mUserManagerInternal.isUserRunning(userId)) {
13689            return;
13690        }
13691        final IActivityManager am = ActivityManager.getService();
13692        try {
13693            // Deliver LOCKED_BOOT_COMPLETED first
13694            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13695                    .setPackage(packageName);
13696            if (includeStopped) {
13697                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13698            }
13699            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13700            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13701                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13702
13703            // Deliver BOOT_COMPLETED only if user is unlocked
13704            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13705                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13706                if (includeStopped) {
13707                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13708                }
13709                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13710                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13711            }
13712        } catch (RemoteException e) {
13713            throw e.rethrowFromSystemServer();
13714        }
13715    }
13716
13717    @Override
13718    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13719            int userId) {
13720        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13721        PackageSetting pkgSetting;
13722        final int callingUid = Binder.getCallingUid();
13723        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13724                true /* requireFullPermission */, true /* checkShell */,
13725                "setApplicationHiddenSetting for user " + userId);
13726
13727        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13728            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13729            return false;
13730        }
13731
13732        long callingId = Binder.clearCallingIdentity();
13733        try {
13734            boolean sendAdded = false;
13735            boolean sendRemoved = false;
13736            // writer
13737            synchronized (mPackages) {
13738                pkgSetting = mSettings.mPackages.get(packageName);
13739                if (pkgSetting == null) {
13740                    return false;
13741                }
13742                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13743                    return false;
13744                }
13745                // Do not allow "android" is being disabled
13746                if ("android".equals(packageName)) {
13747                    Slog.w(TAG, "Cannot hide package: android");
13748                    return false;
13749                }
13750                // Cannot hide static shared libs as they are considered
13751                // a part of the using app (emulating static linking). Also
13752                // static libs are installed always on internal storage.
13753                PackageParser.Package pkg = mPackages.get(packageName);
13754                if (pkg != null && pkg.staticSharedLibName != null) {
13755                    Slog.w(TAG, "Cannot hide package: " + packageName
13756                            + " providing static shared library: "
13757                            + pkg.staticSharedLibName);
13758                    return false;
13759                }
13760                // Only allow protected packages to hide themselves.
13761                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13762                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13763                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13764                    return false;
13765                }
13766
13767                if (pkgSetting.getHidden(userId) != hidden) {
13768                    pkgSetting.setHidden(hidden, userId);
13769                    mSettings.writePackageRestrictionsLPr(userId);
13770                    if (hidden) {
13771                        sendRemoved = true;
13772                    } else {
13773                        sendAdded = true;
13774                    }
13775                }
13776            }
13777            if (sendAdded) {
13778                sendPackageAddedForUser(packageName, pkgSetting, userId);
13779                return true;
13780            }
13781            if (sendRemoved) {
13782                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13783                        "hiding pkg");
13784                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13785                return true;
13786            }
13787        } finally {
13788            Binder.restoreCallingIdentity(callingId);
13789        }
13790        return false;
13791    }
13792
13793    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13794            int userId) {
13795        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13796        info.removedPackage = packageName;
13797        info.installerPackageName = pkgSetting.installerPackageName;
13798        info.removedUsers = new int[] {userId};
13799        info.broadcastUsers = new int[] {userId};
13800        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13801        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13802    }
13803
13804    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13805        if (pkgList.length > 0) {
13806            Bundle extras = new Bundle(1);
13807            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13808
13809            sendPackageBroadcast(
13810                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13811                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13812                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13813                    new int[] {userId}, null);
13814        }
13815    }
13816
13817    /**
13818     * Returns true if application is not found or there was an error. Otherwise it returns
13819     * the hidden state of the package for the given user.
13820     */
13821    @Override
13822    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13823        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13824        final int callingUid = Binder.getCallingUid();
13825        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13826                true /* requireFullPermission */, false /* checkShell */,
13827                "getApplicationHidden for user " + userId);
13828        PackageSetting ps;
13829        long callingId = Binder.clearCallingIdentity();
13830        try {
13831            // writer
13832            synchronized (mPackages) {
13833                ps = mSettings.mPackages.get(packageName);
13834                if (ps == null) {
13835                    return true;
13836                }
13837                if (filterAppAccessLPr(ps, callingUid, userId)) {
13838                    return true;
13839                }
13840                return ps.getHidden(userId);
13841            }
13842        } finally {
13843            Binder.restoreCallingIdentity(callingId);
13844        }
13845    }
13846
13847    /**
13848     * @hide
13849     */
13850    @Override
13851    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13852            int installReason) {
13853        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13854                null);
13855        PackageSetting pkgSetting;
13856        final int callingUid = Binder.getCallingUid();
13857        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13858                true /* requireFullPermission */, true /* checkShell */,
13859                "installExistingPackage for user " + userId);
13860        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13861            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13862        }
13863
13864        long callingId = Binder.clearCallingIdentity();
13865        try {
13866            boolean installed = false;
13867            final boolean instantApp =
13868                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13869            final boolean fullApp =
13870                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13871
13872            // writer
13873            synchronized (mPackages) {
13874                pkgSetting = mSettings.mPackages.get(packageName);
13875                if (pkgSetting == null) {
13876                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13877                }
13878                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13879                    // only allow the existing package to be used if it's installed as a full
13880                    // application for at least one user
13881                    boolean installAllowed = false;
13882                    for (int checkUserId : sUserManager.getUserIds()) {
13883                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13884                        if (installAllowed) {
13885                            break;
13886                        }
13887                    }
13888                    if (!installAllowed) {
13889                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13890                    }
13891                }
13892                if (!pkgSetting.getInstalled(userId)) {
13893                    pkgSetting.setInstalled(true, userId);
13894                    pkgSetting.setHidden(false, userId);
13895                    pkgSetting.setInstallReason(installReason, userId);
13896                    mSettings.writePackageRestrictionsLPr(userId);
13897                    mSettings.writeKernelMappingLPr(pkgSetting);
13898                    installed = true;
13899                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13900                    // upgrade app from instant to full; we don't allow app downgrade
13901                    installed = true;
13902                }
13903                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13904            }
13905
13906            if (installed) {
13907                if (pkgSetting.pkg != null) {
13908                    synchronized (mInstallLock) {
13909                        // We don't need to freeze for a brand new install
13910                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13911                    }
13912                }
13913                sendPackageAddedForUser(packageName, pkgSetting, userId);
13914                synchronized (mPackages) {
13915                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13916                }
13917            }
13918        } finally {
13919            Binder.restoreCallingIdentity(callingId);
13920        }
13921
13922        return PackageManager.INSTALL_SUCCEEDED;
13923    }
13924
13925    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13926            boolean instantApp, boolean fullApp) {
13927        // no state specified; do nothing
13928        if (!instantApp && !fullApp) {
13929            return;
13930        }
13931        if (userId != UserHandle.USER_ALL) {
13932            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13933                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13934            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13935                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13936            }
13937        } else {
13938            for (int currentUserId : sUserManager.getUserIds()) {
13939                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13940                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13941                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13942                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13943                }
13944            }
13945        }
13946    }
13947
13948    boolean isUserRestricted(int userId, String restrictionKey) {
13949        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13950        if (restrictions.getBoolean(restrictionKey, false)) {
13951            Log.w(TAG, "User is restricted: " + restrictionKey);
13952            return true;
13953        }
13954        return false;
13955    }
13956
13957    @Override
13958    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13959            int userId) {
13960        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13961        final int callingUid = Binder.getCallingUid();
13962        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13963                true /* requireFullPermission */, true /* checkShell */,
13964                "setPackagesSuspended for user " + userId);
13965
13966        if (ArrayUtils.isEmpty(packageNames)) {
13967            return packageNames;
13968        }
13969
13970        // List of package names for whom the suspended state has changed.
13971        List<String> changedPackages = new ArrayList<>(packageNames.length);
13972        // List of package names for whom the suspended state is not set as requested in this
13973        // method.
13974        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13975        long callingId = Binder.clearCallingIdentity();
13976        try {
13977            for (int i = 0; i < packageNames.length; i++) {
13978                String packageName = packageNames[i];
13979                boolean changed = false;
13980                final int appId;
13981                synchronized (mPackages) {
13982                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13983                    if (pkgSetting == null
13984                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13985                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13986                                + "\". Skipping suspending/un-suspending.");
13987                        unactionedPackages.add(packageName);
13988                        continue;
13989                    }
13990                    appId = pkgSetting.appId;
13991                    if (pkgSetting.getSuspended(userId) != suspended) {
13992                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13993                            unactionedPackages.add(packageName);
13994                            continue;
13995                        }
13996                        pkgSetting.setSuspended(suspended, userId);
13997                        mSettings.writePackageRestrictionsLPr(userId);
13998                        changed = true;
13999                        changedPackages.add(packageName);
14000                    }
14001                }
14002
14003                if (changed && suspended) {
14004                    killApplication(packageName, UserHandle.getUid(userId, appId),
14005                            "suspending package");
14006                }
14007            }
14008        } finally {
14009            Binder.restoreCallingIdentity(callingId);
14010        }
14011
14012        if (!changedPackages.isEmpty()) {
14013            sendPackagesSuspendedForUser(changedPackages.toArray(
14014                    new String[changedPackages.size()]), userId, suspended);
14015        }
14016
14017        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14018    }
14019
14020    @Override
14021    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14022        final int callingUid = Binder.getCallingUid();
14023        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14024                true /* requireFullPermission */, false /* checkShell */,
14025                "isPackageSuspendedForUser for user " + userId);
14026        synchronized (mPackages) {
14027            final PackageSetting ps = mSettings.mPackages.get(packageName);
14028            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14029                throw new IllegalArgumentException("Unknown target package: " + packageName);
14030            }
14031            return ps.getSuspended(userId);
14032        }
14033    }
14034
14035    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14036        if (isPackageDeviceAdmin(packageName, userId)) {
14037            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14038                    + "\": has an active device admin");
14039            return false;
14040        }
14041
14042        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14043        if (packageName.equals(activeLauncherPackageName)) {
14044            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14045                    + "\": contains the active launcher");
14046            return false;
14047        }
14048
14049        if (packageName.equals(mRequiredInstallerPackage)) {
14050            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14051                    + "\": required for package installation");
14052            return false;
14053        }
14054
14055        if (packageName.equals(mRequiredUninstallerPackage)) {
14056            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14057                    + "\": required for package uninstallation");
14058            return false;
14059        }
14060
14061        if (packageName.equals(mRequiredVerifierPackage)) {
14062            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14063                    + "\": required for package verification");
14064            return false;
14065        }
14066
14067        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14068            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14069                    + "\": is the default dialer");
14070            return false;
14071        }
14072
14073        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14074            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14075                    + "\": protected package");
14076            return false;
14077        }
14078
14079        // Cannot suspend static shared libs as they are considered
14080        // a part of the using app (emulating static linking). Also
14081        // static libs are installed always on internal storage.
14082        PackageParser.Package pkg = mPackages.get(packageName);
14083        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14084            Slog.w(TAG, "Cannot suspend package: " + packageName
14085                    + " providing static shared library: "
14086                    + pkg.staticSharedLibName);
14087            return false;
14088        }
14089
14090        return true;
14091    }
14092
14093    private String getActiveLauncherPackageName(int userId) {
14094        Intent intent = new Intent(Intent.ACTION_MAIN);
14095        intent.addCategory(Intent.CATEGORY_HOME);
14096        ResolveInfo resolveInfo = resolveIntent(
14097                intent,
14098                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14099                PackageManager.MATCH_DEFAULT_ONLY,
14100                userId);
14101
14102        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14103    }
14104
14105    private String getDefaultDialerPackageName(int userId) {
14106        synchronized (mPackages) {
14107            return mSettings.getDefaultDialerPackageNameLPw(userId);
14108        }
14109    }
14110
14111    @Override
14112    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14113        mContext.enforceCallingOrSelfPermission(
14114                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14115                "Only package verification agents can verify applications");
14116
14117        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14118        final PackageVerificationResponse response = new PackageVerificationResponse(
14119                verificationCode, Binder.getCallingUid());
14120        msg.arg1 = id;
14121        msg.obj = response;
14122        mHandler.sendMessage(msg);
14123    }
14124
14125    @Override
14126    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14127            long millisecondsToDelay) {
14128        mContext.enforceCallingOrSelfPermission(
14129                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14130                "Only package verification agents can extend verification timeouts");
14131
14132        final PackageVerificationState state = mPendingVerification.get(id);
14133        final PackageVerificationResponse response = new PackageVerificationResponse(
14134                verificationCodeAtTimeout, Binder.getCallingUid());
14135
14136        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14137            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14138        }
14139        if (millisecondsToDelay < 0) {
14140            millisecondsToDelay = 0;
14141        }
14142        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14143                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14144            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14145        }
14146
14147        if ((state != null) && !state.timeoutExtended()) {
14148            state.extendTimeout();
14149
14150            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14151            msg.arg1 = id;
14152            msg.obj = response;
14153            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14154        }
14155    }
14156
14157    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14158            int verificationCode, UserHandle user) {
14159        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14160        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14161        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14162        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14163        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14164
14165        mContext.sendBroadcastAsUser(intent, user,
14166                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14167    }
14168
14169    private ComponentName matchComponentForVerifier(String packageName,
14170            List<ResolveInfo> receivers) {
14171        ActivityInfo targetReceiver = null;
14172
14173        final int NR = receivers.size();
14174        for (int i = 0; i < NR; i++) {
14175            final ResolveInfo info = receivers.get(i);
14176            if (info.activityInfo == null) {
14177                continue;
14178            }
14179
14180            if (packageName.equals(info.activityInfo.packageName)) {
14181                targetReceiver = info.activityInfo;
14182                break;
14183            }
14184        }
14185
14186        if (targetReceiver == null) {
14187            return null;
14188        }
14189
14190        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14191    }
14192
14193    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14194            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14195        if (pkgInfo.verifiers.length == 0) {
14196            return null;
14197        }
14198
14199        final int N = pkgInfo.verifiers.length;
14200        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14201        for (int i = 0; i < N; i++) {
14202            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14203
14204            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14205                    receivers);
14206            if (comp == null) {
14207                continue;
14208            }
14209
14210            final int verifierUid = getUidForVerifier(verifierInfo);
14211            if (verifierUid == -1) {
14212                continue;
14213            }
14214
14215            if (DEBUG_VERIFY) {
14216                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14217                        + " with the correct signature");
14218            }
14219            sufficientVerifiers.add(comp);
14220            verificationState.addSufficientVerifier(verifierUid);
14221        }
14222
14223        return sufficientVerifiers;
14224    }
14225
14226    private int getUidForVerifier(VerifierInfo verifierInfo) {
14227        synchronized (mPackages) {
14228            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14229            if (pkg == null) {
14230                return -1;
14231            } else if (pkg.mSigningDetails.signatures.length != 1) {
14232                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14233                        + " has more than one signature; ignoring");
14234                return -1;
14235            }
14236
14237            /*
14238             * If the public key of the package's signature does not match
14239             * our expected public key, then this is a different package and
14240             * we should skip.
14241             */
14242
14243            final byte[] expectedPublicKey;
14244            try {
14245                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14246                final PublicKey publicKey = verifierSig.getPublicKey();
14247                expectedPublicKey = publicKey.getEncoded();
14248            } catch (CertificateException e) {
14249                return -1;
14250            }
14251
14252            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14253
14254            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14255                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14256                        + " does not have the expected public key; ignoring");
14257                return -1;
14258            }
14259
14260            return pkg.applicationInfo.uid;
14261        }
14262    }
14263
14264    @Override
14265    public void finishPackageInstall(int token, boolean didLaunch) {
14266        enforceSystemOrRoot("Only the system is allowed to finish installs");
14267
14268        if (DEBUG_INSTALL) {
14269            Slog.v(TAG, "BM finishing package install for " + token);
14270        }
14271        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14272
14273        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14274        mHandler.sendMessage(msg);
14275    }
14276
14277    /**
14278     * Get the verification agent timeout.  Used for both the APK verifier and the
14279     * intent filter verifier.
14280     *
14281     * @return verification timeout in milliseconds
14282     */
14283    private long getVerificationTimeout() {
14284        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14285                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14286                DEFAULT_VERIFICATION_TIMEOUT);
14287    }
14288
14289    /**
14290     * Get the default verification agent response code.
14291     *
14292     * @return default verification response code
14293     */
14294    private int getDefaultVerificationResponse(UserHandle user) {
14295        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14296            return PackageManager.VERIFICATION_REJECT;
14297        }
14298        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14299                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14300                DEFAULT_VERIFICATION_RESPONSE);
14301    }
14302
14303    /**
14304     * Check whether or not package verification has been enabled.
14305     *
14306     * @return true if verification should be performed
14307     */
14308    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14309        if (!DEFAULT_VERIFY_ENABLE) {
14310            return false;
14311        }
14312
14313        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14314
14315        // Check if installing from ADB
14316        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14317            // Do not run verification in a test harness environment
14318            if (ActivityManager.isRunningInTestHarness()) {
14319                return false;
14320            }
14321            if (ensureVerifyAppsEnabled) {
14322                return true;
14323            }
14324            // Check if the developer does not want package verification for ADB installs
14325            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14326                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14327                return false;
14328            }
14329        } else {
14330            // only when not installed from ADB, skip verification for instant apps when
14331            // the installer and verifier are the same.
14332            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14333                if (mInstantAppInstallerActivity != null
14334                        && mInstantAppInstallerActivity.packageName.equals(
14335                                mRequiredVerifierPackage)) {
14336                    try {
14337                        mContext.getSystemService(AppOpsManager.class)
14338                                .checkPackage(installerUid, mRequiredVerifierPackage);
14339                        if (DEBUG_VERIFY) {
14340                            Slog.i(TAG, "disable verification for instant app");
14341                        }
14342                        return false;
14343                    } catch (SecurityException ignore) { }
14344                }
14345            }
14346        }
14347
14348        if (ensureVerifyAppsEnabled) {
14349            return true;
14350        }
14351
14352        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14353                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14354    }
14355
14356    @Override
14357    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14358            throws RemoteException {
14359        mContext.enforceCallingOrSelfPermission(
14360                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14361                "Only intentfilter verification agents can verify applications");
14362
14363        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14364        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14365                Binder.getCallingUid(), verificationCode, failedDomains);
14366        msg.arg1 = id;
14367        msg.obj = response;
14368        mHandler.sendMessage(msg);
14369    }
14370
14371    @Override
14372    public int getIntentVerificationStatus(String packageName, int userId) {
14373        final int callingUid = Binder.getCallingUid();
14374        if (UserHandle.getUserId(callingUid) != userId) {
14375            mContext.enforceCallingOrSelfPermission(
14376                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14377                    "getIntentVerificationStatus" + userId);
14378        }
14379        if (getInstantAppPackageName(callingUid) != null) {
14380            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14381        }
14382        synchronized (mPackages) {
14383            final PackageSetting ps = mSettings.mPackages.get(packageName);
14384            if (ps == null
14385                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14386                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14387            }
14388            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14389        }
14390    }
14391
14392    @Override
14393    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14394        mContext.enforceCallingOrSelfPermission(
14395                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14396
14397        boolean result = false;
14398        synchronized (mPackages) {
14399            final PackageSetting ps = mSettings.mPackages.get(packageName);
14400            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14401                return false;
14402            }
14403            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14404        }
14405        if (result) {
14406            scheduleWritePackageRestrictionsLocked(userId);
14407        }
14408        return result;
14409    }
14410
14411    @Override
14412    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14413            String packageName) {
14414        final int callingUid = Binder.getCallingUid();
14415        if (getInstantAppPackageName(callingUid) != null) {
14416            return ParceledListSlice.emptyList();
14417        }
14418        synchronized (mPackages) {
14419            final PackageSetting ps = mSettings.mPackages.get(packageName);
14420            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14421                return ParceledListSlice.emptyList();
14422            }
14423            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14424        }
14425    }
14426
14427    @Override
14428    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14429        if (TextUtils.isEmpty(packageName)) {
14430            return ParceledListSlice.emptyList();
14431        }
14432        final int callingUid = Binder.getCallingUid();
14433        final int callingUserId = UserHandle.getUserId(callingUid);
14434        synchronized (mPackages) {
14435            PackageParser.Package pkg = mPackages.get(packageName);
14436            if (pkg == null || pkg.activities == null) {
14437                return ParceledListSlice.emptyList();
14438            }
14439            if (pkg.mExtras == null) {
14440                return ParceledListSlice.emptyList();
14441            }
14442            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14443            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14444                return ParceledListSlice.emptyList();
14445            }
14446            final int count = pkg.activities.size();
14447            ArrayList<IntentFilter> result = new ArrayList<>();
14448            for (int n=0; n<count; n++) {
14449                PackageParser.Activity activity = pkg.activities.get(n);
14450                if (activity.intents != null && activity.intents.size() > 0) {
14451                    result.addAll(activity.intents);
14452                }
14453            }
14454            return new ParceledListSlice<>(result);
14455        }
14456    }
14457
14458    @Override
14459    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14460        mContext.enforceCallingOrSelfPermission(
14461                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14462        if (UserHandle.getCallingUserId() != userId) {
14463            mContext.enforceCallingOrSelfPermission(
14464                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14465        }
14466
14467        synchronized (mPackages) {
14468            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14469            if (packageName != null) {
14470                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14471                        packageName, userId);
14472            }
14473            return result;
14474        }
14475    }
14476
14477    @Override
14478    public String getDefaultBrowserPackageName(int userId) {
14479        if (UserHandle.getCallingUserId() != userId) {
14480            mContext.enforceCallingOrSelfPermission(
14481                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14482        }
14483        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14484            return null;
14485        }
14486        synchronized (mPackages) {
14487            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14488        }
14489    }
14490
14491    /**
14492     * Get the "allow unknown sources" setting.
14493     *
14494     * @return the current "allow unknown sources" setting
14495     */
14496    private int getUnknownSourcesSettings() {
14497        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14498                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14499                -1);
14500    }
14501
14502    @Override
14503    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14504        final int callingUid = Binder.getCallingUid();
14505        if (getInstantAppPackageName(callingUid) != null) {
14506            return;
14507        }
14508        // writer
14509        synchronized (mPackages) {
14510            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14511            if (targetPackageSetting == null
14512                    || filterAppAccessLPr(
14513                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14514                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14515            }
14516
14517            PackageSetting installerPackageSetting;
14518            if (installerPackageName != null) {
14519                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14520                if (installerPackageSetting == null) {
14521                    throw new IllegalArgumentException("Unknown installer package: "
14522                            + installerPackageName);
14523                }
14524            } else {
14525                installerPackageSetting = null;
14526            }
14527
14528            Signature[] callerSignature;
14529            Object obj = mSettings.getUserIdLPr(callingUid);
14530            if (obj != null) {
14531                if (obj instanceof SharedUserSetting) {
14532                    callerSignature =
14533                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14534                } else if (obj instanceof PackageSetting) {
14535                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14536                } else {
14537                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14538                }
14539            } else {
14540                throw new SecurityException("Unknown calling UID: " + callingUid);
14541            }
14542
14543            // Verify: can't set installerPackageName to a package that is
14544            // not signed with the same cert as the caller.
14545            if (installerPackageSetting != null) {
14546                if (compareSignatures(callerSignature,
14547                        installerPackageSetting.signatures.mSigningDetails.signatures)
14548                        != PackageManager.SIGNATURE_MATCH) {
14549                    throw new SecurityException(
14550                            "Caller does not have same cert as new installer package "
14551                            + installerPackageName);
14552                }
14553            }
14554
14555            // Verify: if target already has an installer package, it must
14556            // be signed with the same cert as the caller.
14557            if (targetPackageSetting.installerPackageName != null) {
14558                PackageSetting setting = mSettings.mPackages.get(
14559                        targetPackageSetting.installerPackageName);
14560                // If the currently set package isn't valid, then it's always
14561                // okay to change it.
14562                if (setting != null) {
14563                    if (compareSignatures(callerSignature,
14564                            setting.signatures.mSigningDetails.signatures)
14565                            != PackageManager.SIGNATURE_MATCH) {
14566                        throw new SecurityException(
14567                                "Caller does not have same cert as old installer package "
14568                                + targetPackageSetting.installerPackageName);
14569                    }
14570                }
14571            }
14572
14573            // Okay!
14574            targetPackageSetting.installerPackageName = installerPackageName;
14575            if (installerPackageName != null) {
14576                mSettings.mInstallerPackages.add(installerPackageName);
14577            }
14578            scheduleWriteSettingsLocked();
14579        }
14580    }
14581
14582    @Override
14583    public void setApplicationCategoryHint(String packageName, int categoryHint,
14584            String callerPackageName) {
14585        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14586            throw new SecurityException("Instant applications don't have access to this method");
14587        }
14588        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14589                callerPackageName);
14590        synchronized (mPackages) {
14591            PackageSetting ps = mSettings.mPackages.get(packageName);
14592            if (ps == null) {
14593                throw new IllegalArgumentException("Unknown target package " + packageName);
14594            }
14595            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14596                throw new IllegalArgumentException("Unknown target package " + packageName);
14597            }
14598            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14599                throw new IllegalArgumentException("Calling package " + callerPackageName
14600                        + " is not installer for " + packageName);
14601            }
14602
14603            if (ps.categoryHint != categoryHint) {
14604                ps.categoryHint = categoryHint;
14605                scheduleWriteSettingsLocked();
14606            }
14607        }
14608    }
14609
14610    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14611        // Queue up an async operation since the package installation may take a little while.
14612        mHandler.post(new Runnable() {
14613            public void run() {
14614                mHandler.removeCallbacks(this);
14615                 // Result object to be returned
14616                PackageInstalledInfo res = new PackageInstalledInfo();
14617                res.setReturnCode(currentStatus);
14618                res.uid = -1;
14619                res.pkg = null;
14620                res.removedInfo = null;
14621                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14622                    args.doPreInstall(res.returnCode);
14623                    synchronized (mInstallLock) {
14624                        installPackageTracedLI(args, res);
14625                    }
14626                    args.doPostInstall(res.returnCode, res.uid);
14627                }
14628
14629                // A restore should be performed at this point if (a) the install
14630                // succeeded, (b) the operation is not an update, and (c) the new
14631                // package has not opted out of backup participation.
14632                final boolean update = res.removedInfo != null
14633                        && res.removedInfo.removedPackage != null;
14634                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14635                boolean doRestore = !update
14636                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14637
14638                // Set up the post-install work request bookkeeping.  This will be used
14639                // and cleaned up by the post-install event handling regardless of whether
14640                // there's a restore pass performed.  Token values are >= 1.
14641                int token;
14642                if (mNextInstallToken < 0) mNextInstallToken = 1;
14643                token = mNextInstallToken++;
14644
14645                PostInstallData data = new PostInstallData(args, res);
14646                mRunningInstalls.put(token, data);
14647                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14648
14649                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14650                    // Pass responsibility to the Backup Manager.  It will perform a
14651                    // restore if appropriate, then pass responsibility back to the
14652                    // Package Manager to run the post-install observer callbacks
14653                    // and broadcasts.
14654                    IBackupManager bm = IBackupManager.Stub.asInterface(
14655                            ServiceManager.getService(Context.BACKUP_SERVICE));
14656                    if (bm != null) {
14657                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14658                                + " to BM for possible restore");
14659                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14660                        try {
14661                            // TODO: http://b/22388012
14662                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14663                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14664                            } else {
14665                                doRestore = false;
14666                            }
14667                        } catch (RemoteException e) {
14668                            // can't happen; the backup manager is local
14669                        } catch (Exception e) {
14670                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14671                            doRestore = false;
14672                        }
14673                    } else {
14674                        Slog.e(TAG, "Backup Manager not found!");
14675                        doRestore = false;
14676                    }
14677                }
14678
14679                if (!doRestore) {
14680                    // No restore possible, or the Backup Manager was mysteriously not
14681                    // available -- just fire the post-install work request directly.
14682                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14683
14684                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14685
14686                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14687                    mHandler.sendMessage(msg);
14688                }
14689            }
14690        });
14691    }
14692
14693    /**
14694     * Callback from PackageSettings whenever an app is first transitioned out of the
14695     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14696     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14697     * here whether the app is the target of an ongoing install, and only send the
14698     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14699     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14700     * handling.
14701     */
14702    void notifyFirstLaunch(final String packageName, final String installerPackage,
14703            final int userId) {
14704        // Serialize this with the rest of the install-process message chain.  In the
14705        // restore-at-install case, this Runnable will necessarily run before the
14706        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14707        // are coherent.  In the non-restore case, the app has already completed install
14708        // and been launched through some other means, so it is not in a problematic
14709        // state for observers to see the FIRST_LAUNCH signal.
14710        mHandler.post(new Runnable() {
14711            @Override
14712            public void run() {
14713                for (int i = 0; i < mRunningInstalls.size(); i++) {
14714                    final PostInstallData data = mRunningInstalls.valueAt(i);
14715                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14716                        continue;
14717                    }
14718                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14719                        // right package; but is it for the right user?
14720                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14721                            if (userId == data.res.newUsers[uIndex]) {
14722                                if (DEBUG_BACKUP) {
14723                                    Slog.i(TAG, "Package " + packageName
14724                                            + " being restored so deferring FIRST_LAUNCH");
14725                                }
14726                                return;
14727                            }
14728                        }
14729                    }
14730                }
14731                // didn't find it, so not being restored
14732                if (DEBUG_BACKUP) {
14733                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14734                }
14735                final boolean isInstantApp = isInstantApp(packageName, userId);
14736                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14737                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14738                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14739            }
14740        });
14741    }
14742
14743    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14744            int[] userIds, int[] instantUserIds) {
14745        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14746                installerPkg, null, userIds, instantUserIds);
14747    }
14748
14749    private abstract class HandlerParams {
14750        private static final int MAX_RETRIES = 4;
14751
14752        /**
14753         * Number of times startCopy() has been attempted and had a non-fatal
14754         * error.
14755         */
14756        private int mRetries = 0;
14757
14758        /** User handle for the user requesting the information or installation. */
14759        private final UserHandle mUser;
14760        String traceMethod;
14761        int traceCookie;
14762
14763        HandlerParams(UserHandle user) {
14764            mUser = user;
14765        }
14766
14767        UserHandle getUser() {
14768            return mUser;
14769        }
14770
14771        HandlerParams setTraceMethod(String traceMethod) {
14772            this.traceMethod = traceMethod;
14773            return this;
14774        }
14775
14776        HandlerParams setTraceCookie(int traceCookie) {
14777            this.traceCookie = traceCookie;
14778            return this;
14779        }
14780
14781        final boolean startCopy() {
14782            boolean res;
14783            try {
14784                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14785
14786                if (++mRetries > MAX_RETRIES) {
14787                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14788                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14789                    handleServiceError();
14790                    return false;
14791                } else {
14792                    handleStartCopy();
14793                    res = true;
14794                }
14795            } catch (RemoteException e) {
14796                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14797                mHandler.sendEmptyMessage(MCS_RECONNECT);
14798                res = false;
14799            }
14800            handleReturnCode();
14801            return res;
14802        }
14803
14804        final void serviceError() {
14805            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14806            handleServiceError();
14807            handleReturnCode();
14808        }
14809
14810        abstract void handleStartCopy() throws RemoteException;
14811        abstract void handleServiceError();
14812        abstract void handleReturnCode();
14813    }
14814
14815    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14816        for (File path : paths) {
14817            try {
14818                mcs.clearDirectory(path.getAbsolutePath());
14819            } catch (RemoteException e) {
14820            }
14821        }
14822    }
14823
14824    static class OriginInfo {
14825        /**
14826         * Location where install is coming from, before it has been
14827         * copied/renamed into place. This could be a single monolithic APK
14828         * file, or a cluster directory. This location may be untrusted.
14829         */
14830        final File file;
14831
14832        /**
14833         * Flag indicating that {@link #file} or {@link #cid} has already been
14834         * staged, meaning downstream users don't need to defensively copy the
14835         * contents.
14836         */
14837        final boolean staged;
14838
14839        /**
14840         * Flag indicating that {@link #file} or {@link #cid} is an already
14841         * installed app that is being moved.
14842         */
14843        final boolean existing;
14844
14845        final String resolvedPath;
14846        final File resolvedFile;
14847
14848        static OriginInfo fromNothing() {
14849            return new OriginInfo(null, false, false);
14850        }
14851
14852        static OriginInfo fromUntrustedFile(File file) {
14853            return new OriginInfo(file, false, false);
14854        }
14855
14856        static OriginInfo fromExistingFile(File file) {
14857            return new OriginInfo(file, false, true);
14858        }
14859
14860        static OriginInfo fromStagedFile(File file) {
14861            return new OriginInfo(file, true, false);
14862        }
14863
14864        private OriginInfo(File file, boolean staged, boolean existing) {
14865            this.file = file;
14866            this.staged = staged;
14867            this.existing = existing;
14868
14869            if (file != null) {
14870                resolvedPath = file.getAbsolutePath();
14871                resolvedFile = file;
14872            } else {
14873                resolvedPath = null;
14874                resolvedFile = null;
14875            }
14876        }
14877    }
14878
14879    static class MoveInfo {
14880        final int moveId;
14881        final String fromUuid;
14882        final String toUuid;
14883        final String packageName;
14884        final String dataAppName;
14885        final int appId;
14886        final String seinfo;
14887        final int targetSdkVersion;
14888
14889        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14890                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14891            this.moveId = moveId;
14892            this.fromUuid = fromUuid;
14893            this.toUuid = toUuid;
14894            this.packageName = packageName;
14895            this.dataAppName = dataAppName;
14896            this.appId = appId;
14897            this.seinfo = seinfo;
14898            this.targetSdkVersion = targetSdkVersion;
14899        }
14900    }
14901
14902    static class VerificationInfo {
14903        /** A constant used to indicate that a uid value is not present. */
14904        public static final int NO_UID = -1;
14905
14906        /** URI referencing where the package was downloaded from. */
14907        final Uri originatingUri;
14908
14909        /** HTTP referrer URI associated with the originatingURI. */
14910        final Uri referrer;
14911
14912        /** UID of the application that the install request originated from. */
14913        final int originatingUid;
14914
14915        /** UID of application requesting the install */
14916        final int installerUid;
14917
14918        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14919            this.originatingUri = originatingUri;
14920            this.referrer = referrer;
14921            this.originatingUid = originatingUid;
14922            this.installerUid = installerUid;
14923        }
14924    }
14925
14926    class InstallParams extends HandlerParams {
14927        final OriginInfo origin;
14928        final MoveInfo move;
14929        final IPackageInstallObserver2 observer;
14930        int installFlags;
14931        final String installerPackageName;
14932        final String volumeUuid;
14933        private InstallArgs mArgs;
14934        private int mRet;
14935        final String packageAbiOverride;
14936        final String[] grantedRuntimePermissions;
14937        final VerificationInfo verificationInfo;
14938        final PackageParser.SigningDetails signingDetails;
14939        final int installReason;
14940
14941        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14942                int installFlags, String installerPackageName, String volumeUuid,
14943                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14944                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14945            super(user);
14946            this.origin = origin;
14947            this.move = move;
14948            this.observer = observer;
14949            this.installFlags = installFlags;
14950            this.installerPackageName = installerPackageName;
14951            this.volumeUuid = volumeUuid;
14952            this.verificationInfo = verificationInfo;
14953            this.packageAbiOverride = packageAbiOverride;
14954            this.grantedRuntimePermissions = grantedPermissions;
14955            this.signingDetails = signingDetails;
14956            this.installReason = installReason;
14957        }
14958
14959        @Override
14960        public String toString() {
14961            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14962                    + " file=" + origin.file + "}";
14963        }
14964
14965        private int installLocationPolicy(PackageInfoLite pkgLite) {
14966            String packageName = pkgLite.packageName;
14967            int installLocation = pkgLite.installLocation;
14968            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14969            // reader
14970            synchronized (mPackages) {
14971                // Currently installed package which the new package is attempting to replace or
14972                // null if no such package is installed.
14973                PackageParser.Package installedPkg = mPackages.get(packageName);
14974                // Package which currently owns the data which the new package will own if installed.
14975                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14976                // will be null whereas dataOwnerPkg will contain information about the package
14977                // which was uninstalled while keeping its data.
14978                PackageParser.Package dataOwnerPkg = installedPkg;
14979                if (dataOwnerPkg  == null) {
14980                    PackageSetting ps = mSettings.mPackages.get(packageName);
14981                    if (ps != null) {
14982                        dataOwnerPkg = ps.pkg;
14983                    }
14984                }
14985
14986                if (dataOwnerPkg != null) {
14987                    // If installed, the package will get access to data left on the device by its
14988                    // predecessor. As a security measure, this is permited only if this is not a
14989                    // version downgrade or if the predecessor package is marked as debuggable and
14990                    // a downgrade is explicitly requested.
14991                    //
14992                    // On debuggable platform builds, downgrades are permitted even for
14993                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14994                    // not offer security guarantees and thus it's OK to disable some security
14995                    // mechanisms to make debugging/testing easier on those builds. However, even on
14996                    // debuggable builds downgrades of packages are permitted only if requested via
14997                    // installFlags. This is because we aim to keep the behavior of debuggable
14998                    // platform builds as close as possible to the behavior of non-debuggable
14999                    // platform builds.
15000                    final boolean downgradeRequested =
15001                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15002                    final boolean packageDebuggable =
15003                                (dataOwnerPkg.applicationInfo.flags
15004                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15005                    final boolean downgradePermitted =
15006                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15007                    if (!downgradePermitted) {
15008                        try {
15009                            checkDowngrade(dataOwnerPkg, pkgLite);
15010                        } catch (PackageManagerException e) {
15011                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15012                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15013                        }
15014                    }
15015                }
15016
15017                if (installedPkg != null) {
15018                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15019                        // Check for updated system application.
15020                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15021                            if (onSd) {
15022                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15023                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15024                            }
15025                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15026                        } else {
15027                            if (onSd) {
15028                                // Install flag overrides everything.
15029                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15030                            }
15031                            // If current upgrade specifies particular preference
15032                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15033                                // Application explicitly specified internal.
15034                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15035                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15036                                // App explictly prefers external. Let policy decide
15037                            } else {
15038                                // Prefer previous location
15039                                if (isExternal(installedPkg)) {
15040                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15041                                }
15042                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15043                            }
15044                        }
15045                    } else {
15046                        // Invalid install. Return error code
15047                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15048                    }
15049                }
15050            }
15051            // All the special cases have been taken care of.
15052            // Return result based on recommended install location.
15053            if (onSd) {
15054                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15055            }
15056            return pkgLite.recommendedInstallLocation;
15057        }
15058
15059        /*
15060         * Invoke remote method to get package information and install
15061         * location values. Override install location based on default
15062         * policy if needed and then create install arguments based
15063         * on the install location.
15064         */
15065        public void handleStartCopy() throws RemoteException {
15066            int ret = PackageManager.INSTALL_SUCCEEDED;
15067
15068            // If we're already staged, we've firmly committed to an install location
15069            if (origin.staged) {
15070                if (origin.file != null) {
15071                    installFlags |= PackageManager.INSTALL_INTERNAL;
15072                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15073                } else {
15074                    throw new IllegalStateException("Invalid stage location");
15075                }
15076            }
15077
15078            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15079            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15080            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15081            PackageInfoLite pkgLite = null;
15082
15083            if (onInt && onSd) {
15084                // Check if both bits are set.
15085                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15086                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15087            } else if (onSd && ephemeral) {
15088                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15089                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15090            } else {
15091                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15092                        packageAbiOverride);
15093
15094                if (DEBUG_INSTANT && ephemeral) {
15095                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15096                }
15097
15098                /*
15099                 * If we have too little free space, try to free cache
15100                 * before giving up.
15101                 */
15102                if (!origin.staged && pkgLite.recommendedInstallLocation
15103                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15104                    // TODO: focus freeing disk space on the target device
15105                    final StorageManager storage = StorageManager.from(mContext);
15106                    final long lowThreshold = storage.getStorageLowBytes(
15107                            Environment.getDataDirectory());
15108
15109                    final long sizeBytes = mContainerService.calculateInstalledSize(
15110                            origin.resolvedPath, packageAbiOverride);
15111
15112                    try {
15113                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15114                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15115                                installFlags, packageAbiOverride);
15116                    } catch (InstallerException e) {
15117                        Slog.w(TAG, "Failed to free cache", e);
15118                    }
15119
15120                    /*
15121                     * The cache free must have deleted the file we
15122                     * downloaded to install.
15123                     *
15124                     * TODO: fix the "freeCache" call to not delete
15125                     *       the file we care about.
15126                     */
15127                    if (pkgLite.recommendedInstallLocation
15128                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15129                        pkgLite.recommendedInstallLocation
15130                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15131                    }
15132                }
15133            }
15134
15135            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15136                int loc = pkgLite.recommendedInstallLocation;
15137                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15138                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15139                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15140                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15141                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15142                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15143                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15144                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15145                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15146                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15147                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15148                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15149                } else {
15150                    // Override with defaults if needed.
15151                    loc = installLocationPolicy(pkgLite);
15152                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15153                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15154                    } else if (!onSd && !onInt) {
15155                        // Override install location with flags
15156                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15157                            // Set the flag to install on external media.
15158                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15159                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15160                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15161                            if (DEBUG_INSTANT) {
15162                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15163                            }
15164                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15165                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15166                                    |PackageManager.INSTALL_INTERNAL);
15167                        } else {
15168                            // Make sure the flag for installing on external
15169                            // media is unset
15170                            installFlags |= PackageManager.INSTALL_INTERNAL;
15171                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15172                        }
15173                    }
15174                }
15175            }
15176
15177            final InstallArgs args = createInstallArgs(this);
15178            mArgs = args;
15179
15180            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15181                // TODO: http://b/22976637
15182                // Apps installed for "all" users use the device owner to verify the app
15183                UserHandle verifierUser = getUser();
15184                if (verifierUser == UserHandle.ALL) {
15185                    verifierUser = UserHandle.SYSTEM;
15186                }
15187
15188                /*
15189                 * Determine if we have any installed package verifiers. If we
15190                 * do, then we'll defer to them to verify the packages.
15191                 */
15192                final int requiredUid = mRequiredVerifierPackage == null ? -1
15193                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15194                                verifierUser.getIdentifier());
15195                final int installerUid =
15196                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15197                if (!origin.existing && requiredUid != -1
15198                        && isVerificationEnabled(
15199                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15200                    final Intent verification = new Intent(
15201                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15202                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15203                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15204                            PACKAGE_MIME_TYPE);
15205                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15206
15207                    // Query all live verifiers based on current user state
15208                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15209                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15210                            false /*allowDynamicSplits*/);
15211
15212                    if (DEBUG_VERIFY) {
15213                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15214                                + verification.toString() + " with " + pkgLite.verifiers.length
15215                                + " optional verifiers");
15216                    }
15217
15218                    final int verificationId = mPendingVerificationToken++;
15219
15220                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15221
15222                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15223                            installerPackageName);
15224
15225                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15226                            installFlags);
15227
15228                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15229                            pkgLite.packageName);
15230
15231                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15232                            pkgLite.versionCode);
15233
15234                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15235                            pkgLite.getLongVersionCode());
15236
15237                    if (verificationInfo != null) {
15238                        if (verificationInfo.originatingUri != null) {
15239                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15240                                    verificationInfo.originatingUri);
15241                        }
15242                        if (verificationInfo.referrer != null) {
15243                            verification.putExtra(Intent.EXTRA_REFERRER,
15244                                    verificationInfo.referrer);
15245                        }
15246                        if (verificationInfo.originatingUid >= 0) {
15247                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15248                                    verificationInfo.originatingUid);
15249                        }
15250                        if (verificationInfo.installerUid >= 0) {
15251                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15252                                    verificationInfo.installerUid);
15253                        }
15254                    }
15255
15256                    final PackageVerificationState verificationState = new PackageVerificationState(
15257                            requiredUid, args);
15258
15259                    mPendingVerification.append(verificationId, verificationState);
15260
15261                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15262                            receivers, verificationState);
15263
15264                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15265                    final long idleDuration = getVerificationTimeout();
15266
15267                    /*
15268                     * If any sufficient verifiers were listed in the package
15269                     * manifest, attempt to ask them.
15270                     */
15271                    if (sufficientVerifiers != null) {
15272                        final int N = sufficientVerifiers.size();
15273                        if (N == 0) {
15274                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15275                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15276                        } else {
15277                            for (int i = 0; i < N; i++) {
15278                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15279                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15280                                        verifierComponent.getPackageName(), idleDuration,
15281                                        verifierUser.getIdentifier(), false, "package verifier");
15282
15283                                final Intent sufficientIntent = new Intent(verification);
15284                                sufficientIntent.setComponent(verifierComponent);
15285                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15286                            }
15287                        }
15288                    }
15289
15290                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15291                            mRequiredVerifierPackage, receivers);
15292                    if (ret == PackageManager.INSTALL_SUCCEEDED
15293                            && mRequiredVerifierPackage != null) {
15294                        Trace.asyncTraceBegin(
15295                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15296                        /*
15297                         * Send the intent to the required verification agent,
15298                         * but only start the verification timeout after the
15299                         * target BroadcastReceivers have run.
15300                         */
15301                        verification.setComponent(requiredVerifierComponent);
15302                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15303                                mRequiredVerifierPackage, idleDuration,
15304                                verifierUser.getIdentifier(), false, "package verifier");
15305                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15306                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15307                                new BroadcastReceiver() {
15308                                    @Override
15309                                    public void onReceive(Context context, Intent intent) {
15310                                        final Message msg = mHandler
15311                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15312                                        msg.arg1 = verificationId;
15313                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15314                                    }
15315                                }, null, 0, null, null);
15316
15317                        /*
15318                         * We don't want the copy to proceed until verification
15319                         * succeeds, so null out this field.
15320                         */
15321                        mArgs = null;
15322                    }
15323                } else {
15324                    /*
15325                     * No package verification is enabled, so immediately start
15326                     * the remote call to initiate copy using temporary file.
15327                     */
15328                    ret = args.copyApk(mContainerService, true);
15329                }
15330            }
15331
15332            mRet = ret;
15333        }
15334
15335        @Override
15336        void handleReturnCode() {
15337            // If mArgs is null, then MCS couldn't be reached. When it
15338            // reconnects, it will try again to install. At that point, this
15339            // will succeed.
15340            if (mArgs != null) {
15341                processPendingInstall(mArgs, mRet);
15342            }
15343        }
15344
15345        @Override
15346        void handleServiceError() {
15347            mArgs = createInstallArgs(this);
15348            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15349        }
15350    }
15351
15352    private InstallArgs createInstallArgs(InstallParams params) {
15353        if (params.move != null) {
15354            return new MoveInstallArgs(params);
15355        } else {
15356            return new FileInstallArgs(params);
15357        }
15358    }
15359
15360    /**
15361     * Create args that describe an existing installed package. Typically used
15362     * when cleaning up old installs, or used as a move source.
15363     */
15364    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15365            String resourcePath, String[] instructionSets) {
15366        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15367    }
15368
15369    static abstract class InstallArgs {
15370        /** @see InstallParams#origin */
15371        final OriginInfo origin;
15372        /** @see InstallParams#move */
15373        final MoveInfo move;
15374
15375        final IPackageInstallObserver2 observer;
15376        // Always refers to PackageManager flags only
15377        final int installFlags;
15378        final String installerPackageName;
15379        final String volumeUuid;
15380        final UserHandle user;
15381        final String abiOverride;
15382        final String[] installGrantPermissions;
15383        /** If non-null, drop an async trace when the install completes */
15384        final String traceMethod;
15385        final int traceCookie;
15386        final PackageParser.SigningDetails signingDetails;
15387        final int installReason;
15388
15389        // The list of instruction sets supported by this app. This is currently
15390        // only used during the rmdex() phase to clean up resources. We can get rid of this
15391        // if we move dex files under the common app path.
15392        /* nullable */ String[] instructionSets;
15393
15394        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15395                int installFlags, String installerPackageName, String volumeUuid,
15396                UserHandle user, String[] instructionSets,
15397                String abiOverride, String[] installGrantPermissions,
15398                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15399                int installReason) {
15400            this.origin = origin;
15401            this.move = move;
15402            this.installFlags = installFlags;
15403            this.observer = observer;
15404            this.installerPackageName = installerPackageName;
15405            this.volumeUuid = volumeUuid;
15406            this.user = user;
15407            this.instructionSets = instructionSets;
15408            this.abiOverride = abiOverride;
15409            this.installGrantPermissions = installGrantPermissions;
15410            this.traceMethod = traceMethod;
15411            this.traceCookie = traceCookie;
15412            this.signingDetails = signingDetails;
15413            this.installReason = installReason;
15414        }
15415
15416        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15417        abstract int doPreInstall(int status);
15418
15419        /**
15420         * Rename package into final resting place. All paths on the given
15421         * scanned package should be updated to reflect the rename.
15422         */
15423        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15424        abstract int doPostInstall(int status, int uid);
15425
15426        /** @see PackageSettingBase#codePathString */
15427        abstract String getCodePath();
15428        /** @see PackageSettingBase#resourcePathString */
15429        abstract String getResourcePath();
15430
15431        // Need installer lock especially for dex file removal.
15432        abstract void cleanUpResourcesLI();
15433        abstract boolean doPostDeleteLI(boolean delete);
15434
15435        /**
15436         * Called before the source arguments are copied. This is used mostly
15437         * for MoveParams when it needs to read the source file to put it in the
15438         * destination.
15439         */
15440        int doPreCopy() {
15441            return PackageManager.INSTALL_SUCCEEDED;
15442        }
15443
15444        /**
15445         * Called after the source arguments are copied. This is used mostly for
15446         * MoveParams when it needs to read the source file to put it in the
15447         * destination.
15448         */
15449        int doPostCopy(int uid) {
15450            return PackageManager.INSTALL_SUCCEEDED;
15451        }
15452
15453        protected boolean isFwdLocked() {
15454            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15455        }
15456
15457        protected boolean isExternalAsec() {
15458            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15459        }
15460
15461        protected boolean isEphemeral() {
15462            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15463        }
15464
15465        UserHandle getUser() {
15466            return user;
15467        }
15468    }
15469
15470    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15471        if (!allCodePaths.isEmpty()) {
15472            if (instructionSets == null) {
15473                throw new IllegalStateException("instructionSet == null");
15474            }
15475            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15476            for (String codePath : allCodePaths) {
15477                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15478                    try {
15479                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15480                    } catch (InstallerException ignored) {
15481                    }
15482                }
15483            }
15484        }
15485    }
15486
15487    /**
15488     * Logic to handle installation of non-ASEC applications, including copying
15489     * and renaming logic.
15490     */
15491    class FileInstallArgs extends InstallArgs {
15492        private File codeFile;
15493        private File resourceFile;
15494
15495        // Example topology:
15496        // /data/app/com.example/base.apk
15497        // /data/app/com.example/split_foo.apk
15498        // /data/app/com.example/lib/arm/libfoo.so
15499        // /data/app/com.example/lib/arm64/libfoo.so
15500        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15501
15502        /** New install */
15503        FileInstallArgs(InstallParams params) {
15504            super(params.origin, params.move, params.observer, params.installFlags,
15505                    params.installerPackageName, params.volumeUuid,
15506                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15507                    params.grantedRuntimePermissions,
15508                    params.traceMethod, params.traceCookie, params.signingDetails,
15509                    params.installReason);
15510            if (isFwdLocked()) {
15511                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15512            }
15513        }
15514
15515        /** Existing install */
15516        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15517            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15518                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15519                    PackageManager.INSTALL_REASON_UNKNOWN);
15520            this.codeFile = (codePath != null) ? new File(codePath) : null;
15521            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15522        }
15523
15524        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15525            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15526            try {
15527                return doCopyApk(imcs, temp);
15528            } finally {
15529                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15530            }
15531        }
15532
15533        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15534            if (origin.staged) {
15535                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15536                codeFile = origin.file;
15537                resourceFile = origin.file;
15538                return PackageManager.INSTALL_SUCCEEDED;
15539            }
15540
15541            try {
15542                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15543                final File tempDir =
15544                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15545                codeFile = tempDir;
15546                resourceFile = tempDir;
15547            } catch (IOException e) {
15548                Slog.w(TAG, "Failed to create copy file: " + e);
15549                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15550            }
15551
15552            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15553                @Override
15554                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15555                    if (!FileUtils.isValidExtFilename(name)) {
15556                        throw new IllegalArgumentException("Invalid filename: " + name);
15557                    }
15558                    try {
15559                        final File file = new File(codeFile, name);
15560                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15561                                O_RDWR | O_CREAT, 0644);
15562                        Os.chmod(file.getAbsolutePath(), 0644);
15563                        return new ParcelFileDescriptor(fd);
15564                    } catch (ErrnoException e) {
15565                        throw new RemoteException("Failed to open: " + e.getMessage());
15566                    }
15567                }
15568            };
15569
15570            int ret = PackageManager.INSTALL_SUCCEEDED;
15571            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15572            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15573                Slog.e(TAG, "Failed to copy package");
15574                return ret;
15575            }
15576
15577            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15578            NativeLibraryHelper.Handle handle = null;
15579            try {
15580                handle = NativeLibraryHelper.Handle.create(codeFile);
15581                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15582                        abiOverride);
15583            } catch (IOException e) {
15584                Slog.e(TAG, "Copying native libraries failed", e);
15585                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15586            } finally {
15587                IoUtils.closeQuietly(handle);
15588            }
15589
15590            return ret;
15591        }
15592
15593        int doPreInstall(int status) {
15594            if (status != PackageManager.INSTALL_SUCCEEDED) {
15595                cleanUp();
15596            }
15597            return status;
15598        }
15599
15600        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15601            if (status != PackageManager.INSTALL_SUCCEEDED) {
15602                cleanUp();
15603                return false;
15604            }
15605
15606            final File targetDir = codeFile.getParentFile();
15607            final File beforeCodeFile = codeFile;
15608            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15609
15610            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15611            try {
15612                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15613            } catch (ErrnoException e) {
15614                Slog.w(TAG, "Failed to rename", e);
15615                return false;
15616            }
15617
15618            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15619                Slog.w(TAG, "Failed to restorecon");
15620                return false;
15621            }
15622
15623            // Reflect the rename internally
15624            codeFile = afterCodeFile;
15625            resourceFile = afterCodeFile;
15626
15627            // Reflect the rename in scanned details
15628            try {
15629                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15630            } catch (IOException e) {
15631                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15632                return false;
15633            }
15634            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15635                    afterCodeFile, pkg.baseCodePath));
15636            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15637                    afterCodeFile, pkg.splitCodePaths));
15638
15639            // Reflect the rename in app info
15640            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15641            pkg.setApplicationInfoCodePath(pkg.codePath);
15642            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15643            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15644            pkg.setApplicationInfoResourcePath(pkg.codePath);
15645            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15646            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15647
15648            return true;
15649        }
15650
15651        int doPostInstall(int status, int uid) {
15652            if (status != PackageManager.INSTALL_SUCCEEDED) {
15653                cleanUp();
15654            }
15655            return status;
15656        }
15657
15658        @Override
15659        String getCodePath() {
15660            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15661        }
15662
15663        @Override
15664        String getResourcePath() {
15665            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15666        }
15667
15668        private boolean cleanUp() {
15669            if (codeFile == null || !codeFile.exists()) {
15670                return false;
15671            }
15672
15673            removeCodePathLI(codeFile);
15674
15675            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15676                resourceFile.delete();
15677            }
15678
15679            return true;
15680        }
15681
15682        void cleanUpResourcesLI() {
15683            // Try enumerating all code paths before deleting
15684            List<String> allCodePaths = Collections.EMPTY_LIST;
15685            if (codeFile != null && codeFile.exists()) {
15686                try {
15687                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15688                    allCodePaths = pkg.getAllCodePaths();
15689                } catch (PackageParserException e) {
15690                    // Ignored; we tried our best
15691                }
15692            }
15693
15694            cleanUp();
15695            removeDexFiles(allCodePaths, instructionSets);
15696        }
15697
15698        boolean doPostDeleteLI(boolean delete) {
15699            // XXX err, shouldn't we respect the delete flag?
15700            cleanUpResourcesLI();
15701            return true;
15702        }
15703    }
15704
15705    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15706            PackageManagerException {
15707        if (copyRet < 0) {
15708            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15709                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15710                throw new PackageManagerException(copyRet, message);
15711            }
15712        }
15713    }
15714
15715    /**
15716     * Extract the StorageManagerService "container ID" from the full code path of an
15717     * .apk.
15718     */
15719    static String cidFromCodePath(String fullCodePath) {
15720        int eidx = fullCodePath.lastIndexOf("/");
15721        String subStr1 = fullCodePath.substring(0, eidx);
15722        int sidx = subStr1.lastIndexOf("/");
15723        return subStr1.substring(sidx+1, eidx);
15724    }
15725
15726    /**
15727     * Logic to handle movement of existing installed applications.
15728     */
15729    class MoveInstallArgs extends InstallArgs {
15730        private File codeFile;
15731        private File resourceFile;
15732
15733        /** New install */
15734        MoveInstallArgs(InstallParams params) {
15735            super(params.origin, params.move, params.observer, params.installFlags,
15736                    params.installerPackageName, params.volumeUuid,
15737                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15738                    params.grantedRuntimePermissions,
15739                    params.traceMethod, params.traceCookie, params.signingDetails,
15740                    params.installReason);
15741        }
15742
15743        int copyApk(IMediaContainerService imcs, boolean temp) {
15744            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15745                    + move.fromUuid + " to " + move.toUuid);
15746            synchronized (mInstaller) {
15747                try {
15748                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15749                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15750                } catch (InstallerException e) {
15751                    Slog.w(TAG, "Failed to move app", e);
15752                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15753                }
15754            }
15755
15756            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15757            resourceFile = codeFile;
15758            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15759
15760            return PackageManager.INSTALL_SUCCEEDED;
15761        }
15762
15763        int doPreInstall(int status) {
15764            if (status != PackageManager.INSTALL_SUCCEEDED) {
15765                cleanUp(move.toUuid);
15766            }
15767            return status;
15768        }
15769
15770        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15771            if (status != PackageManager.INSTALL_SUCCEEDED) {
15772                cleanUp(move.toUuid);
15773                return false;
15774            }
15775
15776            // Reflect the move in app info
15777            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15778            pkg.setApplicationInfoCodePath(pkg.codePath);
15779            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15780            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15781            pkg.setApplicationInfoResourcePath(pkg.codePath);
15782            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15783            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15784
15785            return true;
15786        }
15787
15788        int doPostInstall(int status, int uid) {
15789            if (status == PackageManager.INSTALL_SUCCEEDED) {
15790                cleanUp(move.fromUuid);
15791            } else {
15792                cleanUp(move.toUuid);
15793            }
15794            return status;
15795        }
15796
15797        @Override
15798        String getCodePath() {
15799            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15800        }
15801
15802        @Override
15803        String getResourcePath() {
15804            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15805        }
15806
15807        private boolean cleanUp(String volumeUuid) {
15808            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15809                    move.dataAppName);
15810            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15811            final int[] userIds = sUserManager.getUserIds();
15812            synchronized (mInstallLock) {
15813                // Clean up both app data and code
15814                // All package moves are frozen until finished
15815                for (int userId : userIds) {
15816                    try {
15817                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15818                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15819                    } catch (InstallerException e) {
15820                        Slog.w(TAG, String.valueOf(e));
15821                    }
15822                }
15823                removeCodePathLI(codeFile);
15824            }
15825            return true;
15826        }
15827
15828        void cleanUpResourcesLI() {
15829            throw new UnsupportedOperationException();
15830        }
15831
15832        boolean doPostDeleteLI(boolean delete) {
15833            throw new UnsupportedOperationException();
15834        }
15835    }
15836
15837    static String getAsecPackageName(String packageCid) {
15838        int idx = packageCid.lastIndexOf("-");
15839        if (idx == -1) {
15840            return packageCid;
15841        }
15842        return packageCid.substring(0, idx);
15843    }
15844
15845    // Utility method used to create code paths based on package name and available index.
15846    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15847        String idxStr = "";
15848        int idx = 1;
15849        // Fall back to default value of idx=1 if prefix is not
15850        // part of oldCodePath
15851        if (oldCodePath != null) {
15852            String subStr = oldCodePath;
15853            // Drop the suffix right away
15854            if (suffix != null && subStr.endsWith(suffix)) {
15855                subStr = subStr.substring(0, subStr.length() - suffix.length());
15856            }
15857            // If oldCodePath already contains prefix find out the
15858            // ending index to either increment or decrement.
15859            int sidx = subStr.lastIndexOf(prefix);
15860            if (sidx != -1) {
15861                subStr = subStr.substring(sidx + prefix.length());
15862                if (subStr != null) {
15863                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15864                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15865                    }
15866                    try {
15867                        idx = Integer.parseInt(subStr);
15868                        if (idx <= 1) {
15869                            idx++;
15870                        } else {
15871                            idx--;
15872                        }
15873                    } catch(NumberFormatException e) {
15874                    }
15875                }
15876            }
15877        }
15878        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15879        return prefix + idxStr;
15880    }
15881
15882    private File getNextCodePath(File targetDir, String packageName) {
15883        File result;
15884        SecureRandom random = new SecureRandom();
15885        byte[] bytes = new byte[16];
15886        do {
15887            random.nextBytes(bytes);
15888            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15889            result = new File(targetDir, packageName + "-" + suffix);
15890        } while (result.exists());
15891        return result;
15892    }
15893
15894    // Utility method that returns the relative package path with respect
15895    // to the installation directory. Like say for /data/data/com.test-1.apk
15896    // string com.test-1 is returned.
15897    static String deriveCodePathName(String codePath) {
15898        if (codePath == null) {
15899            return null;
15900        }
15901        final File codeFile = new File(codePath);
15902        final String name = codeFile.getName();
15903        if (codeFile.isDirectory()) {
15904            return name;
15905        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15906            final int lastDot = name.lastIndexOf('.');
15907            return name.substring(0, lastDot);
15908        } else {
15909            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15910            return null;
15911        }
15912    }
15913
15914    static class PackageInstalledInfo {
15915        String name;
15916        int uid;
15917        // The set of users that originally had this package installed.
15918        int[] origUsers;
15919        // The set of users that now have this package installed.
15920        int[] newUsers;
15921        PackageParser.Package pkg;
15922        int returnCode;
15923        String returnMsg;
15924        String installerPackageName;
15925        PackageRemovedInfo removedInfo;
15926        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15927
15928        public void setError(int code, String msg) {
15929            setReturnCode(code);
15930            setReturnMessage(msg);
15931            Slog.w(TAG, msg);
15932        }
15933
15934        public void setError(String msg, PackageParserException e) {
15935            setReturnCode(e.error);
15936            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15937            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15938            for (int i = 0; i < childCount; i++) {
15939                addedChildPackages.valueAt(i).setError(msg, e);
15940            }
15941            Slog.w(TAG, msg, e);
15942        }
15943
15944        public void setError(String msg, PackageManagerException e) {
15945            returnCode = e.error;
15946            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15947            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15948            for (int i = 0; i < childCount; i++) {
15949                addedChildPackages.valueAt(i).setError(msg, e);
15950            }
15951            Slog.w(TAG, msg, e);
15952        }
15953
15954        public void setReturnCode(int returnCode) {
15955            this.returnCode = returnCode;
15956            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15957            for (int i = 0; i < childCount; i++) {
15958                addedChildPackages.valueAt(i).returnCode = returnCode;
15959            }
15960        }
15961
15962        private void setReturnMessage(String returnMsg) {
15963            this.returnMsg = returnMsg;
15964            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15965            for (int i = 0; i < childCount; i++) {
15966                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15967            }
15968        }
15969
15970        // In some error cases we want to convey more info back to the observer
15971        String origPackage;
15972        String origPermission;
15973    }
15974
15975    /*
15976     * Install a non-existing package.
15977     */
15978    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15979            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15980            String volumeUuid, PackageInstalledInfo res, int installReason) {
15981        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15982
15983        // Remember this for later, in case we need to rollback this install
15984        String pkgName = pkg.packageName;
15985
15986        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15987
15988        synchronized(mPackages) {
15989            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15990            if (renamedPackage != null) {
15991                // A package with the same name is already installed, though
15992                // it has been renamed to an older name.  The package we
15993                // are trying to install should be installed as an update to
15994                // the existing one, but that has not been requested, so bail.
15995                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15996                        + " without first uninstalling package running as "
15997                        + renamedPackage);
15998                return;
15999            }
16000            if (mPackages.containsKey(pkgName)) {
16001                // Don't allow installation over an existing package with the same name.
16002                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16003                        + " without first uninstalling.");
16004                return;
16005            }
16006        }
16007
16008        try {
16009            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16010                    System.currentTimeMillis(), user);
16011
16012            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16013
16014            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16015                prepareAppDataAfterInstallLIF(newPackage);
16016
16017            } else {
16018                // Remove package from internal structures, but keep around any
16019                // data that might have already existed
16020                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16021                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16022            }
16023        } catch (PackageManagerException e) {
16024            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16025        }
16026
16027        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16028    }
16029
16030    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16031        try (DigestInputStream digestStream =
16032                new DigestInputStream(new FileInputStream(file), digest)) {
16033            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16034        }
16035    }
16036
16037    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16038            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16039            PackageInstalledInfo res, int installReason) {
16040        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16041
16042        final PackageParser.Package oldPackage;
16043        final PackageSetting ps;
16044        final String pkgName = pkg.packageName;
16045        final int[] allUsers;
16046        final int[] installedUsers;
16047
16048        synchronized(mPackages) {
16049            oldPackage = mPackages.get(pkgName);
16050            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16051
16052            // don't allow upgrade to target a release SDK from a pre-release SDK
16053            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16054                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16055            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16056                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16057            if (oldTargetsPreRelease
16058                    && !newTargetsPreRelease
16059                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16060                Slog.w(TAG, "Can't install package targeting released sdk");
16061                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16062                return;
16063            }
16064
16065            ps = mSettings.mPackages.get(pkgName);
16066
16067            // verify signatures are valid
16068            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16069            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16070                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16071                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16072                            "New package not signed by keys specified by upgrade-keysets: "
16073                                    + pkgName);
16074                    return;
16075                }
16076            } else {
16077
16078                // default to original signature matching
16079                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16080                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16081                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16082                            "New package has a different signature: " + pkgName);
16083                    return;
16084                }
16085            }
16086
16087            // don't allow a system upgrade unless the upgrade hash matches
16088            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16089                byte[] digestBytes = null;
16090                try {
16091                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16092                    updateDigest(digest, new File(pkg.baseCodePath));
16093                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16094                        for (String path : pkg.splitCodePaths) {
16095                            updateDigest(digest, new File(path));
16096                        }
16097                    }
16098                    digestBytes = digest.digest();
16099                } catch (NoSuchAlgorithmException | IOException e) {
16100                    res.setError(INSTALL_FAILED_INVALID_APK,
16101                            "Could not compute hash: " + pkgName);
16102                    return;
16103                }
16104                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16105                    res.setError(INSTALL_FAILED_INVALID_APK,
16106                            "New package fails restrict-update check: " + pkgName);
16107                    return;
16108                }
16109                // retain upgrade restriction
16110                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16111            }
16112
16113            // Check for shared user id changes
16114            String invalidPackageName =
16115                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16116            if (invalidPackageName != null) {
16117                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16118                        "Package " + invalidPackageName + " tried to change user "
16119                                + oldPackage.mSharedUserId);
16120                return;
16121            }
16122
16123            // check if the new package supports all of the abis which the old package supports
16124            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16125            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16126            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16127                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16128                        "Update to package " + pkgName + " doesn't support multi arch");
16129                return;
16130            }
16131
16132            // In case of rollback, remember per-user/profile install state
16133            allUsers = sUserManager.getUserIds();
16134            installedUsers = ps.queryInstalledUsers(allUsers, true);
16135
16136            // don't allow an upgrade from full to ephemeral
16137            if (isInstantApp) {
16138                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16139                    for (int currentUser : allUsers) {
16140                        if (!ps.getInstantApp(currentUser)) {
16141                            // can't downgrade from full to instant
16142                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16143                                    + " for user: " + currentUser);
16144                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16145                            return;
16146                        }
16147                    }
16148                } else if (!ps.getInstantApp(user.getIdentifier())) {
16149                    // can't downgrade from full to instant
16150                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16151                            + " for user: " + user.getIdentifier());
16152                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16153                    return;
16154                }
16155            }
16156        }
16157
16158        // Update what is removed
16159        res.removedInfo = new PackageRemovedInfo(this);
16160        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16161        res.removedInfo.removedPackage = oldPackage.packageName;
16162        res.removedInfo.installerPackageName = ps.installerPackageName;
16163        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16164        res.removedInfo.isUpdate = true;
16165        res.removedInfo.origUsers = installedUsers;
16166        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16167        for (int i = 0; i < installedUsers.length; i++) {
16168            final int userId = installedUsers[i];
16169            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16170        }
16171
16172        final int childCount = (oldPackage.childPackages != null)
16173                ? oldPackage.childPackages.size() : 0;
16174        for (int i = 0; i < childCount; i++) {
16175            boolean childPackageUpdated = false;
16176            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16177            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16178            if (res.addedChildPackages != null) {
16179                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16180                if (childRes != null) {
16181                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16182                    childRes.removedInfo.removedPackage = childPkg.packageName;
16183                    if (childPs != null) {
16184                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16185                    }
16186                    childRes.removedInfo.isUpdate = true;
16187                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16188                    childPackageUpdated = true;
16189                }
16190            }
16191            if (!childPackageUpdated) {
16192                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16193                childRemovedRes.removedPackage = childPkg.packageName;
16194                if (childPs != null) {
16195                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16196                }
16197                childRemovedRes.isUpdate = false;
16198                childRemovedRes.dataRemoved = true;
16199                synchronized (mPackages) {
16200                    if (childPs != null) {
16201                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16202                    }
16203                }
16204                if (res.removedInfo.removedChildPackages == null) {
16205                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16206                }
16207                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16208            }
16209        }
16210
16211        boolean sysPkg = (isSystemApp(oldPackage));
16212        if (sysPkg) {
16213            // Set the system/privileged/oem/vendor/product flags as needed
16214            final boolean privileged =
16215                    (oldPackage.applicationInfo.privateFlags
16216                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16217            final boolean oem =
16218                    (oldPackage.applicationInfo.privateFlags
16219                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16220            final boolean vendor =
16221                    (oldPackage.applicationInfo.privateFlags
16222                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16223            final boolean product =
16224                    (oldPackage.applicationInfo.privateFlags
16225                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16226            final @ParseFlags int systemParseFlags = parseFlags;
16227            final @ScanFlags int systemScanFlags = scanFlags
16228                    | SCAN_AS_SYSTEM
16229                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16230                    | (oem ? SCAN_AS_OEM : 0)
16231                    | (vendor ? SCAN_AS_VENDOR : 0)
16232                    | (product ? SCAN_AS_PRODUCT : 0);
16233
16234            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16235                    user, allUsers, installerPackageName, res, installReason);
16236        } else {
16237            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16238                    user, allUsers, installerPackageName, res, installReason);
16239        }
16240    }
16241
16242    @Override
16243    public List<String> getPreviousCodePaths(String packageName) {
16244        final int callingUid = Binder.getCallingUid();
16245        final List<String> result = new ArrayList<>();
16246        if (getInstantAppPackageName(callingUid) != null) {
16247            return result;
16248        }
16249        final PackageSetting ps = mSettings.mPackages.get(packageName);
16250        if (ps != null
16251                && ps.oldCodePaths != null
16252                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16253            result.addAll(ps.oldCodePaths);
16254        }
16255        return result;
16256    }
16257
16258    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16259            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16260            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16261            String installerPackageName, PackageInstalledInfo res, int installReason) {
16262        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16263                + deletedPackage);
16264
16265        String pkgName = deletedPackage.packageName;
16266        boolean deletedPkg = true;
16267        boolean addedPkg = false;
16268        boolean updatedSettings = false;
16269        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16270        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16271                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16272
16273        final long origUpdateTime = (pkg.mExtras != null)
16274                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16275
16276        // First delete the existing package while retaining the data directory
16277        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16278                res.removedInfo, true, pkg)) {
16279            // If the existing package wasn't successfully deleted
16280            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16281            deletedPkg = false;
16282        } else {
16283            // Successfully deleted the old package; proceed with replace.
16284
16285            // If deleted package lived in a container, give users a chance to
16286            // relinquish resources before killing.
16287            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16288                if (DEBUG_INSTALL) {
16289                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16290                }
16291                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16292                final ArrayList<String> pkgList = new ArrayList<String>(1);
16293                pkgList.add(deletedPackage.applicationInfo.packageName);
16294                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16295            }
16296
16297            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16298                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16299
16300            try {
16301                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16302                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16303                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16304                        installReason);
16305
16306                // Update the in-memory copy of the previous code paths.
16307                PackageSetting ps = mSettings.mPackages.get(pkgName);
16308                if (!killApp) {
16309                    if (ps.oldCodePaths == null) {
16310                        ps.oldCodePaths = new ArraySet<>();
16311                    }
16312                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16313                    if (deletedPackage.splitCodePaths != null) {
16314                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16315                    }
16316                } else {
16317                    ps.oldCodePaths = null;
16318                }
16319                if (ps.childPackageNames != null) {
16320                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16321                        final String childPkgName = ps.childPackageNames.get(i);
16322                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16323                        childPs.oldCodePaths = ps.oldCodePaths;
16324                    }
16325                }
16326                // set instant app status, but, only if it's explicitly specified
16327                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16328                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16329                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16330                prepareAppDataAfterInstallLIF(newPackage);
16331                addedPkg = true;
16332                mDexManager.notifyPackageUpdated(newPackage.packageName,
16333                        newPackage.baseCodePath, newPackage.splitCodePaths);
16334            } catch (PackageManagerException e) {
16335                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16336            }
16337        }
16338
16339        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16340            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16341
16342            // Revert all internal state mutations and added folders for the failed install
16343            if (addedPkg) {
16344                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16345                        res.removedInfo, true, null);
16346            }
16347
16348            // Restore the old package
16349            if (deletedPkg) {
16350                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16351                File restoreFile = new File(deletedPackage.codePath);
16352                // Parse old package
16353                boolean oldExternal = isExternal(deletedPackage);
16354                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16355                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16356                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16357                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16358                try {
16359                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16360                            null);
16361                } catch (PackageManagerException e) {
16362                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16363                            + e.getMessage());
16364                    return;
16365                }
16366
16367                synchronized (mPackages) {
16368                    // Ensure the installer package name up to date
16369                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16370
16371                    // Update permissions for restored package
16372                    mPermissionManager.updatePermissions(
16373                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16374                            mPermissionCallback);
16375
16376                    mSettings.writeLPr();
16377                }
16378
16379                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16380            }
16381        } else {
16382            synchronized (mPackages) {
16383                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16384                if (ps != null) {
16385                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16386                    if (res.removedInfo.removedChildPackages != null) {
16387                        final int childCount = res.removedInfo.removedChildPackages.size();
16388                        // Iterate in reverse as we may modify the collection
16389                        for (int i = childCount - 1; i >= 0; i--) {
16390                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16391                            if (res.addedChildPackages.containsKey(childPackageName)) {
16392                                res.removedInfo.removedChildPackages.removeAt(i);
16393                            } else {
16394                                PackageRemovedInfo childInfo = res.removedInfo
16395                                        .removedChildPackages.valueAt(i);
16396                                childInfo.removedForAllUsers = mPackages.get(
16397                                        childInfo.removedPackage) == null;
16398                            }
16399                        }
16400                    }
16401                }
16402            }
16403        }
16404    }
16405
16406    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16407            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16408            final @ScanFlags int scanFlags, UserHandle user,
16409            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16410            int installReason) {
16411        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16412                + ", old=" + deletedPackage);
16413
16414        final boolean disabledSystem;
16415
16416        // Remove existing system package
16417        removePackageLI(deletedPackage, true);
16418
16419        synchronized (mPackages) {
16420            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16421        }
16422        if (!disabledSystem) {
16423            // We didn't need to disable the .apk as a current system package,
16424            // which means we are replacing another update that is already
16425            // installed.  We need to make sure to delete the older one's .apk.
16426            res.removedInfo.args = createInstallArgsForExisting(0,
16427                    deletedPackage.applicationInfo.getCodePath(),
16428                    deletedPackage.applicationInfo.getResourcePath(),
16429                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16430        } else {
16431            res.removedInfo.args = null;
16432        }
16433
16434        // Successfully disabled the old package. Now proceed with re-installation
16435        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16436                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16437
16438        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16439        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16440                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16441
16442        PackageParser.Package newPackage = null;
16443        try {
16444            // Add the package to the internal data structures
16445            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16446
16447            // Set the update and install times
16448            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16449            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16450                    System.currentTimeMillis());
16451
16452            // Update the package dynamic state if succeeded
16453            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16454                // Now that the install succeeded make sure we remove data
16455                // directories for any child package the update removed.
16456                final int deletedChildCount = (deletedPackage.childPackages != null)
16457                        ? deletedPackage.childPackages.size() : 0;
16458                final int newChildCount = (newPackage.childPackages != null)
16459                        ? newPackage.childPackages.size() : 0;
16460                for (int i = 0; i < deletedChildCount; i++) {
16461                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16462                    boolean childPackageDeleted = true;
16463                    for (int j = 0; j < newChildCount; j++) {
16464                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16465                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16466                            childPackageDeleted = false;
16467                            break;
16468                        }
16469                    }
16470                    if (childPackageDeleted) {
16471                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16472                                deletedChildPkg.packageName);
16473                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16474                            PackageRemovedInfo removedChildRes = res.removedInfo
16475                                    .removedChildPackages.get(deletedChildPkg.packageName);
16476                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16477                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16478                        }
16479                    }
16480                }
16481
16482                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16483                        installReason);
16484                prepareAppDataAfterInstallLIF(newPackage);
16485
16486                mDexManager.notifyPackageUpdated(newPackage.packageName,
16487                            newPackage.baseCodePath, newPackage.splitCodePaths);
16488            }
16489        } catch (PackageManagerException e) {
16490            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16491            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16492        }
16493
16494        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16495            // Re installation failed. Restore old information
16496            // Remove new pkg information
16497            if (newPackage != null) {
16498                removeInstalledPackageLI(newPackage, true);
16499            }
16500            // Add back the old system package
16501            try {
16502                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16503            } catch (PackageManagerException e) {
16504                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16505            }
16506
16507            synchronized (mPackages) {
16508                if (disabledSystem) {
16509                    enableSystemPackageLPw(deletedPackage);
16510                }
16511
16512                // Ensure the installer package name up to date
16513                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16514
16515                // Update permissions for restored package
16516                mPermissionManager.updatePermissions(
16517                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16518                        mPermissionCallback);
16519
16520                mSettings.writeLPr();
16521            }
16522
16523            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16524                    + " after failed upgrade");
16525        }
16526    }
16527
16528    /**
16529     * Checks whether the parent or any of the child packages have a change shared
16530     * user. For a package to be a valid update the shred users of the parent and
16531     * the children should match. We may later support changing child shared users.
16532     * @param oldPkg The updated package.
16533     * @param newPkg The update package.
16534     * @return The shared user that change between the versions.
16535     */
16536    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16537            PackageParser.Package newPkg) {
16538        // Check parent shared user
16539        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16540            return newPkg.packageName;
16541        }
16542        // Check child shared users
16543        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16544        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16545        for (int i = 0; i < newChildCount; i++) {
16546            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16547            // If this child was present, did it have the same shared user?
16548            for (int j = 0; j < oldChildCount; j++) {
16549                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16550                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16551                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16552                    return newChildPkg.packageName;
16553                }
16554            }
16555        }
16556        return null;
16557    }
16558
16559    private void removeNativeBinariesLI(PackageSetting ps) {
16560        // Remove the lib path for the parent package
16561        if (ps != null) {
16562            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16563            // Remove the lib path for the child packages
16564            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16565            for (int i = 0; i < childCount; i++) {
16566                PackageSetting childPs = null;
16567                synchronized (mPackages) {
16568                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16569                }
16570                if (childPs != null) {
16571                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16572                            .legacyNativeLibraryPathString);
16573                }
16574            }
16575        }
16576    }
16577
16578    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16579        // Enable the parent package
16580        mSettings.enableSystemPackageLPw(pkg.packageName);
16581        // Enable the child packages
16582        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16583        for (int i = 0; i < childCount; i++) {
16584            PackageParser.Package childPkg = pkg.childPackages.get(i);
16585            mSettings.enableSystemPackageLPw(childPkg.packageName);
16586        }
16587    }
16588
16589    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16590            PackageParser.Package newPkg) {
16591        // Disable the parent package (parent always replaced)
16592        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16593        // Disable the child packages
16594        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16595        for (int i = 0; i < childCount; i++) {
16596            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16597            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16598            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16599        }
16600        return disabled;
16601    }
16602
16603    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16604            String installerPackageName) {
16605        // Enable the parent package
16606        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16607        // Enable the child packages
16608        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16609        for (int i = 0; i < childCount; i++) {
16610            PackageParser.Package childPkg = pkg.childPackages.get(i);
16611            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16612        }
16613    }
16614
16615    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16616            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16617        // Update the parent package setting
16618        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16619                res, user, installReason);
16620        // Update the child packages setting
16621        final int childCount = (newPackage.childPackages != null)
16622                ? newPackage.childPackages.size() : 0;
16623        for (int i = 0; i < childCount; i++) {
16624            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16625            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16626            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16627                    childRes.origUsers, childRes, user, installReason);
16628        }
16629    }
16630
16631    private void updateSettingsInternalLI(PackageParser.Package pkg,
16632            String installerPackageName, int[] allUsers, int[] installedForUsers,
16633            PackageInstalledInfo res, UserHandle user, int installReason) {
16634        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16635
16636        String pkgName = pkg.packageName;
16637        synchronized (mPackages) {
16638            //write settings. the installStatus will be incomplete at this stage.
16639            //note that the new package setting would have already been
16640            //added to mPackages. It hasn't been persisted yet.
16641            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16642            // TODO: Remove this write? It's also written at the end of this method
16643            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16644            mSettings.writeLPr();
16645            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16646        }
16647
16648        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16649        synchronized (mPackages) {
16650// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16651            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16652                    mPermissionCallback);
16653            // For system-bundled packages, we assume that installing an upgraded version
16654            // of the package implies that the user actually wants to run that new code,
16655            // so we enable the package.
16656            PackageSetting ps = mSettings.mPackages.get(pkgName);
16657            final int userId = user.getIdentifier();
16658            if (ps != null) {
16659                if (isSystemApp(pkg)) {
16660                    if (DEBUG_INSTALL) {
16661                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16662                    }
16663                    // Enable system package for requested users
16664                    if (res.origUsers != null) {
16665                        for (int origUserId : res.origUsers) {
16666                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16667                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16668                                        origUserId, installerPackageName);
16669                            }
16670                        }
16671                    }
16672                    // Also convey the prior install/uninstall state
16673                    if (allUsers != null && installedForUsers != null) {
16674                        for (int currentUserId : allUsers) {
16675                            final boolean installed = ArrayUtils.contains(
16676                                    installedForUsers, currentUserId);
16677                            if (DEBUG_INSTALL) {
16678                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16679                            }
16680                            ps.setInstalled(installed, currentUserId);
16681                        }
16682                        // these install state changes will be persisted in the
16683                        // upcoming call to mSettings.writeLPr().
16684                    }
16685                }
16686                // It's implied that when a user requests installation, they want the app to be
16687                // installed and enabled.
16688                if (userId != UserHandle.USER_ALL) {
16689                    ps.setInstalled(true, userId);
16690                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16691                }
16692
16693                // When replacing an existing package, preserve the original install reason for all
16694                // users that had the package installed before.
16695                final Set<Integer> previousUserIds = new ArraySet<>();
16696                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16697                    final int installReasonCount = res.removedInfo.installReasons.size();
16698                    for (int i = 0; i < installReasonCount; i++) {
16699                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16700                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16701                        ps.setInstallReason(previousInstallReason, previousUserId);
16702                        previousUserIds.add(previousUserId);
16703                    }
16704                }
16705
16706                // Set install reason for users that are having the package newly installed.
16707                if (userId == UserHandle.USER_ALL) {
16708                    for (int currentUserId : sUserManager.getUserIds()) {
16709                        if (!previousUserIds.contains(currentUserId)) {
16710                            ps.setInstallReason(installReason, currentUserId);
16711                        }
16712                    }
16713                } else if (!previousUserIds.contains(userId)) {
16714                    ps.setInstallReason(installReason, userId);
16715                }
16716                mSettings.writeKernelMappingLPr(ps);
16717            }
16718            res.name = pkgName;
16719            res.uid = pkg.applicationInfo.uid;
16720            res.pkg = pkg;
16721            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16722            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16723            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16724            //to update install status
16725            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16726            mSettings.writeLPr();
16727            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16728        }
16729
16730        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16731    }
16732
16733    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16734        try {
16735            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16736            installPackageLI(args, res);
16737        } finally {
16738            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16739        }
16740    }
16741
16742    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16743        final int installFlags = args.installFlags;
16744        final String installerPackageName = args.installerPackageName;
16745        final String volumeUuid = args.volumeUuid;
16746        final File tmpPackageFile = new File(args.getCodePath());
16747        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16748        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16749                || (args.volumeUuid != null));
16750        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16751        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16752        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16753        final boolean virtualPreload =
16754                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16755        boolean replace = false;
16756        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16757        if (args.move != null) {
16758            // moving a complete application; perform an initial scan on the new install location
16759            scanFlags |= SCAN_INITIAL;
16760        }
16761        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16762            scanFlags |= SCAN_DONT_KILL_APP;
16763        }
16764        if (instantApp) {
16765            scanFlags |= SCAN_AS_INSTANT_APP;
16766        }
16767        if (fullApp) {
16768            scanFlags |= SCAN_AS_FULL_APP;
16769        }
16770        if (virtualPreload) {
16771            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16772        }
16773
16774        // Result object to be returned
16775        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16776        res.installerPackageName = installerPackageName;
16777
16778        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16779
16780        // Sanity check
16781        if (instantApp && (forwardLocked || onExternal)) {
16782            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16783                    + " external=" + onExternal);
16784            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16785            return;
16786        }
16787
16788        // Retrieve PackageSettings and parse package
16789        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16790                | PackageParser.PARSE_ENFORCE_CODE
16791                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16792                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16793                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16794        PackageParser pp = new PackageParser();
16795        pp.setSeparateProcesses(mSeparateProcesses);
16796        pp.setDisplayMetrics(mMetrics);
16797        pp.setCallback(mPackageParserCallback);
16798
16799        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16800        final PackageParser.Package pkg;
16801        try {
16802            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16803            DexMetadataHelper.validatePackageDexMetadata(pkg);
16804        } catch (PackageParserException e) {
16805            res.setError("Failed parse during installPackageLI", e);
16806            return;
16807        } finally {
16808            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16809        }
16810
16811        // Instant apps have several additional install-time checks.
16812        if (instantApp) {
16813            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16814                Slog.w(TAG,
16815                        "Instant app package " + pkg.packageName + " does not target at least O");
16816                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16817                        "Instant app package must target at least O");
16818                return;
16819            }
16820            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16821                Slog.w(TAG, "Instant app package " + pkg.packageName
16822                        + " does not target targetSandboxVersion 2");
16823                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16824                        "Instant app package must use targetSandboxVersion 2");
16825                return;
16826            }
16827            if (pkg.mSharedUserId != null) {
16828                Slog.w(TAG, "Instant app package " + pkg.packageName
16829                        + " may not declare sharedUserId.");
16830                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16831                        "Instant app package may not declare a sharedUserId");
16832                return;
16833            }
16834        }
16835
16836        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16837            // Static shared libraries have synthetic package names
16838            renameStaticSharedLibraryPackage(pkg);
16839
16840            // No static shared libs on external storage
16841            if (onExternal) {
16842                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16843                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16844                        "Packages declaring static-shared libs cannot be updated");
16845                return;
16846            }
16847        }
16848
16849        // If we are installing a clustered package add results for the children
16850        if (pkg.childPackages != null) {
16851            synchronized (mPackages) {
16852                final int childCount = pkg.childPackages.size();
16853                for (int i = 0; i < childCount; i++) {
16854                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16855                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16856                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16857                    childRes.pkg = childPkg;
16858                    childRes.name = childPkg.packageName;
16859                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16860                    if (childPs != null) {
16861                        childRes.origUsers = childPs.queryInstalledUsers(
16862                                sUserManager.getUserIds(), true);
16863                    }
16864                    if ((mPackages.containsKey(childPkg.packageName))) {
16865                        childRes.removedInfo = new PackageRemovedInfo(this);
16866                        childRes.removedInfo.removedPackage = childPkg.packageName;
16867                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16868                    }
16869                    if (res.addedChildPackages == null) {
16870                        res.addedChildPackages = new ArrayMap<>();
16871                    }
16872                    res.addedChildPackages.put(childPkg.packageName, childRes);
16873                }
16874            }
16875        }
16876
16877        // If package doesn't declare API override, mark that we have an install
16878        // time CPU ABI override.
16879        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16880            pkg.cpuAbiOverride = args.abiOverride;
16881        }
16882
16883        String pkgName = res.name = pkg.packageName;
16884        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16885            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16886                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16887                return;
16888            }
16889        }
16890
16891        try {
16892            // either use what we've been given or parse directly from the APK
16893            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16894                pkg.setSigningDetails(args.signingDetails);
16895            } else {
16896                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16897            }
16898        } catch (PackageParserException e) {
16899            res.setError("Failed collect during installPackageLI", e);
16900            return;
16901        }
16902
16903        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16904                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16905            Slog.w(TAG, "Instant app package " + pkg.packageName
16906                    + " is not signed with at least APK Signature Scheme v2");
16907            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16908                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16909            return;
16910        }
16911
16912        // Get rid of all references to package scan path via parser.
16913        pp = null;
16914        String oldCodePath = null;
16915        boolean systemApp = false;
16916        synchronized (mPackages) {
16917            // Check if installing already existing package
16918            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16919                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16920                if (pkg.mOriginalPackages != null
16921                        && pkg.mOriginalPackages.contains(oldName)
16922                        && mPackages.containsKey(oldName)) {
16923                    // This package is derived from an original package,
16924                    // and this device has been updating from that original
16925                    // name.  We must continue using the original name, so
16926                    // rename the new package here.
16927                    pkg.setPackageName(oldName);
16928                    pkgName = pkg.packageName;
16929                    replace = true;
16930                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16931                            + oldName + " pkgName=" + pkgName);
16932                } else if (mPackages.containsKey(pkgName)) {
16933                    // This package, under its official name, already exists
16934                    // on the device; we should replace it.
16935                    replace = true;
16936                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16937                }
16938
16939                // Child packages are installed through the parent package
16940                if (pkg.parentPackage != null) {
16941                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16942                            "Package " + pkg.packageName + " is child of package "
16943                                    + pkg.parentPackage.parentPackage + ". Child packages "
16944                                    + "can be updated only through the parent package.");
16945                    return;
16946                }
16947
16948                if (replace) {
16949                    // Prevent apps opting out from runtime permissions
16950                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16951                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16952                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16953                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16954                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16955                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16956                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16957                                        + " doesn't support runtime permissions but the old"
16958                                        + " target SDK " + oldTargetSdk + " does.");
16959                        return;
16960                    }
16961                    // Prevent persistent apps from being updated
16962                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16963                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16964                                "Package " + oldPackage.packageName + " is a persistent app. "
16965                                        + "Persistent apps are not updateable.");
16966                        return;
16967                    }
16968                    // Prevent apps from downgrading their targetSandbox.
16969                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16970                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16971                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16972                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16973                                "Package " + pkg.packageName + " new target sandbox "
16974                                + newTargetSandbox + " is incompatible with the previous value of"
16975                                + oldTargetSandbox + ".");
16976                        return;
16977                    }
16978
16979                    // Prevent installing of child packages
16980                    if (oldPackage.parentPackage != null) {
16981                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16982                                "Package " + pkg.packageName + " is child of package "
16983                                        + oldPackage.parentPackage + ". Child packages "
16984                                        + "can be updated only through the parent package.");
16985                        return;
16986                    }
16987                }
16988            }
16989
16990            PackageSetting ps = mSettings.mPackages.get(pkgName);
16991            if (ps != null) {
16992                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16993
16994                // Static shared libs have same package with different versions where
16995                // we internally use a synthetic package name to allow multiple versions
16996                // of the same package, therefore we need to compare signatures against
16997                // the package setting for the latest library version.
16998                PackageSetting signatureCheckPs = ps;
16999                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17000                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17001                    if (libraryEntry != null) {
17002                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17003                    }
17004                }
17005
17006                // Quick sanity check that we're signed correctly if updating;
17007                // we'll check this again later when scanning, but we want to
17008                // bail early here before tripping over redefined permissions.
17009                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17010                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17011                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17012                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17013                                + pkg.packageName + " upgrade keys do not match the "
17014                                + "previously installed version");
17015                        return;
17016                    }
17017                } else {
17018                    try {
17019                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17020                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17021                        // We don't care about disabledPkgSetting on install for now.
17022                        final boolean compatMatch = verifySignatures(
17023                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17024                                compareRecover);
17025                        // The new KeySets will be re-added later in the scanning process.
17026                        if (compatMatch) {
17027                            synchronized (mPackages) {
17028                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17029                            }
17030                        }
17031                    } catch (PackageManagerException e) {
17032                        res.setError(e.error, e.getMessage());
17033                        return;
17034                    }
17035                }
17036
17037                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17038                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17039                    systemApp = (ps.pkg.applicationInfo.flags &
17040                            ApplicationInfo.FLAG_SYSTEM) != 0;
17041                }
17042                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17043            }
17044
17045            int N = pkg.permissions.size();
17046            for (int i = N-1; i >= 0; i--) {
17047                final PackageParser.Permission perm = pkg.permissions.get(i);
17048                final BasePermission bp =
17049                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17050
17051                // Don't allow anyone but the system to define ephemeral permissions.
17052                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17053                        && !systemApp) {
17054                    Slog.w(TAG, "Non-System package " + pkg.packageName
17055                            + " attempting to delcare ephemeral permission "
17056                            + perm.info.name + "; Removing ephemeral.");
17057                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17058                }
17059
17060                // Check whether the newly-scanned package wants to define an already-defined perm
17061                if (bp != null) {
17062                    // If the defining package is signed with our cert, it's okay.  This
17063                    // also includes the "updating the same package" case, of course.
17064                    // "updating same package" could also involve key-rotation.
17065                    final boolean sigsOk;
17066                    final String sourcePackageName = bp.getSourcePackageName();
17067                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17068                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17069                    if (sourcePackageName.equals(pkg.packageName)
17070                            && (ksms.shouldCheckUpgradeKeySetLocked(
17071                                    sourcePackageSetting, scanFlags))) {
17072                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17073                    } else {
17074
17075                        // in the event of signing certificate rotation, we need to see if the
17076                        // package's certificate has rotated from the current one, or if it is an
17077                        // older certificate with which the current is ok with sharing permissions
17078                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17079                                        pkg.mSigningDetails,
17080                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17081                            sigsOk = true;
17082                        } else if (pkg.mSigningDetails.checkCapability(
17083                                        sourcePackageSetting.signatures.mSigningDetails,
17084                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17085
17086                            // the scanned package checks out, has signing certificate rotation
17087                            // history, and is newer; bring it over
17088                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17089                            sigsOk = true;
17090                        } else {
17091                            sigsOk = false;
17092                        }
17093                    }
17094                    if (!sigsOk) {
17095                        // If the owning package is the system itself, we log but allow
17096                        // install to proceed; we fail the install on all other permission
17097                        // redefinitions.
17098                        if (!sourcePackageName.equals("android")) {
17099                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17100                                    + pkg.packageName + " attempting to redeclare permission "
17101                                    + perm.info.name + " already owned by " + sourcePackageName);
17102                            res.origPermission = perm.info.name;
17103                            res.origPackage = sourcePackageName;
17104                            return;
17105                        } else {
17106                            Slog.w(TAG, "Package " + pkg.packageName
17107                                    + " attempting to redeclare system permission "
17108                                    + perm.info.name + "; ignoring new declaration");
17109                            pkg.permissions.remove(i);
17110                        }
17111                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17112                        // Prevent apps to change protection level to dangerous from any other
17113                        // type as this would allow a privilege escalation where an app adds a
17114                        // normal/signature permission in other app's group and later redefines
17115                        // it as dangerous leading to the group auto-grant.
17116                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17117                                == PermissionInfo.PROTECTION_DANGEROUS) {
17118                            if (bp != null && !bp.isRuntime()) {
17119                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17120                                        + "non-runtime permission " + perm.info.name
17121                                        + " to runtime; keeping old protection level");
17122                                perm.info.protectionLevel = bp.getProtectionLevel();
17123                            }
17124                        }
17125                    }
17126                }
17127            }
17128        }
17129
17130        if (systemApp) {
17131            if (onExternal) {
17132                // Abort update; system app can't be replaced with app on sdcard
17133                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17134                        "Cannot install updates to system apps on sdcard");
17135                return;
17136            } else if (instantApp) {
17137                // Abort update; system app can't be replaced with an instant app
17138                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17139                        "Cannot update a system app with an instant app");
17140                return;
17141            }
17142        }
17143
17144        if (args.move != null) {
17145            // We did an in-place move, so dex is ready to roll
17146            scanFlags |= SCAN_NO_DEX;
17147            scanFlags |= SCAN_MOVE;
17148
17149            synchronized (mPackages) {
17150                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17151                if (ps == null) {
17152                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17153                            "Missing settings for moved package " + pkgName);
17154                }
17155
17156                // We moved the entire application as-is, so bring over the
17157                // previously derived ABI information.
17158                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17159                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17160            }
17161
17162        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17163            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17164            scanFlags |= SCAN_NO_DEX;
17165
17166            try {
17167                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17168                    args.abiOverride : pkg.cpuAbiOverride);
17169                final boolean extractNativeLibs = !pkg.isLibrary();
17170                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17171            } catch (PackageManagerException pme) {
17172                Slog.e(TAG, "Error deriving application ABI", pme);
17173                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17174                return;
17175            }
17176
17177            // Shared libraries for the package need to be updated.
17178            synchronized (mPackages) {
17179                try {
17180                    updateSharedLibrariesLPr(pkg, null);
17181                } catch (PackageManagerException e) {
17182                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17183                }
17184            }
17185        }
17186
17187        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17188            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17189            return;
17190        }
17191
17192        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17193            String apkPath = null;
17194            synchronized (mPackages) {
17195                // Note that if the attacker managed to skip verify setup, for example by tampering
17196                // with the package settings, upon reboot we will do full apk verification when
17197                // verity is not detected.
17198                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17199                if (ps != null && ps.isPrivileged()) {
17200                    apkPath = pkg.baseCodePath;
17201                }
17202            }
17203
17204            if (apkPath != null) {
17205                final VerityUtils.SetupResult result =
17206                        VerityUtils.generateApkVeritySetupData(apkPath);
17207                if (result.isOk()) {
17208                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17209                    FileDescriptor fd = result.getUnownedFileDescriptor();
17210                    try {
17211                        mInstaller.installApkVerity(apkPath, fd);
17212                    } catch (InstallerException e) {
17213                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17214                                "Failed to set up verity: " + e);
17215                        return;
17216                    } finally {
17217                        IoUtils.closeQuietly(fd);
17218                    }
17219                } else if (result.isFailed()) {
17220                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17221                    return;
17222                } else {
17223                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17224                    // reboot.
17225                }
17226            }
17227        }
17228
17229        if (!instantApp) {
17230            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17231        } else {
17232            if (DEBUG_DOMAIN_VERIFICATION) {
17233                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17234            }
17235        }
17236
17237        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17238                "installPackageLI")) {
17239            if (replace) {
17240                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17241                    // Static libs have a synthetic package name containing the version
17242                    // and cannot be updated as an update would get a new package name,
17243                    // unless this is the exact same version code which is useful for
17244                    // development.
17245                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17246                    if (existingPkg != null &&
17247                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17248                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17249                                + "static-shared libs cannot be updated");
17250                        return;
17251                    }
17252                }
17253                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17254                        installerPackageName, res, args.installReason);
17255            } else {
17256                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17257                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17258            }
17259        }
17260
17261        // Prepare the application profiles for the new code paths.
17262        // This needs to be done before invoking dexopt so that any install-time profile
17263        // can be used for optimizations.
17264        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17265
17266        // Check whether we need to dexopt the app.
17267        //
17268        // NOTE: it is IMPORTANT to call dexopt:
17269        //   - after doRename which will sync the package data from PackageParser.Package and its
17270        //     corresponding ApplicationInfo.
17271        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17272        //     uid of the application (pkg.applicationInfo.uid).
17273        //     This update happens in place!
17274        //
17275        // We only need to dexopt if the package meets ALL of the following conditions:
17276        //   1) it is not forward locked.
17277        //   2) it is not on on an external ASEC container.
17278        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17279        //
17280        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17281        // complete, so we skip this step during installation. Instead, we'll take extra time
17282        // the first time the instant app starts. It's preferred to do it this way to provide
17283        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17284        // middle of running an instant app. The default behaviour can be overridden
17285        // via gservices.
17286        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17287                && !forwardLocked
17288                && !pkg.applicationInfo.isExternalAsec()
17289                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17290                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17291
17292        if (performDexopt) {
17293            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17294            // Do not run PackageDexOptimizer through the local performDexOpt
17295            // method because `pkg` may not be in `mPackages` yet.
17296            //
17297            // Also, don't fail application installs if the dexopt step fails.
17298            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17299                    REASON_INSTALL,
17300                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
17301            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17302                    null /* instructionSets */,
17303                    getOrCreateCompilerPackageStats(pkg),
17304                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17305                    dexoptOptions);
17306            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17307        }
17308
17309        // Notify BackgroundDexOptService that the package has been changed.
17310        // If this is an update of a package which used to fail to compile,
17311        // BackgroundDexOptService will remove it from its blacklist.
17312        // TODO: Layering violation
17313        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17314
17315        synchronized (mPackages) {
17316            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17317            if (ps != null) {
17318                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17319                ps.setUpdateAvailable(false /*updateAvailable*/);
17320            }
17321
17322            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17323            for (int i = 0; i < childCount; i++) {
17324                PackageParser.Package childPkg = pkg.childPackages.get(i);
17325                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17326                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17327                if (childPs != null) {
17328                    childRes.newUsers = childPs.queryInstalledUsers(
17329                            sUserManager.getUserIds(), true);
17330                }
17331            }
17332
17333            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17334                updateSequenceNumberLP(ps, res.newUsers);
17335                updateInstantAppInstallerLocked(pkgName);
17336            }
17337        }
17338    }
17339
17340    private void startIntentFilterVerifications(int userId, boolean replacing,
17341            PackageParser.Package pkg) {
17342        if (mIntentFilterVerifierComponent == null) {
17343            Slog.w(TAG, "No IntentFilter verification will not be done as "
17344                    + "there is no IntentFilterVerifier available!");
17345            return;
17346        }
17347
17348        final int verifierUid = getPackageUid(
17349                mIntentFilterVerifierComponent.getPackageName(),
17350                MATCH_DEBUG_TRIAGED_MISSING,
17351                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17352
17353        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17354        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17355        mHandler.sendMessage(msg);
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            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17361            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17362            mHandler.sendMessage(msg);
17363        }
17364    }
17365
17366    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17367            PackageParser.Package pkg) {
17368        int size = pkg.activities.size();
17369        if (size == 0) {
17370            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17371                    "No activity, so no need to verify any IntentFilter!");
17372            return;
17373        }
17374
17375        final boolean hasDomainURLs = hasDomainURLs(pkg);
17376        if (!hasDomainURLs) {
17377            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17378                    "No domain URLs, so no need to verify any IntentFilter!");
17379            return;
17380        }
17381
17382        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17383                + " if any IntentFilter from the " + size
17384                + " Activities needs verification ...");
17385
17386        int count = 0;
17387        final String packageName = pkg.packageName;
17388
17389        synchronized (mPackages) {
17390            // If this is a new install and we see that we've already run verification for this
17391            // package, we have nothing to do: it means the state was restored from backup.
17392            if (!replacing) {
17393                IntentFilterVerificationInfo ivi =
17394                        mSettings.getIntentFilterVerificationLPr(packageName);
17395                if (ivi != null) {
17396                    if (DEBUG_DOMAIN_VERIFICATION) {
17397                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17398                                + ivi.getStatusString());
17399                    }
17400                    return;
17401                }
17402            }
17403
17404            // If any filters need to be verified, then all need to be.
17405            boolean needToVerify = false;
17406            for (PackageParser.Activity a : pkg.activities) {
17407                for (ActivityIntentInfo filter : a.intents) {
17408                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17409                        if (DEBUG_DOMAIN_VERIFICATION) {
17410                            Slog.d(TAG,
17411                                    "Intent filter needs verification, so processing all filters");
17412                        }
17413                        needToVerify = true;
17414                        break;
17415                    }
17416                }
17417            }
17418
17419            if (needToVerify) {
17420                final int verificationId = mIntentFilterVerificationToken++;
17421                for (PackageParser.Activity a : pkg.activities) {
17422                    for (ActivityIntentInfo filter : a.intents) {
17423                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17424                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17425                                    "Verification needed for IntentFilter:" + filter.toString());
17426                            mIntentFilterVerifier.addOneIntentFilterVerification(
17427                                    verifierUid, userId, verificationId, filter, packageName);
17428                            count++;
17429                        }
17430                    }
17431                }
17432            }
17433        }
17434
17435        if (count > 0) {
17436            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17437                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17438                    +  " for userId:" + userId);
17439            mIntentFilterVerifier.startVerifications(userId);
17440        } else {
17441            if (DEBUG_DOMAIN_VERIFICATION) {
17442                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17443            }
17444        }
17445    }
17446
17447    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17448        final ComponentName cn  = filter.activity.getComponentName();
17449        final String packageName = cn.getPackageName();
17450
17451        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17452                packageName);
17453        if (ivi == null) {
17454            return true;
17455        }
17456        int status = ivi.getStatus();
17457        switch (status) {
17458            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17459            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17460                return true;
17461
17462            default:
17463                // Nothing to do
17464                return false;
17465        }
17466    }
17467
17468    private static boolean isMultiArch(ApplicationInfo info) {
17469        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17470    }
17471
17472    private static boolean isExternal(PackageParser.Package pkg) {
17473        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17474    }
17475
17476    private static boolean isExternal(PackageSetting ps) {
17477        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17478    }
17479
17480    private static boolean isSystemApp(PackageParser.Package pkg) {
17481        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17482    }
17483
17484    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17485        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17486    }
17487
17488    private static boolean isOemApp(PackageParser.Package pkg) {
17489        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17490    }
17491
17492    private static boolean isVendorApp(PackageParser.Package pkg) {
17493        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17494    }
17495
17496    private static boolean isProductApp(PackageParser.Package pkg) {
17497        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17498    }
17499
17500    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17501        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17502    }
17503
17504    private static boolean isSystemApp(PackageSetting ps) {
17505        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17506    }
17507
17508    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17509        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17510    }
17511
17512    private int packageFlagsToInstallFlags(PackageSetting ps) {
17513        int installFlags = 0;
17514        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17515            // This existing package was an external ASEC install when we have
17516            // the external flag without a UUID
17517            installFlags |= PackageManager.INSTALL_EXTERNAL;
17518        }
17519        if (ps.isForwardLocked()) {
17520            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17521        }
17522        return installFlags;
17523    }
17524
17525    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17526        if (isExternal(pkg)) {
17527            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17528                return mSettings.getExternalVersion();
17529            } else {
17530                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17531            }
17532        } else {
17533            return mSettings.getInternalVersion();
17534        }
17535    }
17536
17537    private void deleteTempPackageFiles() {
17538        final FilenameFilter filter = new FilenameFilter() {
17539            public boolean accept(File dir, String name) {
17540                return name.startsWith("vmdl") && name.endsWith(".tmp");
17541            }
17542        };
17543        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17544            file.delete();
17545        }
17546    }
17547
17548    @Override
17549    public void deletePackageAsUser(String packageName, int versionCode,
17550            IPackageDeleteObserver observer, int userId, int flags) {
17551        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17552                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17553    }
17554
17555    @Override
17556    public void deletePackageVersioned(VersionedPackage versionedPackage,
17557            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17558        final int callingUid = Binder.getCallingUid();
17559        mContext.enforceCallingOrSelfPermission(
17560                android.Manifest.permission.DELETE_PACKAGES, null);
17561        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17562        Preconditions.checkNotNull(versionedPackage);
17563        Preconditions.checkNotNull(observer);
17564        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17565                PackageManager.VERSION_CODE_HIGHEST,
17566                Long.MAX_VALUE, "versionCode must be >= -1");
17567
17568        final String packageName = versionedPackage.getPackageName();
17569        final long versionCode = versionedPackage.getLongVersionCode();
17570        final String internalPackageName;
17571        synchronized (mPackages) {
17572            // Normalize package name to handle renamed packages and static libs
17573            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17574        }
17575
17576        final int uid = Binder.getCallingUid();
17577        if (!isOrphaned(internalPackageName)
17578                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17579            try {
17580                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17581                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17582                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17583                observer.onUserActionRequired(intent);
17584            } catch (RemoteException re) {
17585            }
17586            return;
17587        }
17588        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17589        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17590        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17591            mContext.enforceCallingOrSelfPermission(
17592                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17593                    "deletePackage for user " + userId);
17594        }
17595
17596        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17597            try {
17598                observer.onPackageDeleted(packageName,
17599                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17600            } catch (RemoteException re) {
17601            }
17602            return;
17603        }
17604
17605        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17606            try {
17607                observer.onPackageDeleted(packageName,
17608                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17609            } catch (RemoteException re) {
17610            }
17611            return;
17612        }
17613
17614        if (DEBUG_REMOVE) {
17615            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17616                    + " deleteAllUsers: " + deleteAllUsers + " version="
17617                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17618                    ? "VERSION_CODE_HIGHEST" : versionCode));
17619        }
17620        // Queue up an async operation since the package deletion may take a little while.
17621        mHandler.post(new Runnable() {
17622            public void run() {
17623                mHandler.removeCallbacks(this);
17624                int returnCode;
17625                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17626                boolean doDeletePackage = true;
17627                if (ps != null) {
17628                    final boolean targetIsInstantApp =
17629                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17630                    doDeletePackage = !targetIsInstantApp
17631                            || canViewInstantApps;
17632                }
17633                if (doDeletePackage) {
17634                    if (!deleteAllUsers) {
17635                        returnCode = deletePackageX(internalPackageName, versionCode,
17636                                userId, deleteFlags);
17637                    } else {
17638                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17639                                internalPackageName, users);
17640                        // If nobody is blocking uninstall, proceed with delete for all users
17641                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17642                            returnCode = deletePackageX(internalPackageName, versionCode,
17643                                    userId, deleteFlags);
17644                        } else {
17645                            // Otherwise uninstall individually for users with blockUninstalls=false
17646                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17647                            for (int userId : users) {
17648                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17649                                    returnCode = deletePackageX(internalPackageName, versionCode,
17650                                            userId, userFlags);
17651                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17652                                        Slog.w(TAG, "Package delete failed for user " + userId
17653                                                + ", returnCode " + returnCode);
17654                                    }
17655                                }
17656                            }
17657                            // The app has only been marked uninstalled for certain users.
17658                            // We still need to report that delete was blocked
17659                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17660                        }
17661                    }
17662                } else {
17663                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17664                }
17665                try {
17666                    observer.onPackageDeleted(packageName, returnCode, null);
17667                } catch (RemoteException e) {
17668                    Log.i(TAG, "Observer no longer exists.");
17669                } //end catch
17670            } //end run
17671        });
17672    }
17673
17674    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17675        if (pkg.staticSharedLibName != null) {
17676            return pkg.manifestPackageName;
17677        }
17678        return pkg.packageName;
17679    }
17680
17681    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17682        // Handle renamed packages
17683        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17684        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17685
17686        // Is this a static library?
17687        LongSparseArray<SharedLibraryEntry> versionedLib =
17688                mStaticLibsByDeclaringPackage.get(packageName);
17689        if (versionedLib == null || versionedLib.size() <= 0) {
17690            return packageName;
17691        }
17692
17693        // Figure out which lib versions the caller can see
17694        LongSparseLongArray versionsCallerCanSee = null;
17695        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17696        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17697                && callingAppId != Process.ROOT_UID) {
17698            versionsCallerCanSee = new LongSparseLongArray();
17699            String libName = versionedLib.valueAt(0).info.getName();
17700            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17701            if (uidPackages != null) {
17702                for (String uidPackage : uidPackages) {
17703                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17704                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17705                    if (libIdx >= 0) {
17706                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17707                        versionsCallerCanSee.append(libVersion, libVersion);
17708                    }
17709                }
17710            }
17711        }
17712
17713        // Caller can see nothing - done
17714        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17715            return packageName;
17716        }
17717
17718        // Find the version the caller can see and the app version code
17719        SharedLibraryEntry highestVersion = null;
17720        final int versionCount = versionedLib.size();
17721        for (int i = 0; i < versionCount; i++) {
17722            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17723            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17724                    libEntry.info.getLongVersion()) < 0) {
17725                continue;
17726            }
17727            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17728            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17729                if (libVersionCode == versionCode) {
17730                    return libEntry.apk;
17731                }
17732            } else if (highestVersion == null) {
17733                highestVersion = libEntry;
17734            } else if (libVersionCode  > highestVersion.info
17735                    .getDeclaringPackage().getLongVersionCode()) {
17736                highestVersion = libEntry;
17737            }
17738        }
17739
17740        if (highestVersion != null) {
17741            return highestVersion.apk;
17742        }
17743
17744        return packageName;
17745    }
17746
17747    boolean isCallerVerifier(int callingUid) {
17748        final int callingUserId = UserHandle.getUserId(callingUid);
17749        return mRequiredVerifierPackage != null &&
17750                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17751    }
17752
17753    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17754        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17755              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17756            return true;
17757        }
17758        final int callingUserId = UserHandle.getUserId(callingUid);
17759        // If the caller installed the pkgName, then allow it to silently uninstall.
17760        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17761            return true;
17762        }
17763
17764        // Allow package verifier to silently uninstall.
17765        if (mRequiredVerifierPackage != null &&
17766                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17767            return true;
17768        }
17769
17770        // Allow package uninstaller to silently uninstall.
17771        if (mRequiredUninstallerPackage != null &&
17772                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17773            return true;
17774        }
17775
17776        // Allow storage manager to silently uninstall.
17777        if (mStorageManagerPackage != null &&
17778                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17779            return true;
17780        }
17781
17782        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17783        // uninstall for device owner provisioning.
17784        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17785                == PERMISSION_GRANTED) {
17786            return true;
17787        }
17788
17789        return false;
17790    }
17791
17792    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17793        int[] result = EMPTY_INT_ARRAY;
17794        for (int userId : userIds) {
17795            if (getBlockUninstallForUser(packageName, userId)) {
17796                result = ArrayUtils.appendInt(result, userId);
17797            }
17798        }
17799        return result;
17800    }
17801
17802    @Override
17803    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17804        final int callingUid = Binder.getCallingUid();
17805        if (getInstantAppPackageName(callingUid) != null
17806                && !isCallerSameApp(packageName, callingUid)) {
17807            return false;
17808        }
17809        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17810    }
17811
17812    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17813        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17814                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17815        try {
17816            if (dpm != null) {
17817                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17818                        /* callingUserOnly =*/ false);
17819                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17820                        : deviceOwnerComponentName.getPackageName();
17821                // Does the package contains the device owner?
17822                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17823                // this check is probably not needed, since DO should be registered as a device
17824                // admin on some user too. (Original bug for this: b/17657954)
17825                if (packageName.equals(deviceOwnerPackageName)) {
17826                    return true;
17827                }
17828                // Does it contain a device admin for any user?
17829                int[] users;
17830                if (userId == UserHandle.USER_ALL) {
17831                    users = sUserManager.getUserIds();
17832                } else {
17833                    users = new int[]{userId};
17834                }
17835                for (int i = 0; i < users.length; ++i) {
17836                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17837                        return true;
17838                    }
17839                }
17840            }
17841        } catch (RemoteException e) {
17842        }
17843        return false;
17844    }
17845
17846    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17847        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17848    }
17849
17850    /**
17851     *  This method is an internal method that could be get invoked either
17852     *  to delete an installed package or to clean up a failed installation.
17853     *  After deleting an installed package, a broadcast is sent to notify any
17854     *  listeners that the package has been removed. For cleaning up a failed
17855     *  installation, the broadcast is not necessary since the package's
17856     *  installation wouldn't have sent the initial broadcast either
17857     *  The key steps in deleting a package are
17858     *  deleting the package information in internal structures like mPackages,
17859     *  deleting the packages base directories through installd
17860     *  updating mSettings to reflect current status
17861     *  persisting settings for later use
17862     *  sending a broadcast if necessary
17863     */
17864    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17865        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17866        final boolean res;
17867
17868        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17869                ? UserHandle.USER_ALL : userId;
17870
17871        if (isPackageDeviceAdmin(packageName, removeUser)) {
17872            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17873            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17874        }
17875
17876        PackageSetting uninstalledPs = null;
17877        PackageParser.Package pkg = null;
17878
17879        // for the uninstall-updates case and restricted profiles, remember the per-
17880        // user handle installed state
17881        int[] allUsers;
17882        synchronized (mPackages) {
17883            uninstalledPs = mSettings.mPackages.get(packageName);
17884            if (uninstalledPs == null) {
17885                Slog.w(TAG, "Not removing non-existent package " + packageName);
17886                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17887            }
17888
17889            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17890                    && uninstalledPs.versionCode != versionCode) {
17891                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17892                        + uninstalledPs.versionCode + " != " + versionCode);
17893                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17894            }
17895
17896            // Static shared libs can be declared by any package, so let us not
17897            // allow removing a package if it provides a lib others depend on.
17898            pkg = mPackages.get(packageName);
17899
17900            allUsers = sUserManager.getUserIds();
17901
17902            if (pkg != null && pkg.staticSharedLibName != null) {
17903                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17904                        pkg.staticSharedLibVersion);
17905                if (libEntry != null) {
17906                    for (int currUserId : allUsers) {
17907                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17908                            continue;
17909                        }
17910                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17911                                libEntry.info, 0, currUserId);
17912                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17913                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17914                                    + " hosting lib " + libEntry.info.getName() + " version "
17915                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17916                                    + " for user " + currUserId);
17917                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17918                        }
17919                    }
17920                }
17921            }
17922
17923            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17924        }
17925
17926        final int freezeUser;
17927        if (isUpdatedSystemApp(uninstalledPs)
17928                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17929            // We're downgrading a system app, which will apply to all users, so
17930            // freeze them all during the downgrade
17931            freezeUser = UserHandle.USER_ALL;
17932        } else {
17933            freezeUser = removeUser;
17934        }
17935
17936        synchronized (mInstallLock) {
17937            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17938            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17939                    deleteFlags, "deletePackageX")) {
17940                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17941                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17942            }
17943            synchronized (mPackages) {
17944                if (res) {
17945                    if (pkg != null) {
17946                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17947                    }
17948                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17949                    updateInstantAppInstallerLocked(packageName);
17950                }
17951            }
17952        }
17953
17954        if (res) {
17955            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17956            info.sendPackageRemovedBroadcasts(killApp);
17957            info.sendSystemPackageUpdatedBroadcasts();
17958            info.sendSystemPackageAppearedBroadcasts();
17959        }
17960        // Force a gc here.
17961        Runtime.getRuntime().gc();
17962        // Delete the resources here after sending the broadcast to let
17963        // other processes clean up before deleting resources.
17964        if (info.args != null) {
17965            synchronized (mInstallLock) {
17966                info.args.doPostDeleteLI(true);
17967            }
17968        }
17969
17970        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17971    }
17972
17973    static class PackageRemovedInfo {
17974        final PackageSender packageSender;
17975        String removedPackage;
17976        String installerPackageName;
17977        int uid = -1;
17978        int removedAppId = -1;
17979        int[] origUsers;
17980        int[] removedUsers = null;
17981        int[] broadcastUsers = null;
17982        int[] instantUserIds = null;
17983        SparseArray<Integer> installReasons;
17984        boolean isRemovedPackageSystemUpdate = false;
17985        boolean isUpdate;
17986        boolean dataRemoved;
17987        boolean removedForAllUsers;
17988        boolean isStaticSharedLib;
17989        // Clean up resources deleted packages.
17990        InstallArgs args = null;
17991        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17992        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17993
17994        PackageRemovedInfo(PackageSender packageSender) {
17995            this.packageSender = packageSender;
17996        }
17997
17998        void sendPackageRemovedBroadcasts(boolean killApp) {
17999            sendPackageRemovedBroadcastInternal(killApp);
18000            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18001            for (int i = 0; i < childCount; i++) {
18002                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18003                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18004            }
18005        }
18006
18007        void sendSystemPackageUpdatedBroadcasts() {
18008            if (isRemovedPackageSystemUpdate) {
18009                sendSystemPackageUpdatedBroadcastsInternal();
18010                final int childCount = (removedChildPackages != null)
18011                        ? removedChildPackages.size() : 0;
18012                for (int i = 0; i < childCount; i++) {
18013                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18014                    if (childInfo.isRemovedPackageSystemUpdate) {
18015                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18016                    }
18017                }
18018            }
18019        }
18020
18021        void sendSystemPackageAppearedBroadcasts() {
18022            final int packageCount = (appearedChildPackages != null)
18023                    ? appearedChildPackages.size() : 0;
18024            for (int i = 0; i < packageCount; i++) {
18025                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18026                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18027                    true /*sendBootCompleted*/, false /*startReceiver*/,
18028                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18029            }
18030        }
18031
18032        private void sendSystemPackageUpdatedBroadcastsInternal() {
18033            Bundle extras = new Bundle(2);
18034            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18035            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18036            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18037                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18038            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18039                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18040            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18041                null, null, 0, removedPackage, null, null, null);
18042            if (installerPackageName != null) {
18043                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18044                        removedPackage, extras, 0 /*flags*/,
18045                        installerPackageName, null, null, null);
18046                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18047                        removedPackage, extras, 0 /*flags*/,
18048                        installerPackageName, null, null, null);
18049            }
18050        }
18051
18052        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18053            // Don't send static shared library removal broadcasts as these
18054            // libs are visible only the the apps that depend on them an one
18055            // cannot remove the library if it has a dependency.
18056            if (isStaticSharedLib) {
18057                return;
18058            }
18059            Bundle extras = new Bundle(2);
18060            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18061            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18062            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18063            if (isUpdate || isRemovedPackageSystemUpdate) {
18064                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18065            }
18066            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18067            if (removedPackage != null) {
18068                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18069                    removedPackage, extras, 0, null /*targetPackage*/, null,
18070                    broadcastUsers, instantUserIds);
18071                if (installerPackageName != null) {
18072                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18073                            removedPackage, extras, 0 /*flags*/,
18074                            installerPackageName, null, broadcastUsers, instantUserIds);
18075                }
18076                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18077                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18078                        removedPackage, extras,
18079                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18080                        null, null, broadcastUsers, instantUserIds);
18081                    packageSender.notifyPackageRemoved(removedPackage);
18082                }
18083            }
18084            if (removedAppId >= 0) {
18085                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18086                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18087                    null, null, broadcastUsers, instantUserIds);
18088            }
18089        }
18090
18091        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18092            removedUsers = userIds;
18093            if (removedUsers == null) {
18094                broadcastUsers = null;
18095                return;
18096            }
18097
18098            broadcastUsers = EMPTY_INT_ARRAY;
18099            instantUserIds = EMPTY_INT_ARRAY;
18100            for (int i = userIds.length - 1; i >= 0; --i) {
18101                final int userId = userIds[i];
18102                if (deletedPackageSetting.getInstantApp(userId)) {
18103                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18104                } else {
18105                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18106                }
18107            }
18108        }
18109    }
18110
18111    /*
18112     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18113     * flag is not set, the data directory is removed as well.
18114     * make sure this flag is set for partially installed apps. If not its meaningless to
18115     * delete a partially installed application.
18116     */
18117    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18118            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18119        String packageName = ps.name;
18120        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18121        // Retrieve object to delete permissions for shared user later on
18122        final PackageParser.Package deletedPkg;
18123        final PackageSetting deletedPs;
18124        // reader
18125        synchronized (mPackages) {
18126            deletedPkg = mPackages.get(packageName);
18127            deletedPs = mSettings.mPackages.get(packageName);
18128            if (outInfo != null) {
18129                outInfo.removedPackage = packageName;
18130                outInfo.installerPackageName = ps.installerPackageName;
18131                outInfo.isStaticSharedLib = deletedPkg != null
18132                        && deletedPkg.staticSharedLibName != null;
18133                outInfo.populateUsers(deletedPs == null ? null
18134                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18135            }
18136        }
18137
18138        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18139
18140        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18141            final PackageParser.Package resolvedPkg;
18142            if (deletedPkg != null) {
18143                resolvedPkg = deletedPkg;
18144            } else {
18145                // We don't have a parsed package when it lives on an ejected
18146                // adopted storage device, so fake something together
18147                resolvedPkg = new PackageParser.Package(ps.name);
18148                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18149            }
18150            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18151                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18152            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18153            if (outInfo != null) {
18154                outInfo.dataRemoved = true;
18155            }
18156            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18157        }
18158
18159        int removedAppId = -1;
18160
18161        // writer
18162        synchronized (mPackages) {
18163            boolean installedStateChanged = false;
18164            if (deletedPs != null) {
18165                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18166                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18167                    clearDefaultBrowserIfNeeded(packageName);
18168                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18169                    removedAppId = mSettings.removePackageLPw(packageName);
18170                    if (outInfo != null) {
18171                        outInfo.removedAppId = removedAppId;
18172                    }
18173                    mPermissionManager.updatePermissions(
18174                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18175                    if (deletedPs.sharedUser != null) {
18176                        // Remove permissions associated with package. Since runtime
18177                        // permissions are per user we have to kill the removed package
18178                        // or packages running under the shared user of the removed
18179                        // package if revoking the permissions requested only by the removed
18180                        // package is successful and this causes a change in gids.
18181                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18182                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18183                                    userId);
18184                            if (userIdToKill == UserHandle.USER_ALL
18185                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18186                                // If gids changed for this user, kill all affected packages.
18187                                mHandler.post(new Runnable() {
18188                                    @Override
18189                                    public void run() {
18190                                        // This has to happen with no lock held.
18191                                        killApplication(deletedPs.name, deletedPs.appId,
18192                                                KILL_APP_REASON_GIDS_CHANGED);
18193                                    }
18194                                });
18195                                break;
18196                            }
18197                        }
18198                    }
18199                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18200                }
18201                // make sure to preserve per-user disabled state if this removal was just
18202                // a downgrade of a system app to the factory package
18203                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18204                    if (DEBUG_REMOVE) {
18205                        Slog.d(TAG, "Propagating install state across downgrade");
18206                    }
18207                    for (int userId : allUserHandles) {
18208                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18209                        if (DEBUG_REMOVE) {
18210                            Slog.d(TAG, "    user " + userId + " => " + installed);
18211                        }
18212                        if (installed != ps.getInstalled(userId)) {
18213                            installedStateChanged = true;
18214                        }
18215                        ps.setInstalled(installed, userId);
18216                    }
18217                }
18218            }
18219            // can downgrade to reader
18220            if (writeSettings) {
18221                // Save settings now
18222                mSettings.writeLPr();
18223            }
18224            if (installedStateChanged) {
18225                mSettings.writeKernelMappingLPr(ps);
18226            }
18227        }
18228        if (removedAppId != -1) {
18229            // A user ID was deleted here. Go through all users and remove it
18230            // from KeyStore.
18231            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18232        }
18233    }
18234
18235    static boolean locationIsPrivileged(String path) {
18236        try {
18237            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18238            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18239            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18240            return path.startsWith(privilegedAppDir.getCanonicalPath())
18241                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18242                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18243        } catch (IOException e) {
18244            Slog.e(TAG, "Unable to access code path " + path);
18245        }
18246        return false;
18247    }
18248
18249    static boolean locationIsOem(String path) {
18250        try {
18251            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18252        } catch (IOException e) {
18253            Slog.e(TAG, "Unable to access code path " + path);
18254        }
18255        return false;
18256    }
18257
18258    static boolean locationIsVendor(String path) {
18259        try {
18260            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18261        } catch (IOException e) {
18262            Slog.e(TAG, "Unable to access code path " + path);
18263        }
18264        return false;
18265    }
18266
18267    static boolean locationIsProduct(String path) {
18268        try {
18269            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18270        } catch (IOException e) {
18271            Slog.e(TAG, "Unable to access code path " + path);
18272        }
18273        return false;
18274    }
18275
18276    /*
18277     * Tries to delete system package.
18278     */
18279    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18280            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18281            boolean writeSettings) {
18282        if (deletedPs.parentPackageName != null) {
18283            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18284            return false;
18285        }
18286
18287        final boolean applyUserRestrictions
18288                = (allUserHandles != null) && (outInfo.origUsers != null);
18289        final PackageSetting disabledPs;
18290        // Confirm if the system package has been updated
18291        // An updated system app can be deleted. This will also have to restore
18292        // the system pkg from system partition
18293        // reader
18294        synchronized (mPackages) {
18295            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18296        }
18297
18298        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18299                + " disabledPs=" + disabledPs);
18300
18301        if (disabledPs == null) {
18302            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18303            return false;
18304        } else if (DEBUG_REMOVE) {
18305            Slog.d(TAG, "Deleting system pkg from data partition");
18306        }
18307
18308        if (DEBUG_REMOVE) {
18309            if (applyUserRestrictions) {
18310                Slog.d(TAG, "Remembering install states:");
18311                for (int userId : allUserHandles) {
18312                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18313                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18314                }
18315            }
18316        }
18317
18318        // Delete the updated package
18319        outInfo.isRemovedPackageSystemUpdate = true;
18320        if (outInfo.removedChildPackages != null) {
18321            final int childCount = (deletedPs.childPackageNames != null)
18322                    ? deletedPs.childPackageNames.size() : 0;
18323            for (int i = 0; i < childCount; i++) {
18324                String childPackageName = deletedPs.childPackageNames.get(i);
18325                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18326                        .contains(childPackageName)) {
18327                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18328                            childPackageName);
18329                    if (childInfo != null) {
18330                        childInfo.isRemovedPackageSystemUpdate = true;
18331                    }
18332                }
18333            }
18334        }
18335
18336        if (disabledPs.versionCode < deletedPs.versionCode) {
18337            // Delete data for downgrades
18338            flags &= ~PackageManager.DELETE_KEEP_DATA;
18339        } else {
18340            // Preserve data by setting flag
18341            flags |= PackageManager.DELETE_KEEP_DATA;
18342        }
18343
18344        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18345                outInfo, writeSettings, disabledPs.pkg);
18346        if (!ret) {
18347            return false;
18348        }
18349
18350        // writer
18351        synchronized (mPackages) {
18352            // NOTE: The system package always needs to be enabled; even if it's for
18353            // a compressed stub. If we don't, installing the system package fails
18354            // during scan [scanning checks the disabled packages]. We will reverse
18355            // this later, after we've "installed" the stub.
18356            // Reinstate the old system package
18357            enableSystemPackageLPw(disabledPs.pkg);
18358            // Remove any native libraries from the upgraded package.
18359            removeNativeBinariesLI(deletedPs);
18360        }
18361
18362        // Install the system package
18363        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18364        try {
18365            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18366                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18367        } catch (PackageManagerException e) {
18368            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18369                    + e.getMessage());
18370            return false;
18371        } finally {
18372            if (disabledPs.pkg.isStub) {
18373                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18374            }
18375        }
18376        return true;
18377    }
18378
18379    /**
18380     * Installs a package that's already on the system partition.
18381     */
18382    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18383            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18384            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18385                    throws PackageManagerException {
18386        @ParseFlags int parseFlags =
18387                mDefParseFlags
18388                | PackageParser.PARSE_MUST_BE_APK
18389                | PackageParser.PARSE_IS_SYSTEM_DIR;
18390        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18391        if (isPrivileged || locationIsPrivileged(codePathString)) {
18392            scanFlags |= SCAN_AS_PRIVILEGED;
18393        }
18394        if (locationIsOem(codePathString)) {
18395            scanFlags |= SCAN_AS_OEM;
18396        }
18397        if (locationIsVendor(codePathString)) {
18398            scanFlags |= SCAN_AS_VENDOR;
18399        }
18400        if (locationIsProduct(codePathString)) {
18401            scanFlags |= SCAN_AS_PRODUCT;
18402        }
18403
18404        final File codePath = new File(codePathString);
18405        final PackageParser.Package pkg =
18406                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18407
18408        try {
18409            // update shared libraries for the newly re-installed system package
18410            updateSharedLibrariesLPr(pkg, null);
18411        } catch (PackageManagerException e) {
18412            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18413        }
18414
18415        prepareAppDataAfterInstallLIF(pkg);
18416
18417        // writer
18418        synchronized (mPackages) {
18419            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18420
18421            // Propagate the permissions state as we do not want to drop on the floor
18422            // runtime permissions. The update permissions method below will take
18423            // care of removing obsolete permissions and grant install permissions.
18424            if (origPermissionState != null) {
18425                ps.getPermissionsState().copyFrom(origPermissionState);
18426            }
18427            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18428                    mPermissionCallback);
18429
18430            final boolean applyUserRestrictions
18431                    = (allUserHandles != null) && (origUserHandles != null);
18432            if (applyUserRestrictions) {
18433                boolean installedStateChanged = false;
18434                if (DEBUG_REMOVE) {
18435                    Slog.d(TAG, "Propagating install state across reinstall");
18436                }
18437                for (int userId : allUserHandles) {
18438                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18439                    if (DEBUG_REMOVE) {
18440                        Slog.d(TAG, "    user " + userId + " => " + installed);
18441                    }
18442                    if (installed != ps.getInstalled(userId)) {
18443                        installedStateChanged = true;
18444                    }
18445                    ps.setInstalled(installed, userId);
18446
18447                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18448                }
18449                // Regardless of writeSettings we need to ensure that this restriction
18450                // state propagation is persisted
18451                mSettings.writeAllUsersPackageRestrictionsLPr();
18452                if (installedStateChanged) {
18453                    mSettings.writeKernelMappingLPr(ps);
18454                }
18455            }
18456            // can downgrade to reader here
18457            if (writeSettings) {
18458                mSettings.writeLPr();
18459            }
18460        }
18461        return pkg;
18462    }
18463
18464    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18465            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18466            PackageRemovedInfo outInfo, boolean writeSettings,
18467            PackageParser.Package replacingPackage) {
18468        synchronized (mPackages) {
18469            if (outInfo != null) {
18470                outInfo.uid = ps.appId;
18471            }
18472
18473            if (outInfo != null && outInfo.removedChildPackages != null) {
18474                final int childCount = (ps.childPackageNames != null)
18475                        ? ps.childPackageNames.size() : 0;
18476                for (int i = 0; i < childCount; i++) {
18477                    String childPackageName = ps.childPackageNames.get(i);
18478                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18479                    if (childPs == null) {
18480                        return false;
18481                    }
18482                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18483                            childPackageName);
18484                    if (childInfo != null) {
18485                        childInfo.uid = childPs.appId;
18486                    }
18487                }
18488            }
18489        }
18490
18491        // Delete package data from internal structures and also remove data if flag is set
18492        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18493
18494        // Delete the child packages data
18495        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18496        for (int i = 0; i < childCount; i++) {
18497            PackageSetting childPs;
18498            synchronized (mPackages) {
18499                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18500            }
18501            if (childPs != null) {
18502                PackageRemovedInfo childOutInfo = (outInfo != null
18503                        && outInfo.removedChildPackages != null)
18504                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18505                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18506                        && (replacingPackage != null
18507                        && !replacingPackage.hasChildPackage(childPs.name))
18508                        ? flags & ~DELETE_KEEP_DATA : flags;
18509                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18510                        deleteFlags, writeSettings);
18511            }
18512        }
18513
18514        // Delete application code and resources only for parent packages
18515        if (ps.parentPackageName == null) {
18516            if (deleteCodeAndResources && (outInfo != null)) {
18517                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18518                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18519                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18520            }
18521        }
18522
18523        return true;
18524    }
18525
18526    @Override
18527    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18528            int userId) {
18529        mContext.enforceCallingOrSelfPermission(
18530                android.Manifest.permission.DELETE_PACKAGES, null);
18531        synchronized (mPackages) {
18532            // Cannot block uninstall of static shared libs as they are
18533            // considered a part of the using app (emulating static linking).
18534            // Also static libs are installed always on internal storage.
18535            PackageParser.Package pkg = mPackages.get(packageName);
18536            if (pkg != null && pkg.staticSharedLibName != null) {
18537                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18538                        + " providing static shared library: " + pkg.staticSharedLibName);
18539                return false;
18540            }
18541            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18542            mSettings.writePackageRestrictionsLPr(userId);
18543        }
18544        return true;
18545    }
18546
18547    @Override
18548    public boolean getBlockUninstallForUser(String packageName, int userId) {
18549        synchronized (mPackages) {
18550            final PackageSetting ps = mSettings.mPackages.get(packageName);
18551            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18552                return false;
18553            }
18554            return mSettings.getBlockUninstallLPr(userId, packageName);
18555        }
18556    }
18557
18558    @Override
18559    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18560        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18561        synchronized (mPackages) {
18562            PackageSetting ps = mSettings.mPackages.get(packageName);
18563            if (ps == null) {
18564                Log.w(TAG, "Package doesn't exist: " + packageName);
18565                return false;
18566            }
18567            if (systemUserApp) {
18568                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18569            } else {
18570                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18571            }
18572            mSettings.writeLPr();
18573        }
18574        return true;
18575    }
18576
18577    /*
18578     * This method handles package deletion in general
18579     */
18580    private boolean deletePackageLIF(String packageName, UserHandle user,
18581            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18582            PackageRemovedInfo outInfo, boolean writeSettings,
18583            PackageParser.Package replacingPackage) {
18584        if (packageName == null) {
18585            Slog.w(TAG, "Attempt to delete null packageName.");
18586            return false;
18587        }
18588
18589        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18590
18591        PackageSetting ps;
18592        synchronized (mPackages) {
18593            ps = mSettings.mPackages.get(packageName);
18594            if (ps == null) {
18595                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18596                return false;
18597            }
18598
18599            if (ps.parentPackageName != null && (!isSystemApp(ps)
18600                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18601                if (DEBUG_REMOVE) {
18602                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18603                            + ((user == null) ? UserHandle.USER_ALL : user));
18604                }
18605                final int removedUserId = (user != null) ? user.getIdentifier()
18606                        : UserHandle.USER_ALL;
18607                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18608                    return false;
18609                }
18610                markPackageUninstalledForUserLPw(ps, user);
18611                scheduleWritePackageRestrictionsLocked(user);
18612                return true;
18613            }
18614        }
18615
18616        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18617                && user.getIdentifier() != UserHandle.USER_ALL)) {
18618            // The caller is asking that the package only be deleted for a single
18619            // user.  To do this, we just mark its uninstalled state and delete
18620            // its data. If this is a system app, we only allow this to happen if
18621            // they have set the special DELETE_SYSTEM_APP which requests different
18622            // semantics than normal for uninstalling system apps.
18623            markPackageUninstalledForUserLPw(ps, user);
18624
18625            if (!isSystemApp(ps)) {
18626                // Do not uninstall the APK if an app should be cached
18627                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18628                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18629                    // Other user still have this package installed, so all
18630                    // we need to do is clear this user's data and save that
18631                    // it is uninstalled.
18632                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18633                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18634                        return false;
18635                    }
18636                    scheduleWritePackageRestrictionsLocked(user);
18637                    return true;
18638                } else {
18639                    // We need to set it back to 'installed' so the uninstall
18640                    // broadcasts will be sent correctly.
18641                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18642                    ps.setInstalled(true, user.getIdentifier());
18643                    mSettings.writeKernelMappingLPr(ps);
18644                }
18645            } else {
18646                // This is a system app, so we assume that the
18647                // other users still have this package installed, so all
18648                // we need to do is clear this user's data and save that
18649                // it is uninstalled.
18650                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18651                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18652                    return false;
18653                }
18654                scheduleWritePackageRestrictionsLocked(user);
18655                return true;
18656            }
18657        }
18658
18659        // If we are deleting a composite package for all users, keep track
18660        // of result for each child.
18661        if (ps.childPackageNames != null && outInfo != null) {
18662            synchronized (mPackages) {
18663                final int childCount = ps.childPackageNames.size();
18664                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18665                for (int i = 0; i < childCount; i++) {
18666                    String childPackageName = ps.childPackageNames.get(i);
18667                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18668                    childInfo.removedPackage = childPackageName;
18669                    childInfo.installerPackageName = ps.installerPackageName;
18670                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18671                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18672                    if (childPs != null) {
18673                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18674                    }
18675                }
18676            }
18677        }
18678
18679        boolean ret = false;
18680        if (isSystemApp(ps)) {
18681            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18682            // When an updated system application is deleted we delete the existing resources
18683            // as well and fall back to existing code in system partition
18684            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18685        } else {
18686            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18687            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18688                    outInfo, writeSettings, replacingPackage);
18689        }
18690
18691        // Take a note whether we deleted the package for all users
18692        if (outInfo != null) {
18693            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18694            if (outInfo.removedChildPackages != null) {
18695                synchronized (mPackages) {
18696                    final int childCount = outInfo.removedChildPackages.size();
18697                    for (int i = 0; i < childCount; i++) {
18698                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18699                        if (childInfo != null) {
18700                            childInfo.removedForAllUsers = mPackages.get(
18701                                    childInfo.removedPackage) == null;
18702                        }
18703                    }
18704                }
18705            }
18706            // If we uninstalled an update to a system app there may be some
18707            // child packages that appeared as they are declared in the system
18708            // app but were not declared in the update.
18709            if (isSystemApp(ps)) {
18710                synchronized (mPackages) {
18711                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18712                    final int childCount = (updatedPs.childPackageNames != null)
18713                            ? updatedPs.childPackageNames.size() : 0;
18714                    for (int i = 0; i < childCount; i++) {
18715                        String childPackageName = updatedPs.childPackageNames.get(i);
18716                        if (outInfo.removedChildPackages == null
18717                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18718                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18719                            if (childPs == null) {
18720                                continue;
18721                            }
18722                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18723                            installRes.name = childPackageName;
18724                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18725                            installRes.pkg = mPackages.get(childPackageName);
18726                            installRes.uid = childPs.pkg.applicationInfo.uid;
18727                            if (outInfo.appearedChildPackages == null) {
18728                                outInfo.appearedChildPackages = new ArrayMap<>();
18729                            }
18730                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18731                        }
18732                    }
18733                }
18734            }
18735        }
18736
18737        return ret;
18738    }
18739
18740    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18741        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18742                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18743        for (int nextUserId : userIds) {
18744            if (DEBUG_REMOVE) {
18745                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18746            }
18747            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18748                    false /*installed*/,
18749                    true /*stopped*/,
18750                    true /*notLaunched*/,
18751                    false /*hidden*/,
18752                    false /*suspended*/,
18753                    false /*instantApp*/,
18754                    false /*virtualPreload*/,
18755                    null /*lastDisableAppCaller*/,
18756                    null /*enabledComponents*/,
18757                    null /*disabledComponents*/,
18758                    ps.readUserState(nextUserId).domainVerificationStatus,
18759                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18760                    null /*harmfulAppWarning*/);
18761        }
18762        mSettings.writeKernelMappingLPr(ps);
18763    }
18764
18765    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18766            PackageRemovedInfo outInfo) {
18767        final PackageParser.Package pkg;
18768        synchronized (mPackages) {
18769            pkg = mPackages.get(ps.name);
18770        }
18771
18772        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18773                : new int[] {userId};
18774        for (int nextUserId : userIds) {
18775            if (DEBUG_REMOVE) {
18776                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18777                        + nextUserId);
18778            }
18779
18780            destroyAppDataLIF(pkg, userId,
18781                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18782            destroyAppProfilesLIF(pkg, userId);
18783            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18784            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18785            schedulePackageCleaning(ps.name, nextUserId, false);
18786            synchronized (mPackages) {
18787                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18788                    scheduleWritePackageRestrictionsLocked(nextUserId);
18789                }
18790                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18791            }
18792        }
18793
18794        if (outInfo != null) {
18795            outInfo.removedPackage = ps.name;
18796            outInfo.installerPackageName = ps.installerPackageName;
18797            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18798            outInfo.removedAppId = ps.appId;
18799            outInfo.removedUsers = userIds;
18800            outInfo.broadcastUsers = userIds;
18801        }
18802
18803        return true;
18804    }
18805
18806    private final class ClearStorageConnection implements ServiceConnection {
18807        IMediaContainerService mContainerService;
18808
18809        @Override
18810        public void onServiceConnected(ComponentName name, IBinder service) {
18811            synchronized (this) {
18812                mContainerService = IMediaContainerService.Stub
18813                        .asInterface(Binder.allowBlocking(service));
18814                notifyAll();
18815            }
18816        }
18817
18818        @Override
18819        public void onServiceDisconnected(ComponentName name) {
18820        }
18821    }
18822
18823    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18824        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18825
18826        final boolean mounted;
18827        if (Environment.isExternalStorageEmulated()) {
18828            mounted = true;
18829        } else {
18830            final String status = Environment.getExternalStorageState();
18831
18832            mounted = status.equals(Environment.MEDIA_MOUNTED)
18833                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18834        }
18835
18836        if (!mounted) {
18837            return;
18838        }
18839
18840        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18841        int[] users;
18842        if (userId == UserHandle.USER_ALL) {
18843            users = sUserManager.getUserIds();
18844        } else {
18845            users = new int[] { userId };
18846        }
18847        final ClearStorageConnection conn = new ClearStorageConnection();
18848        if (mContext.bindServiceAsUser(
18849                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18850            try {
18851                for (int curUser : users) {
18852                    long timeout = SystemClock.uptimeMillis() + 5000;
18853                    synchronized (conn) {
18854                        long now;
18855                        while (conn.mContainerService == null &&
18856                                (now = SystemClock.uptimeMillis()) < timeout) {
18857                            try {
18858                                conn.wait(timeout - now);
18859                            } catch (InterruptedException e) {
18860                            }
18861                        }
18862                    }
18863                    if (conn.mContainerService == null) {
18864                        return;
18865                    }
18866
18867                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18868                    clearDirectory(conn.mContainerService,
18869                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18870                    if (allData) {
18871                        clearDirectory(conn.mContainerService,
18872                                userEnv.buildExternalStorageAppDataDirs(packageName));
18873                        clearDirectory(conn.mContainerService,
18874                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18875                    }
18876                }
18877            } finally {
18878                mContext.unbindService(conn);
18879            }
18880        }
18881    }
18882
18883    @Override
18884    public void clearApplicationProfileData(String packageName) {
18885        enforceSystemOrRoot("Only the system can clear all profile data");
18886
18887        final PackageParser.Package pkg;
18888        synchronized (mPackages) {
18889            pkg = mPackages.get(packageName);
18890        }
18891
18892        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18893            synchronized (mInstallLock) {
18894                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18895            }
18896        }
18897    }
18898
18899    @Override
18900    public void clearApplicationUserData(final String packageName,
18901            final IPackageDataObserver observer, final int userId) {
18902        mContext.enforceCallingOrSelfPermission(
18903                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18904
18905        final int callingUid = Binder.getCallingUid();
18906        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18907                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18908
18909        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18910        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18911        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18912            throw new SecurityException("Cannot clear data for a protected package: "
18913                    + packageName);
18914        }
18915        // Queue up an async operation since the package deletion may take a little while.
18916        mHandler.post(new Runnable() {
18917            public void run() {
18918                mHandler.removeCallbacks(this);
18919                final boolean succeeded;
18920                if (!filterApp) {
18921                    try (PackageFreezer freezer = freezePackage(packageName,
18922                            "clearApplicationUserData")) {
18923                        synchronized (mInstallLock) {
18924                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18925                        }
18926                        clearExternalStorageDataSync(packageName, userId, true);
18927                        synchronized (mPackages) {
18928                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18929                                    packageName, userId);
18930                        }
18931                    }
18932                    if (succeeded) {
18933                        // invoke DeviceStorageMonitor's update method to clear any notifications
18934                        DeviceStorageMonitorInternal dsm = LocalServices
18935                                .getService(DeviceStorageMonitorInternal.class);
18936                        if (dsm != null) {
18937                            dsm.checkMemory();
18938                        }
18939                    }
18940                } else {
18941                    succeeded = false;
18942                }
18943                if (observer != null) {
18944                    try {
18945                        observer.onRemoveCompleted(packageName, succeeded);
18946                    } catch (RemoteException e) {
18947                        Log.i(TAG, "Observer no longer exists.");
18948                    }
18949                } //end if observer
18950            } //end run
18951        });
18952    }
18953
18954    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18955        if (packageName == null) {
18956            Slog.w(TAG, "Attempt to delete null packageName.");
18957            return false;
18958        }
18959
18960        // Try finding details about the requested package
18961        PackageParser.Package pkg;
18962        synchronized (mPackages) {
18963            pkg = mPackages.get(packageName);
18964            if (pkg == null) {
18965                final PackageSetting ps = mSettings.mPackages.get(packageName);
18966                if (ps != null) {
18967                    pkg = ps.pkg;
18968                }
18969            }
18970
18971            if (pkg == null) {
18972                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18973                return false;
18974            }
18975
18976            PackageSetting ps = (PackageSetting) pkg.mExtras;
18977            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18978        }
18979
18980        clearAppDataLIF(pkg, userId,
18981                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18982
18983        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18984        removeKeystoreDataIfNeeded(userId, appId);
18985
18986        UserManagerInternal umInternal = getUserManagerInternal();
18987        final int flags;
18988        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18989            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18990        } else if (umInternal.isUserRunning(userId)) {
18991            flags = StorageManager.FLAG_STORAGE_DE;
18992        } else {
18993            flags = 0;
18994        }
18995        prepareAppDataContentsLIF(pkg, userId, flags);
18996
18997        return true;
18998    }
18999
19000    /**
19001     * Reverts user permission state changes (permissions and flags) in
19002     * all packages for a given user.
19003     *
19004     * @param userId The device user for which to do a reset.
19005     */
19006    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19007        final int packageCount = mPackages.size();
19008        for (int i = 0; i < packageCount; i++) {
19009            PackageParser.Package pkg = mPackages.valueAt(i);
19010            PackageSetting ps = (PackageSetting) pkg.mExtras;
19011            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19012        }
19013    }
19014
19015    private void resetNetworkPolicies(int userId) {
19016        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19017    }
19018
19019    /**
19020     * Reverts user permission state changes (permissions and flags).
19021     *
19022     * @param ps The package for which to reset.
19023     * @param userId The device user for which to do a reset.
19024     */
19025    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19026            final PackageSetting ps, final int userId) {
19027        if (ps.pkg == null) {
19028            return;
19029        }
19030
19031        // These are flags that can change base on user actions.
19032        final int userSettableMask = FLAG_PERMISSION_USER_SET
19033                | FLAG_PERMISSION_USER_FIXED
19034                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19035                | FLAG_PERMISSION_REVIEW_REQUIRED;
19036
19037        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19038                | FLAG_PERMISSION_POLICY_FIXED;
19039
19040        boolean writeInstallPermissions = false;
19041        boolean writeRuntimePermissions = false;
19042
19043        final int permissionCount = ps.pkg.requestedPermissions.size();
19044        for (int i = 0; i < permissionCount; i++) {
19045            final String permName = ps.pkg.requestedPermissions.get(i);
19046            final BasePermission bp =
19047                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19048            if (bp == null) {
19049                continue;
19050            }
19051
19052            // If shared user we just reset the state to which only this app contributed.
19053            if (ps.sharedUser != null) {
19054                boolean used = false;
19055                final int packageCount = ps.sharedUser.packages.size();
19056                for (int j = 0; j < packageCount; j++) {
19057                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19058                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19059                            && pkg.pkg.requestedPermissions.contains(permName)) {
19060                        used = true;
19061                        break;
19062                    }
19063                }
19064                if (used) {
19065                    continue;
19066                }
19067            }
19068
19069            final PermissionsState permissionsState = ps.getPermissionsState();
19070
19071            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19072
19073            // Always clear the user settable flags.
19074            final boolean hasInstallState =
19075                    permissionsState.getInstallPermissionState(permName) != null;
19076            // If permission review is enabled and this is a legacy app, mark the
19077            // permission as requiring a review as this is the initial state.
19078            int flags = 0;
19079            if (mSettings.mPermissions.mPermissionReviewRequired
19080                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19081                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19082            }
19083            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19084                if (hasInstallState) {
19085                    writeInstallPermissions = true;
19086                } else {
19087                    writeRuntimePermissions = true;
19088                }
19089            }
19090
19091            // Below is only runtime permission handling.
19092            if (!bp.isRuntime()) {
19093                continue;
19094            }
19095
19096            // Never clobber system or policy.
19097            if ((oldFlags & policyOrSystemFlags) != 0) {
19098                continue;
19099            }
19100
19101            // If this permission was granted by default, make sure it is.
19102            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19103                if (permissionsState.grantRuntimePermission(bp, userId)
19104                        != PERMISSION_OPERATION_FAILURE) {
19105                    writeRuntimePermissions = true;
19106                }
19107            // If permission review is enabled the permissions for a legacy apps
19108            // are represented as constantly granted runtime ones, so don't revoke.
19109            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19110                // Otherwise, reset the permission.
19111                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19112                switch (revokeResult) {
19113                    case PERMISSION_OPERATION_SUCCESS:
19114                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19115                        writeRuntimePermissions = true;
19116                        final int appId = ps.appId;
19117                        mHandler.post(new Runnable() {
19118                            @Override
19119                            public void run() {
19120                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19121                            }
19122                        });
19123                    } break;
19124                }
19125            }
19126        }
19127
19128        // Synchronously write as we are taking permissions away.
19129        if (writeRuntimePermissions) {
19130            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19131        }
19132
19133        // Synchronously write as we are taking permissions away.
19134        if (writeInstallPermissions) {
19135            mSettings.writeLPr();
19136        }
19137    }
19138
19139    /**
19140     * Remove entries from the keystore daemon. Will only remove it if the
19141     * {@code appId} is valid.
19142     */
19143    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19144        if (appId < 0) {
19145            return;
19146        }
19147
19148        final KeyStore keyStore = KeyStore.getInstance();
19149        if (keyStore != null) {
19150            if (userId == UserHandle.USER_ALL) {
19151                for (final int individual : sUserManager.getUserIds()) {
19152                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19153                }
19154            } else {
19155                keyStore.clearUid(UserHandle.getUid(userId, appId));
19156            }
19157        } else {
19158            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19159        }
19160    }
19161
19162    @Override
19163    public void deleteApplicationCacheFiles(final String packageName,
19164            final IPackageDataObserver observer) {
19165        final int userId = UserHandle.getCallingUserId();
19166        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19167    }
19168
19169    @Override
19170    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19171            final IPackageDataObserver observer) {
19172        final int callingUid = Binder.getCallingUid();
19173        mContext.enforceCallingOrSelfPermission(
19174                android.Manifest.permission.DELETE_CACHE_FILES, null);
19175        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19176                /* requireFullPermission= */ true, /* checkShell= */ false,
19177                "delete application cache files");
19178        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19179                android.Manifest.permission.ACCESS_INSTANT_APPS);
19180
19181        final PackageParser.Package pkg;
19182        synchronized (mPackages) {
19183            pkg = mPackages.get(packageName);
19184        }
19185
19186        // Queue up an async operation since the package deletion may take a little while.
19187        mHandler.post(new Runnable() {
19188            public void run() {
19189                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19190                boolean doClearData = true;
19191                if (ps != null) {
19192                    final boolean targetIsInstantApp =
19193                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19194                    doClearData = !targetIsInstantApp
19195                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19196                }
19197                if (doClearData) {
19198                    synchronized (mInstallLock) {
19199                        final int flags = StorageManager.FLAG_STORAGE_DE
19200                                | StorageManager.FLAG_STORAGE_CE;
19201                        // We're only clearing cache files, so we don't care if the
19202                        // app is unfrozen and still able to run
19203                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19204                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19205                    }
19206                    clearExternalStorageDataSync(packageName, userId, false);
19207                }
19208                if (observer != null) {
19209                    try {
19210                        observer.onRemoveCompleted(packageName, true);
19211                    } catch (RemoteException e) {
19212                        Log.i(TAG, "Observer no longer exists.");
19213                    }
19214                }
19215            }
19216        });
19217    }
19218
19219    @Override
19220    public void getPackageSizeInfo(final String packageName, int userHandle,
19221            final IPackageStatsObserver observer) {
19222        throw new UnsupportedOperationException(
19223                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19224    }
19225
19226    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19227        final PackageSetting ps;
19228        synchronized (mPackages) {
19229            ps = mSettings.mPackages.get(packageName);
19230            if (ps == null) {
19231                Slog.w(TAG, "Failed to find settings for " + packageName);
19232                return false;
19233            }
19234        }
19235
19236        final String[] packageNames = { packageName };
19237        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19238        final String[] codePaths = { ps.codePathString };
19239
19240        try {
19241            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19242                    ps.appId, ceDataInodes, codePaths, stats);
19243
19244            // For now, ignore code size of packages on system partition
19245            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19246                stats.codeSize = 0;
19247            }
19248
19249            // External clients expect these to be tracked separately
19250            stats.dataSize -= stats.cacheSize;
19251
19252        } catch (InstallerException e) {
19253            Slog.w(TAG, String.valueOf(e));
19254            return false;
19255        }
19256
19257        return true;
19258    }
19259
19260    private int getUidTargetSdkVersionLockedLPr(int uid) {
19261        Object obj = mSettings.getUserIdLPr(uid);
19262        if (obj instanceof SharedUserSetting) {
19263            final SharedUserSetting sus = (SharedUserSetting) obj;
19264            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19265            final Iterator<PackageSetting> it = sus.packages.iterator();
19266            while (it.hasNext()) {
19267                final PackageSetting ps = it.next();
19268                if (ps.pkg != null) {
19269                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19270                    if (v < vers) vers = v;
19271                }
19272            }
19273            return vers;
19274        } else if (obj instanceof PackageSetting) {
19275            final PackageSetting ps = (PackageSetting) obj;
19276            if (ps.pkg != null) {
19277                return ps.pkg.applicationInfo.targetSdkVersion;
19278            }
19279        }
19280        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19281    }
19282
19283    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19284        final PackageParser.Package p = mPackages.get(packageName);
19285        if (p != null) {
19286            return p.applicationInfo.targetSdkVersion;
19287        }
19288        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19289    }
19290
19291    @Override
19292    public void addPreferredActivity(IntentFilter filter, int match,
19293            ComponentName[] set, ComponentName activity, int userId) {
19294        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19295                "Adding preferred");
19296    }
19297
19298    private void addPreferredActivityInternal(IntentFilter filter, int match,
19299            ComponentName[] set, ComponentName activity, boolean always, int userId,
19300            String opname) {
19301        // writer
19302        int callingUid = Binder.getCallingUid();
19303        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19304                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19305        if (filter.countActions() == 0) {
19306            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19307            return;
19308        }
19309        synchronized (mPackages) {
19310            if (mContext.checkCallingOrSelfPermission(
19311                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19312                    != PackageManager.PERMISSION_GRANTED) {
19313                if (getUidTargetSdkVersionLockedLPr(callingUid)
19314                        < Build.VERSION_CODES.FROYO) {
19315                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19316                            + callingUid);
19317                    return;
19318                }
19319                mContext.enforceCallingOrSelfPermission(
19320                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19321            }
19322
19323            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19324            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19325                    + userId + ":");
19326            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19327            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19328            scheduleWritePackageRestrictionsLocked(userId);
19329            postPreferredActivityChangedBroadcast(userId);
19330        }
19331    }
19332
19333    private void postPreferredActivityChangedBroadcast(int userId) {
19334        mHandler.post(() -> {
19335            final IActivityManager am = ActivityManager.getService();
19336            if (am == null) {
19337                return;
19338            }
19339
19340            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19341            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19342            try {
19343                am.broadcastIntent(null, intent, null, null,
19344                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19345                        null, false, false, userId);
19346            } catch (RemoteException e) {
19347            }
19348        });
19349    }
19350
19351    @Override
19352    public void replacePreferredActivity(IntentFilter filter, int match,
19353            ComponentName[] set, ComponentName activity, int userId) {
19354        if (filter.countActions() != 1) {
19355            throw new IllegalArgumentException(
19356                    "replacePreferredActivity expects filter to have only 1 action.");
19357        }
19358        if (filter.countDataAuthorities() != 0
19359                || filter.countDataPaths() != 0
19360                || filter.countDataSchemes() > 1
19361                || filter.countDataTypes() != 0) {
19362            throw new IllegalArgumentException(
19363                    "replacePreferredActivity expects filter to have no data authorities, " +
19364                    "paths, or types; and at most one scheme.");
19365        }
19366
19367        final int callingUid = Binder.getCallingUid();
19368        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19369                true /* requireFullPermission */, false /* checkShell */,
19370                "replace preferred activity");
19371        synchronized (mPackages) {
19372            if (mContext.checkCallingOrSelfPermission(
19373                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19374                    != PackageManager.PERMISSION_GRANTED) {
19375                if (getUidTargetSdkVersionLockedLPr(callingUid)
19376                        < Build.VERSION_CODES.FROYO) {
19377                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19378                            + Binder.getCallingUid());
19379                    return;
19380                }
19381                mContext.enforceCallingOrSelfPermission(
19382                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19383            }
19384
19385            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19386            if (pir != null) {
19387                // Get all of the existing entries that exactly match this filter.
19388                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19389                if (existing != null && existing.size() == 1) {
19390                    PreferredActivity cur = existing.get(0);
19391                    if (DEBUG_PREFERRED) {
19392                        Slog.i(TAG, "Checking replace of preferred:");
19393                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19394                        if (!cur.mPref.mAlways) {
19395                            Slog.i(TAG, "  -- CUR; not mAlways!");
19396                        } else {
19397                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19398                            Slog.i(TAG, "  -- CUR: mSet="
19399                                    + Arrays.toString(cur.mPref.mSetComponents));
19400                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19401                            Slog.i(TAG, "  -- NEW: mMatch="
19402                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19403                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19404                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19405                        }
19406                    }
19407                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19408                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19409                            && cur.mPref.sameSet(set)) {
19410                        // Setting the preferred activity to what it happens to be already
19411                        if (DEBUG_PREFERRED) {
19412                            Slog.i(TAG, "Replacing with same preferred activity "
19413                                    + cur.mPref.mShortComponent + " for user "
19414                                    + userId + ":");
19415                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19416                        }
19417                        return;
19418                    }
19419                }
19420
19421                if (existing != null) {
19422                    if (DEBUG_PREFERRED) {
19423                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19424                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19425                    }
19426                    for (int i = 0; i < existing.size(); i++) {
19427                        PreferredActivity pa = existing.get(i);
19428                        if (DEBUG_PREFERRED) {
19429                            Slog.i(TAG, "Removing existing preferred activity "
19430                                    + pa.mPref.mComponent + ":");
19431                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19432                        }
19433                        pir.removeFilter(pa);
19434                    }
19435                }
19436            }
19437            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19438                    "Replacing preferred");
19439        }
19440    }
19441
19442    @Override
19443    public void clearPackagePreferredActivities(String packageName) {
19444        final int callingUid = Binder.getCallingUid();
19445        if (getInstantAppPackageName(callingUid) != null) {
19446            return;
19447        }
19448        // writer
19449        synchronized (mPackages) {
19450            PackageParser.Package pkg = mPackages.get(packageName);
19451            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19452                if (mContext.checkCallingOrSelfPermission(
19453                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19454                        != PackageManager.PERMISSION_GRANTED) {
19455                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19456                            < Build.VERSION_CODES.FROYO) {
19457                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19458                                + callingUid);
19459                        return;
19460                    }
19461                    mContext.enforceCallingOrSelfPermission(
19462                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19463                }
19464            }
19465            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19466            if (ps != null
19467                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19468                return;
19469            }
19470            int user = UserHandle.getCallingUserId();
19471            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19472                scheduleWritePackageRestrictionsLocked(user);
19473            }
19474        }
19475    }
19476
19477    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19478    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19479        ArrayList<PreferredActivity> removed = null;
19480        boolean changed = false;
19481        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19482            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19483            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19484            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19485                continue;
19486            }
19487            Iterator<PreferredActivity> it = pir.filterIterator();
19488            while (it.hasNext()) {
19489                PreferredActivity pa = it.next();
19490                // Mark entry for removal only if it matches the package name
19491                // and the entry is of type "always".
19492                if (packageName == null ||
19493                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19494                                && pa.mPref.mAlways)) {
19495                    if (removed == null) {
19496                        removed = new ArrayList<PreferredActivity>();
19497                    }
19498                    removed.add(pa);
19499                }
19500            }
19501            if (removed != null) {
19502                for (int j=0; j<removed.size(); j++) {
19503                    PreferredActivity pa = removed.get(j);
19504                    pir.removeFilter(pa);
19505                }
19506                changed = true;
19507            }
19508        }
19509        if (changed) {
19510            postPreferredActivityChangedBroadcast(userId);
19511        }
19512        return changed;
19513    }
19514
19515    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19516    private void clearIntentFilterVerificationsLPw(int userId) {
19517        final int packageCount = mPackages.size();
19518        for (int i = 0; i < packageCount; i++) {
19519            PackageParser.Package pkg = mPackages.valueAt(i);
19520            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19521        }
19522    }
19523
19524    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19525    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19526        if (userId == UserHandle.USER_ALL) {
19527            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19528                    sUserManager.getUserIds())) {
19529                for (int oneUserId : sUserManager.getUserIds()) {
19530                    scheduleWritePackageRestrictionsLocked(oneUserId);
19531                }
19532            }
19533        } else {
19534            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19535                scheduleWritePackageRestrictionsLocked(userId);
19536            }
19537        }
19538    }
19539
19540    /** Clears state for all users, and touches intent filter verification policy */
19541    void clearDefaultBrowserIfNeeded(String packageName) {
19542        for (int oneUserId : sUserManager.getUserIds()) {
19543            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19544        }
19545    }
19546
19547    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19548        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19549        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19550            if (packageName.equals(defaultBrowserPackageName)) {
19551                setDefaultBrowserPackageName(null, userId);
19552            }
19553        }
19554    }
19555
19556    @Override
19557    public void resetApplicationPreferences(int userId) {
19558        mContext.enforceCallingOrSelfPermission(
19559                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19560        final long identity = Binder.clearCallingIdentity();
19561        // writer
19562        try {
19563            synchronized (mPackages) {
19564                clearPackagePreferredActivitiesLPw(null, userId);
19565                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19566                // TODO: We have to reset the default SMS and Phone. This requires
19567                // significant refactoring to keep all default apps in the package
19568                // manager (cleaner but more work) or have the services provide
19569                // callbacks to the package manager to request a default app reset.
19570                applyFactoryDefaultBrowserLPw(userId);
19571                clearIntentFilterVerificationsLPw(userId);
19572                primeDomainVerificationsLPw(userId);
19573                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19574                scheduleWritePackageRestrictionsLocked(userId);
19575            }
19576            resetNetworkPolicies(userId);
19577        } finally {
19578            Binder.restoreCallingIdentity(identity);
19579        }
19580    }
19581
19582    @Override
19583    public int getPreferredActivities(List<IntentFilter> outFilters,
19584            List<ComponentName> outActivities, String packageName) {
19585        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19586            return 0;
19587        }
19588        int num = 0;
19589        final int userId = UserHandle.getCallingUserId();
19590        // reader
19591        synchronized (mPackages) {
19592            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19593            if (pir != null) {
19594                final Iterator<PreferredActivity> it = pir.filterIterator();
19595                while (it.hasNext()) {
19596                    final PreferredActivity pa = it.next();
19597                    if (packageName == null
19598                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19599                                    && pa.mPref.mAlways)) {
19600                        if (outFilters != null) {
19601                            outFilters.add(new IntentFilter(pa));
19602                        }
19603                        if (outActivities != null) {
19604                            outActivities.add(pa.mPref.mComponent);
19605                        }
19606                    }
19607                }
19608            }
19609        }
19610
19611        return num;
19612    }
19613
19614    @Override
19615    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19616            int userId) {
19617        int callingUid = Binder.getCallingUid();
19618        if (callingUid != Process.SYSTEM_UID) {
19619            throw new SecurityException(
19620                    "addPersistentPreferredActivity can only be run by the system");
19621        }
19622        if (filter.countActions() == 0) {
19623            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19624            return;
19625        }
19626        synchronized (mPackages) {
19627            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19628                    ":");
19629            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19630            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19631                    new PersistentPreferredActivity(filter, activity));
19632            scheduleWritePackageRestrictionsLocked(userId);
19633            postPreferredActivityChangedBroadcast(userId);
19634        }
19635    }
19636
19637    @Override
19638    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19639        int callingUid = Binder.getCallingUid();
19640        if (callingUid != Process.SYSTEM_UID) {
19641            throw new SecurityException(
19642                    "clearPackagePersistentPreferredActivities can only be run by the system");
19643        }
19644        ArrayList<PersistentPreferredActivity> removed = null;
19645        boolean changed = false;
19646        synchronized (mPackages) {
19647            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19648                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19649                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19650                        .valueAt(i);
19651                if (userId != thisUserId) {
19652                    continue;
19653                }
19654                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19655                while (it.hasNext()) {
19656                    PersistentPreferredActivity ppa = it.next();
19657                    // Mark entry for removal only if it matches the package name.
19658                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19659                        if (removed == null) {
19660                            removed = new ArrayList<PersistentPreferredActivity>();
19661                        }
19662                        removed.add(ppa);
19663                    }
19664                }
19665                if (removed != null) {
19666                    for (int j=0; j<removed.size(); j++) {
19667                        PersistentPreferredActivity ppa = removed.get(j);
19668                        ppir.removeFilter(ppa);
19669                    }
19670                    changed = true;
19671                }
19672            }
19673
19674            if (changed) {
19675                scheduleWritePackageRestrictionsLocked(userId);
19676                postPreferredActivityChangedBroadcast(userId);
19677            }
19678        }
19679    }
19680
19681    /**
19682     * Common machinery for picking apart a restored XML blob and passing
19683     * it to a caller-supplied functor to be applied to the running system.
19684     */
19685    private void restoreFromXml(XmlPullParser parser, int userId,
19686            String expectedStartTag, BlobXmlRestorer functor)
19687            throws IOException, XmlPullParserException {
19688        int type;
19689        while ((type = parser.next()) != XmlPullParser.START_TAG
19690                && type != XmlPullParser.END_DOCUMENT) {
19691        }
19692        if (type != XmlPullParser.START_TAG) {
19693            // oops didn't find a start tag?!
19694            if (DEBUG_BACKUP) {
19695                Slog.e(TAG, "Didn't find start tag during restore");
19696            }
19697            return;
19698        }
19699Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19700        // this is supposed to be TAG_PREFERRED_BACKUP
19701        if (!expectedStartTag.equals(parser.getName())) {
19702            if (DEBUG_BACKUP) {
19703                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19704            }
19705            return;
19706        }
19707
19708        // skip interfering stuff, then we're aligned with the backing implementation
19709        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19710Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19711        functor.apply(parser, userId);
19712    }
19713
19714    private interface BlobXmlRestorer {
19715        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19716    }
19717
19718    /**
19719     * Non-Binder method, support for the backup/restore mechanism: write the
19720     * full set of preferred activities in its canonical XML format.  Returns the
19721     * XML output as a byte array, or null if there is none.
19722     */
19723    @Override
19724    public byte[] getPreferredActivityBackup(int userId) {
19725        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19726            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19727        }
19728
19729        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19730        try {
19731            final XmlSerializer serializer = new FastXmlSerializer();
19732            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19733            serializer.startDocument(null, true);
19734            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19735
19736            synchronized (mPackages) {
19737                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19738            }
19739
19740            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19741            serializer.endDocument();
19742            serializer.flush();
19743        } catch (Exception e) {
19744            if (DEBUG_BACKUP) {
19745                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19746            }
19747            return null;
19748        }
19749
19750        return dataStream.toByteArray();
19751    }
19752
19753    @Override
19754    public void restorePreferredActivities(byte[] backup, int userId) {
19755        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19756            throw new SecurityException("Only the system may call restorePreferredActivities()");
19757        }
19758
19759        try {
19760            final XmlPullParser parser = Xml.newPullParser();
19761            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19762            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19763                    new BlobXmlRestorer() {
19764                        @Override
19765                        public void apply(XmlPullParser parser, int userId)
19766                                throws XmlPullParserException, IOException {
19767                            synchronized (mPackages) {
19768                                mSettings.readPreferredActivitiesLPw(parser, userId);
19769                            }
19770                        }
19771                    } );
19772        } catch (Exception e) {
19773            if (DEBUG_BACKUP) {
19774                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19775            }
19776        }
19777    }
19778
19779    /**
19780     * Non-Binder method, support for the backup/restore mechanism: write the
19781     * default browser (etc) settings in its canonical XML format.  Returns the default
19782     * browser XML representation as a byte array, or null if there is none.
19783     */
19784    @Override
19785    public byte[] getDefaultAppsBackup(int userId) {
19786        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19787            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19788        }
19789
19790        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19791        try {
19792            final XmlSerializer serializer = new FastXmlSerializer();
19793            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19794            serializer.startDocument(null, true);
19795            serializer.startTag(null, TAG_DEFAULT_APPS);
19796
19797            synchronized (mPackages) {
19798                mSettings.writeDefaultAppsLPr(serializer, userId);
19799            }
19800
19801            serializer.endTag(null, TAG_DEFAULT_APPS);
19802            serializer.endDocument();
19803            serializer.flush();
19804        } catch (Exception e) {
19805            if (DEBUG_BACKUP) {
19806                Slog.e(TAG, "Unable to write default apps for backup", e);
19807            }
19808            return null;
19809        }
19810
19811        return dataStream.toByteArray();
19812    }
19813
19814    @Override
19815    public void restoreDefaultApps(byte[] backup, int userId) {
19816        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19817            throw new SecurityException("Only the system may call restoreDefaultApps()");
19818        }
19819
19820        try {
19821            final XmlPullParser parser = Xml.newPullParser();
19822            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19823            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19824                    new BlobXmlRestorer() {
19825                        @Override
19826                        public void apply(XmlPullParser parser, int userId)
19827                                throws XmlPullParserException, IOException {
19828                            synchronized (mPackages) {
19829                                mSettings.readDefaultAppsLPw(parser, userId);
19830                            }
19831                        }
19832                    } );
19833        } catch (Exception e) {
19834            if (DEBUG_BACKUP) {
19835                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19836            }
19837        }
19838    }
19839
19840    @Override
19841    public byte[] getIntentFilterVerificationBackup(int userId) {
19842        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19843            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19844        }
19845
19846        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19847        try {
19848            final XmlSerializer serializer = new FastXmlSerializer();
19849            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19850            serializer.startDocument(null, true);
19851            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19852
19853            synchronized (mPackages) {
19854                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19855            }
19856
19857            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19858            serializer.endDocument();
19859            serializer.flush();
19860        } catch (Exception e) {
19861            if (DEBUG_BACKUP) {
19862                Slog.e(TAG, "Unable to write default apps for backup", e);
19863            }
19864            return null;
19865        }
19866
19867        return dataStream.toByteArray();
19868    }
19869
19870    @Override
19871    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19872        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19873            throw new SecurityException("Only the system may call restorePreferredActivities()");
19874        }
19875
19876        try {
19877            final XmlPullParser parser = Xml.newPullParser();
19878            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19879            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19880                    new BlobXmlRestorer() {
19881                        @Override
19882                        public void apply(XmlPullParser parser, int userId)
19883                                throws XmlPullParserException, IOException {
19884                            synchronized (mPackages) {
19885                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19886                                mSettings.writeLPr();
19887                            }
19888                        }
19889                    } );
19890        } catch (Exception e) {
19891            if (DEBUG_BACKUP) {
19892                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19893            }
19894        }
19895    }
19896
19897    @Override
19898    public byte[] getPermissionGrantBackup(int userId) {
19899        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19900            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19901        }
19902
19903        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19904        try {
19905            final XmlSerializer serializer = new FastXmlSerializer();
19906            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19907            serializer.startDocument(null, true);
19908            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19909
19910            synchronized (mPackages) {
19911                serializeRuntimePermissionGrantsLPr(serializer, userId);
19912            }
19913
19914            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19915            serializer.endDocument();
19916            serializer.flush();
19917        } catch (Exception e) {
19918            if (DEBUG_BACKUP) {
19919                Slog.e(TAG, "Unable to write default apps for backup", e);
19920            }
19921            return null;
19922        }
19923
19924        return dataStream.toByteArray();
19925    }
19926
19927    @Override
19928    public void restorePermissionGrants(byte[] backup, int userId) {
19929        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19930            throw new SecurityException("Only the system may call restorePermissionGrants()");
19931        }
19932
19933        try {
19934            final XmlPullParser parser = Xml.newPullParser();
19935            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19936            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19937                    new BlobXmlRestorer() {
19938                        @Override
19939                        public void apply(XmlPullParser parser, int userId)
19940                                throws XmlPullParserException, IOException {
19941                            synchronized (mPackages) {
19942                                processRestoredPermissionGrantsLPr(parser, userId);
19943                            }
19944                        }
19945                    } );
19946        } catch (Exception e) {
19947            if (DEBUG_BACKUP) {
19948                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19949            }
19950        }
19951    }
19952
19953    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19954            throws IOException {
19955        serializer.startTag(null, TAG_ALL_GRANTS);
19956
19957        final int N = mSettings.mPackages.size();
19958        for (int i = 0; i < N; i++) {
19959            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19960            boolean pkgGrantsKnown = false;
19961
19962            PermissionsState packagePerms = ps.getPermissionsState();
19963
19964            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19965                final int grantFlags = state.getFlags();
19966                // only look at grants that are not system/policy fixed
19967                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19968                    final boolean isGranted = state.isGranted();
19969                    // And only back up the user-twiddled state bits
19970                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19971                        final String packageName = mSettings.mPackages.keyAt(i);
19972                        if (!pkgGrantsKnown) {
19973                            serializer.startTag(null, TAG_GRANT);
19974                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19975                            pkgGrantsKnown = true;
19976                        }
19977
19978                        final boolean userSet =
19979                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19980                        final boolean userFixed =
19981                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19982                        final boolean revoke =
19983                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19984
19985                        serializer.startTag(null, TAG_PERMISSION);
19986                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19987                        if (isGranted) {
19988                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19989                        }
19990                        if (userSet) {
19991                            serializer.attribute(null, ATTR_USER_SET, "true");
19992                        }
19993                        if (userFixed) {
19994                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19995                        }
19996                        if (revoke) {
19997                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19998                        }
19999                        serializer.endTag(null, TAG_PERMISSION);
20000                    }
20001                }
20002            }
20003
20004            if (pkgGrantsKnown) {
20005                serializer.endTag(null, TAG_GRANT);
20006            }
20007        }
20008
20009        serializer.endTag(null, TAG_ALL_GRANTS);
20010    }
20011
20012    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20013            throws XmlPullParserException, IOException {
20014        String pkgName = null;
20015        int outerDepth = parser.getDepth();
20016        int type;
20017        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20018                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20019            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20020                continue;
20021            }
20022
20023            final String tagName = parser.getName();
20024            if (tagName.equals(TAG_GRANT)) {
20025                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20026                if (DEBUG_BACKUP) {
20027                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20028                }
20029            } else if (tagName.equals(TAG_PERMISSION)) {
20030
20031                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20032                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20033
20034                int newFlagSet = 0;
20035                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20036                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20037                }
20038                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20039                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20040                }
20041                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20042                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20043                }
20044                if (DEBUG_BACKUP) {
20045                    Slog.v(TAG, "  + Restoring grant:"
20046                            + " pkg=" + pkgName
20047                            + " perm=" + permName
20048                            + " granted=" + isGranted
20049                            + " bits=0x" + Integer.toHexString(newFlagSet));
20050                }
20051                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20052                if (ps != null) {
20053                    // Already installed so we apply the grant immediately
20054                    if (DEBUG_BACKUP) {
20055                        Slog.v(TAG, "        + already installed; applying");
20056                    }
20057                    PermissionsState perms = ps.getPermissionsState();
20058                    BasePermission bp =
20059                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20060                    if (bp != null) {
20061                        if (isGranted) {
20062                            perms.grantRuntimePermission(bp, userId);
20063                        }
20064                        if (newFlagSet != 0) {
20065                            perms.updatePermissionFlags(
20066                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20067                        }
20068                    }
20069                } else {
20070                    // Need to wait for post-restore install to apply the grant
20071                    if (DEBUG_BACKUP) {
20072                        Slog.v(TAG, "        - not yet installed; saving for later");
20073                    }
20074                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20075                            isGranted, newFlagSet, userId);
20076                }
20077            } else {
20078                PackageManagerService.reportSettingsProblem(Log.WARN,
20079                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20080                XmlUtils.skipCurrentTag(parser);
20081            }
20082        }
20083
20084        scheduleWriteSettingsLocked();
20085        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20086    }
20087
20088    @Override
20089    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20090            int sourceUserId, int targetUserId, int flags) {
20091        mContext.enforceCallingOrSelfPermission(
20092                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20093        int callingUid = Binder.getCallingUid();
20094        enforceOwnerRights(ownerPackage, callingUid);
20095        PackageManagerServiceUtils.enforceShellRestriction(
20096                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20097        if (intentFilter.countActions() == 0) {
20098            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20099            return;
20100        }
20101        synchronized (mPackages) {
20102            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20103                    ownerPackage, targetUserId, flags);
20104            CrossProfileIntentResolver resolver =
20105                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20106            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20107            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20108            if (existing != null) {
20109                int size = existing.size();
20110                for (int i = 0; i < size; i++) {
20111                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20112                        return;
20113                    }
20114                }
20115            }
20116            resolver.addFilter(newFilter);
20117            scheduleWritePackageRestrictionsLocked(sourceUserId);
20118        }
20119    }
20120
20121    @Override
20122    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20123        mContext.enforceCallingOrSelfPermission(
20124                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20125        final int callingUid = Binder.getCallingUid();
20126        enforceOwnerRights(ownerPackage, callingUid);
20127        PackageManagerServiceUtils.enforceShellRestriction(
20128                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20129        synchronized (mPackages) {
20130            CrossProfileIntentResolver resolver =
20131                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20132            ArraySet<CrossProfileIntentFilter> set =
20133                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20134            for (CrossProfileIntentFilter filter : set) {
20135                if (filter.getOwnerPackage().equals(ownerPackage)) {
20136                    resolver.removeFilter(filter);
20137                }
20138            }
20139            scheduleWritePackageRestrictionsLocked(sourceUserId);
20140        }
20141    }
20142
20143    // Enforcing that callingUid is owning pkg on userId
20144    private void enforceOwnerRights(String pkg, int callingUid) {
20145        // The system owns everything.
20146        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20147            return;
20148        }
20149        final int callingUserId = UserHandle.getUserId(callingUid);
20150        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20151        if (pi == null) {
20152            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20153                    + callingUserId);
20154        }
20155        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20156            throw new SecurityException("Calling uid " + callingUid
20157                    + " does not own package " + pkg);
20158        }
20159    }
20160
20161    @Override
20162    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20163        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20164            return null;
20165        }
20166        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20167    }
20168
20169    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20170        UserManagerService ums = UserManagerService.getInstance();
20171        if (ums != null) {
20172            final UserInfo parent = ums.getProfileParent(userId);
20173            final int launcherUid = (parent != null) ? parent.id : userId;
20174            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20175            if (launcherComponent != null) {
20176                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20177                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20178                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20179                        .setPackage(launcherComponent.getPackageName());
20180                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20181            }
20182        }
20183    }
20184
20185    /**
20186     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20187     * then reports the most likely home activity or null if there are more than one.
20188     */
20189    private ComponentName getDefaultHomeActivity(int userId) {
20190        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20191        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20192        if (cn != null) {
20193            return cn;
20194        }
20195
20196        // Find the launcher with the highest priority and return that component if there are no
20197        // other home activity with the same priority.
20198        int lastPriority = Integer.MIN_VALUE;
20199        ComponentName lastComponent = null;
20200        final int size = allHomeCandidates.size();
20201        for (int i = 0; i < size; i++) {
20202            final ResolveInfo ri = allHomeCandidates.get(i);
20203            if (ri.priority > lastPriority) {
20204                lastComponent = ri.activityInfo.getComponentName();
20205                lastPriority = ri.priority;
20206            } else if (ri.priority == lastPriority) {
20207                // Two components found with same priority.
20208                lastComponent = null;
20209            }
20210        }
20211        return lastComponent;
20212    }
20213
20214    private Intent getHomeIntent() {
20215        Intent intent = new Intent(Intent.ACTION_MAIN);
20216        intent.addCategory(Intent.CATEGORY_HOME);
20217        intent.addCategory(Intent.CATEGORY_DEFAULT);
20218        return intent;
20219    }
20220
20221    private IntentFilter getHomeFilter() {
20222        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20223        filter.addCategory(Intent.CATEGORY_HOME);
20224        filter.addCategory(Intent.CATEGORY_DEFAULT);
20225        return filter;
20226    }
20227
20228    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20229            int userId) {
20230        Intent intent  = getHomeIntent();
20231        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20232                PackageManager.GET_META_DATA, userId);
20233        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20234                true, false, false, userId);
20235
20236        allHomeCandidates.clear();
20237        if (list != null) {
20238            for (ResolveInfo ri : list) {
20239                allHomeCandidates.add(ri);
20240            }
20241        }
20242        return (preferred == null || preferred.activityInfo == null)
20243                ? null
20244                : new ComponentName(preferred.activityInfo.packageName,
20245                        preferred.activityInfo.name);
20246    }
20247
20248    @Override
20249    public void setHomeActivity(ComponentName comp, int userId) {
20250        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20251            return;
20252        }
20253        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20254        getHomeActivitiesAsUser(homeActivities, userId);
20255
20256        boolean found = false;
20257
20258        final int size = homeActivities.size();
20259        final ComponentName[] set = new ComponentName[size];
20260        for (int i = 0; i < size; i++) {
20261            final ResolveInfo candidate = homeActivities.get(i);
20262            final ActivityInfo info = candidate.activityInfo;
20263            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20264            set[i] = activityName;
20265            if (!found && activityName.equals(comp)) {
20266                found = true;
20267            }
20268        }
20269        if (!found) {
20270            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20271                    + userId);
20272        }
20273        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20274                set, comp, userId);
20275    }
20276
20277    private @Nullable String getSetupWizardPackageName() {
20278        final Intent intent = new Intent(Intent.ACTION_MAIN);
20279        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20280
20281        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20282                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20283                        | MATCH_DISABLED_COMPONENTS,
20284                UserHandle.myUserId());
20285        if (matches.size() == 1) {
20286            return matches.get(0).getComponentInfo().packageName;
20287        } else {
20288            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20289                    + ": matches=" + matches);
20290            return null;
20291        }
20292    }
20293
20294    private @Nullable String getStorageManagerPackageName() {
20295        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20296
20297        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20298                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20299                        | MATCH_DISABLED_COMPONENTS,
20300                UserHandle.myUserId());
20301        if (matches.size() == 1) {
20302            return matches.get(0).getComponentInfo().packageName;
20303        } else {
20304            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20305                    + matches.size() + ": matches=" + matches);
20306            return null;
20307        }
20308    }
20309
20310    @Override
20311    public void setApplicationEnabledSetting(String appPackageName,
20312            int newState, int flags, int userId, String callingPackage) {
20313        if (!sUserManager.exists(userId)) return;
20314        if (callingPackage == null) {
20315            callingPackage = Integer.toString(Binder.getCallingUid());
20316        }
20317        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20318    }
20319
20320    @Override
20321    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20322        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20323        synchronized (mPackages) {
20324            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20325            if (pkgSetting != null) {
20326                pkgSetting.setUpdateAvailable(updateAvailable);
20327            }
20328        }
20329    }
20330
20331    @Override
20332    public void setComponentEnabledSetting(ComponentName componentName,
20333            int newState, int flags, int userId) {
20334        if (!sUserManager.exists(userId)) return;
20335        setEnabledSetting(componentName.getPackageName(),
20336                componentName.getClassName(), newState, flags, userId, null);
20337    }
20338
20339    private void setEnabledSetting(final String packageName, String className, int newState,
20340            final int flags, int userId, String callingPackage) {
20341        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20342              || newState == COMPONENT_ENABLED_STATE_ENABLED
20343              || newState == COMPONENT_ENABLED_STATE_DISABLED
20344              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20345              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20346            throw new IllegalArgumentException("Invalid new component state: "
20347                    + newState);
20348        }
20349        PackageSetting pkgSetting;
20350        final int callingUid = Binder.getCallingUid();
20351        final int permission;
20352        if (callingUid == Process.SYSTEM_UID) {
20353            permission = PackageManager.PERMISSION_GRANTED;
20354        } else {
20355            permission = mContext.checkCallingOrSelfPermission(
20356                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20357        }
20358        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20359                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20360        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20361        boolean sendNow = false;
20362        boolean isApp = (className == null);
20363        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20364        String componentName = isApp ? packageName : className;
20365        int packageUid = -1;
20366        ArrayList<String> components;
20367
20368        // reader
20369        synchronized (mPackages) {
20370            pkgSetting = mSettings.mPackages.get(packageName);
20371            if (pkgSetting == null) {
20372                if (!isCallerInstantApp) {
20373                    if (className == null) {
20374                        throw new IllegalArgumentException("Unknown package: " + packageName);
20375                    }
20376                    throw new IllegalArgumentException(
20377                            "Unknown component: " + packageName + "/" + className);
20378                } else {
20379                    // throw SecurityException to prevent leaking package information
20380                    throw new SecurityException(
20381                            "Attempt to change component state; "
20382                            + "pid=" + Binder.getCallingPid()
20383                            + ", uid=" + callingUid
20384                            + (className == null
20385                                    ? ", package=" + packageName
20386                                    : ", component=" + packageName + "/" + className));
20387                }
20388            }
20389        }
20390
20391        // Limit who can change which apps
20392        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20393            // Don't allow apps that don't have permission to modify other apps
20394            if (!allowedByPermission
20395                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20396                throw new SecurityException(
20397                        "Attempt to change component state; "
20398                        + "pid=" + Binder.getCallingPid()
20399                        + ", uid=" + callingUid
20400                        + (className == null
20401                                ? ", package=" + packageName
20402                                : ", component=" + packageName + "/" + className));
20403            }
20404            // Don't allow changing protected packages.
20405            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20406                throw new SecurityException("Cannot disable a protected package: " + packageName);
20407            }
20408        }
20409
20410        synchronized (mPackages) {
20411            if (callingUid == Process.SHELL_UID
20412                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20413                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20414                // unless it is a test package.
20415                int oldState = pkgSetting.getEnabled(userId);
20416                if (className == null
20417                        &&
20418                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20419                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20420                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20421                        &&
20422                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20423                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20424                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20425                    // ok
20426                } else {
20427                    throw new SecurityException(
20428                            "Shell cannot change component state for " + packageName + "/"
20429                                    + className + " to " + newState);
20430                }
20431            }
20432        }
20433        if (className == null) {
20434            // We're dealing with an application/package level state change
20435            synchronized (mPackages) {
20436                if (pkgSetting.getEnabled(userId) == newState) {
20437                    // Nothing to do
20438                    return;
20439                }
20440            }
20441            // If we're enabling a system stub, there's a little more work to do.
20442            // Prior to enabling the package, we need to decompress the APK(s) to the
20443            // data partition and then replace the version on the system partition.
20444            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20445            final boolean isSystemStub = deletedPkg.isStub
20446                    && deletedPkg.isSystem();
20447            if (isSystemStub
20448                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20449                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20450                final File codePath = decompressPackage(deletedPkg);
20451                if (codePath == null) {
20452                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20453                    return;
20454                }
20455                // TODO remove direct parsing of the package object during internal cleanup
20456                // of scan package
20457                // We need to call parse directly here for no other reason than we need
20458                // the new package in order to disable the old one [we use the information
20459                // for some internal optimization to optionally create a new package setting
20460                // object on replace]. However, we can't get the package from the scan
20461                // because the scan modifies live structures and we need to remove the
20462                // old [system] package from the system before a scan can be attempted.
20463                // Once scan is indempotent we can remove this parse and use the package
20464                // object we scanned, prior to adding it to package settings.
20465                final PackageParser pp = new PackageParser();
20466                pp.setSeparateProcesses(mSeparateProcesses);
20467                pp.setDisplayMetrics(mMetrics);
20468                pp.setCallback(mPackageParserCallback);
20469                final PackageParser.Package tmpPkg;
20470                try {
20471                    final @ParseFlags int parseFlags = mDefParseFlags
20472                            | PackageParser.PARSE_MUST_BE_APK
20473                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20474                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20475                } catch (PackageParserException e) {
20476                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20477                    return;
20478                }
20479                synchronized (mInstallLock) {
20480                    // Disable the stub and remove any package entries
20481                    removePackageLI(deletedPkg, true);
20482                    synchronized (mPackages) {
20483                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20484                    }
20485                    final PackageParser.Package pkg;
20486                    try (PackageFreezer freezer =
20487                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20488                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20489                                | PackageParser.PARSE_ENFORCE_CODE;
20490                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20491                                0 /*currentTime*/, null /*user*/);
20492                        prepareAppDataAfterInstallLIF(pkg);
20493                        synchronized (mPackages) {
20494                            try {
20495                                updateSharedLibrariesLPr(pkg, null);
20496                            } catch (PackageManagerException e) {
20497                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20498                            }
20499                            mPermissionManager.updatePermissions(
20500                                    pkg.packageName, pkg, true, mPackages.values(),
20501                                    mPermissionCallback);
20502                            mSettings.writeLPr();
20503                        }
20504                    } catch (PackageManagerException e) {
20505                        // Whoops! Something went wrong; try to roll back to the stub
20506                        Slog.w(TAG, "Failed to install compressed system package:"
20507                                + pkgSetting.name, e);
20508                        // Remove the failed install
20509                        removeCodePathLI(codePath);
20510
20511                        // Install the system package
20512                        try (PackageFreezer freezer =
20513                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20514                            synchronized (mPackages) {
20515                                // NOTE: The system package always needs to be enabled; even
20516                                // if it's for a compressed stub. If we don't, installing the
20517                                // system package fails during scan [scanning checks the disabled
20518                                // packages]. We will reverse this later, after we've "installed"
20519                                // the stub.
20520                                // This leaves us in a fragile state; the stub should never be
20521                                // enabled, so, cross your fingers and hope nothing goes wrong
20522                                // until we can disable the package later.
20523                                enableSystemPackageLPw(deletedPkg);
20524                            }
20525                            installPackageFromSystemLIF(deletedPkg.codePath,
20526                                    false /*isPrivileged*/, null /*allUserHandles*/,
20527                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20528                                    true /*writeSettings*/);
20529                        } catch (PackageManagerException pme) {
20530                            Slog.w(TAG, "Failed to restore system package:"
20531                                    + deletedPkg.packageName, pme);
20532                        } finally {
20533                            synchronized (mPackages) {
20534                                mSettings.disableSystemPackageLPw(
20535                                        deletedPkg.packageName, true /*replaced*/);
20536                                mSettings.writeLPr();
20537                            }
20538                        }
20539                        return;
20540                    }
20541                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20542                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20543                    mDexManager.notifyPackageUpdated(pkg.packageName,
20544                            pkg.baseCodePath, pkg.splitCodePaths);
20545                }
20546            }
20547            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20548                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20549                // Don't care about who enables an app.
20550                callingPackage = null;
20551            }
20552            synchronized (mPackages) {
20553                pkgSetting.setEnabled(newState, userId, callingPackage);
20554            }
20555        } else {
20556            synchronized (mPackages) {
20557                // We're dealing with a component level state change
20558                // First, verify that this is a valid class name.
20559                PackageParser.Package pkg = pkgSetting.pkg;
20560                if (pkg == null || !pkg.hasComponentClassName(className)) {
20561                    if (pkg != null &&
20562                            pkg.applicationInfo.targetSdkVersion >=
20563                                    Build.VERSION_CODES.JELLY_BEAN) {
20564                        throw new IllegalArgumentException("Component class " + className
20565                                + " does not exist in " + packageName);
20566                    } else {
20567                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20568                                + className + " does not exist in " + packageName);
20569                    }
20570                }
20571                switch (newState) {
20572                    case COMPONENT_ENABLED_STATE_ENABLED:
20573                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20574                            return;
20575                        }
20576                        break;
20577                    case COMPONENT_ENABLED_STATE_DISABLED:
20578                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20579                            return;
20580                        }
20581                        break;
20582                    case COMPONENT_ENABLED_STATE_DEFAULT:
20583                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20584                            return;
20585                        }
20586                        break;
20587                    default:
20588                        Slog.e(TAG, "Invalid new component state: " + newState);
20589                        return;
20590                }
20591            }
20592        }
20593        synchronized (mPackages) {
20594            scheduleWritePackageRestrictionsLocked(userId);
20595            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20596            final long callingId = Binder.clearCallingIdentity();
20597            try {
20598                updateInstantAppInstallerLocked(packageName);
20599            } finally {
20600                Binder.restoreCallingIdentity(callingId);
20601            }
20602            components = mPendingBroadcasts.get(userId, packageName);
20603            final boolean newPackage = components == null;
20604            if (newPackage) {
20605                components = new ArrayList<String>();
20606            }
20607            if (!components.contains(componentName)) {
20608                components.add(componentName);
20609            }
20610            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20611                sendNow = true;
20612                // Purge entry from pending broadcast list if another one exists already
20613                // since we are sending one right away.
20614                mPendingBroadcasts.remove(userId, packageName);
20615            } else {
20616                if (newPackage) {
20617                    mPendingBroadcasts.put(userId, packageName, components);
20618                }
20619                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20620                    // Schedule a message
20621                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20622                }
20623            }
20624        }
20625
20626        long callingId = Binder.clearCallingIdentity();
20627        try {
20628            if (sendNow) {
20629                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20630                sendPackageChangedBroadcast(packageName,
20631                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20632            }
20633        } finally {
20634            Binder.restoreCallingIdentity(callingId);
20635        }
20636    }
20637
20638    @Override
20639    public void flushPackageRestrictionsAsUser(int userId) {
20640        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20641            return;
20642        }
20643        if (!sUserManager.exists(userId)) {
20644            return;
20645        }
20646        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20647                false /* checkShell */, "flushPackageRestrictions");
20648        synchronized (mPackages) {
20649            mSettings.writePackageRestrictionsLPr(userId);
20650            mDirtyUsers.remove(userId);
20651            if (mDirtyUsers.isEmpty()) {
20652                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20653            }
20654        }
20655    }
20656
20657    private void sendPackageChangedBroadcast(String packageName,
20658            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20659        if (DEBUG_INSTALL)
20660            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20661                    + componentNames);
20662        Bundle extras = new Bundle(4);
20663        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20664        String nameList[] = new String[componentNames.size()];
20665        componentNames.toArray(nameList);
20666        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20667        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20668        extras.putInt(Intent.EXTRA_UID, packageUid);
20669        // If this is not reporting a change of the overall package, then only send it
20670        // to registered receivers.  We don't want to launch a swath of apps for every
20671        // little component state change.
20672        final int flags = !componentNames.contains(packageName)
20673                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20674        final int userId = UserHandle.getUserId(packageUid);
20675        final boolean isInstantApp = isInstantApp(packageName, userId);
20676        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20677        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20678        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20679                userIds, instantUserIds);
20680    }
20681
20682    @Override
20683    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20684        if (!sUserManager.exists(userId)) return;
20685        final int callingUid = Binder.getCallingUid();
20686        if (getInstantAppPackageName(callingUid) != null) {
20687            return;
20688        }
20689        final int permission = mContext.checkCallingOrSelfPermission(
20690                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20691        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20692        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20693                true /* requireFullPermission */, true /* checkShell */, "stop package");
20694        // writer
20695        synchronized (mPackages) {
20696            final PackageSetting ps = mSettings.mPackages.get(packageName);
20697            if (!filterAppAccessLPr(ps, callingUid, userId)
20698                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20699                            allowedByPermission, callingUid, userId)) {
20700                scheduleWritePackageRestrictionsLocked(userId);
20701            }
20702        }
20703    }
20704
20705    @Override
20706    public String getInstallerPackageName(String packageName) {
20707        final int callingUid = Binder.getCallingUid();
20708        if (getInstantAppPackageName(callingUid) != null) {
20709            return null;
20710        }
20711        // reader
20712        synchronized (mPackages) {
20713            final PackageSetting ps = mSettings.mPackages.get(packageName);
20714            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20715                return null;
20716            }
20717            return mSettings.getInstallerPackageNameLPr(packageName);
20718        }
20719    }
20720
20721    public boolean isOrphaned(String packageName) {
20722        // reader
20723        synchronized (mPackages) {
20724            return mSettings.isOrphaned(packageName);
20725        }
20726    }
20727
20728    @Override
20729    public int getApplicationEnabledSetting(String packageName, int userId) {
20730        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20731        int callingUid = Binder.getCallingUid();
20732        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20733                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20734        // reader
20735        synchronized (mPackages) {
20736            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20737                return COMPONENT_ENABLED_STATE_DISABLED;
20738            }
20739            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20740        }
20741    }
20742
20743    @Override
20744    public int getComponentEnabledSetting(ComponentName component, int userId) {
20745        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20746        int callingUid = Binder.getCallingUid();
20747        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20748                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20749        synchronized (mPackages) {
20750            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20751                    component, TYPE_UNKNOWN, userId)) {
20752                return COMPONENT_ENABLED_STATE_DISABLED;
20753            }
20754            return mSettings.getComponentEnabledSettingLPr(component, userId);
20755        }
20756    }
20757
20758    @Override
20759    public void enterSafeMode() {
20760        enforceSystemOrRoot("Only the system can request entering safe mode");
20761
20762        if (!mSystemReady) {
20763            mSafeMode = true;
20764        }
20765    }
20766
20767    @Override
20768    public void systemReady() {
20769        enforceSystemOrRoot("Only the system can claim the system is ready");
20770
20771        mSystemReady = true;
20772        final ContentResolver resolver = mContext.getContentResolver();
20773        ContentObserver co = new ContentObserver(mHandler) {
20774            @Override
20775            public void onChange(boolean selfChange) {
20776                mEphemeralAppsDisabled =
20777                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20778                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20779            }
20780        };
20781        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20782                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20783                false, co, UserHandle.USER_SYSTEM);
20784        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20785                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20786        co.onChange(true);
20787
20788        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20789        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20790        // it is done.
20791        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20792            @Override
20793            public void onChange(boolean selfChange) {
20794                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20795                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20796                        oobEnabled == 1 ? "true" : "false");
20797            }
20798        };
20799        mContext.getContentResolver().registerContentObserver(
20800                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20801                UserHandle.USER_SYSTEM);
20802        // At boot, restore the value from the setting, which persists across reboot.
20803        privAppOobObserver.onChange(true);
20804
20805        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20806        // disabled after already being started.
20807        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20808                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20809
20810        // Read the compatibilty setting when the system is ready.
20811        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20812                mContext.getContentResolver(),
20813                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20814        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20815        if (DEBUG_SETTINGS) {
20816            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20817        }
20818
20819        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20820
20821        synchronized (mPackages) {
20822            // Verify that all of the preferred activity components actually
20823            // exist.  It is possible for applications to be updated and at
20824            // that point remove a previously declared activity component that
20825            // had been set as a preferred activity.  We try to clean this up
20826            // the next time we encounter that preferred activity, but it is
20827            // possible for the user flow to never be able to return to that
20828            // situation so here we do a sanity check to make sure we haven't
20829            // left any junk around.
20830            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20831            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20832                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20833                removed.clear();
20834                for (PreferredActivity pa : pir.filterSet()) {
20835                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20836                        removed.add(pa);
20837                    }
20838                }
20839                if (removed.size() > 0) {
20840                    for (int r=0; r<removed.size(); r++) {
20841                        PreferredActivity pa = removed.get(r);
20842                        Slog.w(TAG, "Removing dangling preferred activity: "
20843                                + pa.mPref.mComponent);
20844                        pir.removeFilter(pa);
20845                    }
20846                    mSettings.writePackageRestrictionsLPr(
20847                            mSettings.mPreferredActivities.keyAt(i));
20848                }
20849            }
20850
20851            for (int userId : UserManagerService.getInstance().getUserIds()) {
20852                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20853                    grantPermissionsUserIds = ArrayUtils.appendInt(
20854                            grantPermissionsUserIds, userId);
20855                }
20856            }
20857        }
20858        sUserManager.systemReady();
20859        // If we upgraded grant all default permissions before kicking off.
20860        for (int userId : grantPermissionsUserIds) {
20861            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20862        }
20863
20864        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20865            // If we did not grant default permissions, we preload from this the
20866            // default permission exceptions lazily to ensure we don't hit the
20867            // disk on a new user creation.
20868            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20869        }
20870
20871        // Now that we've scanned all packages, and granted any default
20872        // permissions, ensure permissions are updated. Beware of dragons if you
20873        // try optimizing this.
20874        synchronized (mPackages) {
20875            mPermissionManager.updateAllPermissions(
20876                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20877                    mPermissionCallback);
20878        }
20879
20880        // Kick off any messages waiting for system ready
20881        if (mPostSystemReadyMessages != null) {
20882            for (Message msg : mPostSystemReadyMessages) {
20883                msg.sendToTarget();
20884            }
20885            mPostSystemReadyMessages = null;
20886        }
20887
20888        // Watch for external volumes that come and go over time
20889        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20890        storage.registerListener(mStorageListener);
20891
20892        mInstallerService.systemReady();
20893        mPackageDexOptimizer.systemReady();
20894
20895        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20896                StorageManagerInternal.class);
20897        StorageManagerInternal.addExternalStoragePolicy(
20898                new StorageManagerInternal.ExternalStorageMountPolicy() {
20899            @Override
20900            public int getMountMode(int uid, String packageName) {
20901                if (Process.isIsolated(uid)) {
20902                    return Zygote.MOUNT_EXTERNAL_NONE;
20903                }
20904                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20905                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20906                }
20907                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20908                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20909                }
20910                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20911                    return Zygote.MOUNT_EXTERNAL_READ;
20912                }
20913                return Zygote.MOUNT_EXTERNAL_WRITE;
20914            }
20915
20916            @Override
20917            public boolean hasExternalStorage(int uid, String packageName) {
20918                return true;
20919            }
20920        });
20921
20922        // Now that we're mostly running, clean up stale users and apps
20923        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20924        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20925
20926        mPermissionManager.systemReady();
20927    }
20928
20929    public void waitForAppDataPrepared() {
20930        if (mPrepareAppDataFuture == null) {
20931            return;
20932        }
20933        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20934        mPrepareAppDataFuture = null;
20935    }
20936
20937    @Override
20938    public boolean isSafeMode() {
20939        // allow instant applications
20940        return mSafeMode;
20941    }
20942
20943    @Override
20944    public boolean hasSystemUidErrors() {
20945        // allow instant applications
20946        return mHasSystemUidErrors;
20947    }
20948
20949    static String arrayToString(int[] array) {
20950        StringBuffer buf = new StringBuffer(128);
20951        buf.append('[');
20952        if (array != null) {
20953            for (int i=0; i<array.length; i++) {
20954                if (i > 0) buf.append(", ");
20955                buf.append(array[i]);
20956            }
20957        }
20958        buf.append(']');
20959        return buf.toString();
20960    }
20961
20962    @Override
20963    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20964            FileDescriptor err, String[] args, ShellCallback callback,
20965            ResultReceiver resultReceiver) {
20966        (new PackageManagerShellCommand(this)).exec(
20967                this, in, out, err, args, callback, resultReceiver);
20968    }
20969
20970    @Override
20971    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20972        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20973
20974        DumpState dumpState = new DumpState();
20975        boolean fullPreferred = false;
20976        boolean checkin = false;
20977
20978        String packageName = null;
20979        ArraySet<String> permissionNames = null;
20980
20981        int opti = 0;
20982        while (opti < args.length) {
20983            String opt = args[opti];
20984            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20985                break;
20986            }
20987            opti++;
20988
20989            if ("-a".equals(opt)) {
20990                // Right now we only know how to print all.
20991            } else if ("-h".equals(opt)) {
20992                pw.println("Package manager dump options:");
20993                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20994                pw.println("    --checkin: dump for a checkin");
20995                pw.println("    -f: print details of intent filters");
20996                pw.println("    -h: print this help");
20997                pw.println("  cmd may be one of:");
20998                pw.println("    l[ibraries]: list known shared libraries");
20999                pw.println("    f[eatures]: list device features");
21000                pw.println("    k[eysets]: print known keysets");
21001                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21002                pw.println("    perm[issions]: dump permissions");
21003                pw.println("    permission [name ...]: dump declaration and use of given permission");
21004                pw.println("    pref[erred]: print preferred package settings");
21005                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21006                pw.println("    prov[iders]: dump content providers");
21007                pw.println("    p[ackages]: dump installed packages");
21008                pw.println("    s[hared-users]: dump shared user IDs");
21009                pw.println("    m[essages]: print collected runtime messages");
21010                pw.println("    v[erifiers]: print package verifier info");
21011                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21012                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21013                pw.println("    version: print database version info");
21014                pw.println("    write: write current settings now");
21015                pw.println("    installs: details about install sessions");
21016                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21017                pw.println("    dexopt: dump dexopt state");
21018                pw.println("    compiler-stats: dump compiler statistics");
21019                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21020                pw.println("    service-permissions: dump permissions required by services");
21021                pw.println("    <package.name>: info about given package");
21022                return;
21023            } else if ("--checkin".equals(opt)) {
21024                checkin = true;
21025            } else if ("-f".equals(opt)) {
21026                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21027            } else if ("--proto".equals(opt)) {
21028                dumpProto(fd);
21029                return;
21030            } else {
21031                pw.println("Unknown argument: " + opt + "; use -h for help");
21032            }
21033        }
21034
21035        // Is the caller requesting to dump a particular piece of data?
21036        if (opti < args.length) {
21037            String cmd = args[opti];
21038            opti++;
21039            // Is this a package name?
21040            if ("android".equals(cmd) || cmd.contains(".")) {
21041                packageName = cmd;
21042                // When dumping a single package, we always dump all of its
21043                // filter information since the amount of data will be reasonable.
21044                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21045            } else if ("check-permission".equals(cmd)) {
21046                if (opti >= args.length) {
21047                    pw.println("Error: check-permission missing permission argument");
21048                    return;
21049                }
21050                String perm = args[opti];
21051                opti++;
21052                if (opti >= args.length) {
21053                    pw.println("Error: check-permission missing package argument");
21054                    return;
21055                }
21056
21057                String pkg = args[opti];
21058                opti++;
21059                int user = UserHandle.getUserId(Binder.getCallingUid());
21060                if (opti < args.length) {
21061                    try {
21062                        user = Integer.parseInt(args[opti]);
21063                    } catch (NumberFormatException e) {
21064                        pw.println("Error: check-permission user argument is not a number: "
21065                                + args[opti]);
21066                        return;
21067                    }
21068                }
21069
21070                // Normalize package name to handle renamed packages and static libs
21071                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21072
21073                pw.println(checkPermission(perm, pkg, user));
21074                return;
21075            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21076                dumpState.setDump(DumpState.DUMP_LIBS);
21077            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21078                dumpState.setDump(DumpState.DUMP_FEATURES);
21079            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21080                if (opti >= args.length) {
21081                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21082                            | DumpState.DUMP_SERVICE_RESOLVERS
21083                            | DumpState.DUMP_RECEIVER_RESOLVERS
21084                            | DumpState.DUMP_CONTENT_RESOLVERS);
21085                } else {
21086                    while (opti < args.length) {
21087                        String name = args[opti];
21088                        if ("a".equals(name) || "activity".equals(name)) {
21089                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21090                        } else if ("s".equals(name) || "service".equals(name)) {
21091                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21092                        } else if ("r".equals(name) || "receiver".equals(name)) {
21093                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21094                        } else if ("c".equals(name) || "content".equals(name)) {
21095                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21096                        } else {
21097                            pw.println("Error: unknown resolver table type: " + name);
21098                            return;
21099                        }
21100                        opti++;
21101                    }
21102                }
21103            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21104                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21105            } else if ("permission".equals(cmd)) {
21106                if (opti >= args.length) {
21107                    pw.println("Error: permission requires permission name");
21108                    return;
21109                }
21110                permissionNames = new ArraySet<>();
21111                while (opti < args.length) {
21112                    permissionNames.add(args[opti]);
21113                    opti++;
21114                }
21115                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21116                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21117            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21118                dumpState.setDump(DumpState.DUMP_PREFERRED);
21119            } else if ("preferred-xml".equals(cmd)) {
21120                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21121                if (opti < args.length && "--full".equals(args[opti])) {
21122                    fullPreferred = true;
21123                    opti++;
21124                }
21125            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21126                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21127            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21128                dumpState.setDump(DumpState.DUMP_PACKAGES);
21129            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21130                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21131            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21132                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21133            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21134                dumpState.setDump(DumpState.DUMP_MESSAGES);
21135            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21136                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21137            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21138                    || "intent-filter-verifiers".equals(cmd)) {
21139                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21140            } else if ("version".equals(cmd)) {
21141                dumpState.setDump(DumpState.DUMP_VERSION);
21142            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21143                dumpState.setDump(DumpState.DUMP_KEYSETS);
21144            } else if ("installs".equals(cmd)) {
21145                dumpState.setDump(DumpState.DUMP_INSTALLS);
21146            } else if ("frozen".equals(cmd)) {
21147                dumpState.setDump(DumpState.DUMP_FROZEN);
21148            } else if ("volumes".equals(cmd)) {
21149                dumpState.setDump(DumpState.DUMP_VOLUMES);
21150            } else if ("dexopt".equals(cmd)) {
21151                dumpState.setDump(DumpState.DUMP_DEXOPT);
21152            } else if ("compiler-stats".equals(cmd)) {
21153                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21154            } else if ("changes".equals(cmd)) {
21155                dumpState.setDump(DumpState.DUMP_CHANGES);
21156            } else if ("service-permissions".equals(cmd)) {
21157                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21158            } else if ("write".equals(cmd)) {
21159                synchronized (mPackages) {
21160                    mSettings.writeLPr();
21161                    pw.println("Settings written.");
21162                    return;
21163                }
21164            }
21165        }
21166
21167        if (checkin) {
21168            pw.println("vers,1");
21169        }
21170
21171        // reader
21172        synchronized (mPackages) {
21173            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21174                if (!checkin) {
21175                    if (dumpState.onTitlePrinted())
21176                        pw.println();
21177                    pw.println("Database versions:");
21178                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21179                }
21180            }
21181
21182            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21183                if (!checkin) {
21184                    if (dumpState.onTitlePrinted())
21185                        pw.println();
21186                    pw.println("Verifiers:");
21187                    pw.print("  Required: ");
21188                    pw.print(mRequiredVerifierPackage);
21189                    pw.print(" (uid=");
21190                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21191                            UserHandle.USER_SYSTEM));
21192                    pw.println(")");
21193                } else if (mRequiredVerifierPackage != null) {
21194                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21195                    pw.print(",");
21196                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21197                            UserHandle.USER_SYSTEM));
21198                }
21199            }
21200
21201            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21202                    packageName == null) {
21203                if (mIntentFilterVerifierComponent != null) {
21204                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21205                    if (!checkin) {
21206                        if (dumpState.onTitlePrinted())
21207                            pw.println();
21208                        pw.println("Intent Filter Verifier:");
21209                        pw.print("  Using: ");
21210                        pw.print(verifierPackageName);
21211                        pw.print(" (uid=");
21212                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21213                                UserHandle.USER_SYSTEM));
21214                        pw.println(")");
21215                    } else if (verifierPackageName != null) {
21216                        pw.print("ifv,"); pw.print(verifierPackageName);
21217                        pw.print(",");
21218                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21219                                UserHandle.USER_SYSTEM));
21220                    }
21221                } else {
21222                    pw.println();
21223                    pw.println("No Intent Filter Verifier available!");
21224                }
21225            }
21226
21227            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21228                boolean printedHeader = false;
21229                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21230                while (it.hasNext()) {
21231                    String libName = it.next();
21232                    LongSparseArray<SharedLibraryEntry> versionedLib
21233                            = mSharedLibraries.get(libName);
21234                    if (versionedLib == null) {
21235                        continue;
21236                    }
21237                    final int versionCount = versionedLib.size();
21238                    for (int i = 0; i < versionCount; i++) {
21239                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21240                        if (!checkin) {
21241                            if (!printedHeader) {
21242                                if (dumpState.onTitlePrinted())
21243                                    pw.println();
21244                                pw.println("Libraries:");
21245                                printedHeader = true;
21246                            }
21247                            pw.print("  ");
21248                        } else {
21249                            pw.print("lib,");
21250                        }
21251                        pw.print(libEntry.info.getName());
21252                        if (libEntry.info.isStatic()) {
21253                            pw.print(" version=" + libEntry.info.getLongVersion());
21254                        }
21255                        if (!checkin) {
21256                            pw.print(" -> ");
21257                        }
21258                        if (libEntry.path != null) {
21259                            pw.print(" (jar) ");
21260                            pw.print(libEntry.path);
21261                        } else {
21262                            pw.print(" (apk) ");
21263                            pw.print(libEntry.apk);
21264                        }
21265                        pw.println();
21266                    }
21267                }
21268            }
21269
21270            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21271                if (dumpState.onTitlePrinted())
21272                    pw.println();
21273                if (!checkin) {
21274                    pw.println("Features:");
21275                }
21276
21277                synchronized (mAvailableFeatures) {
21278                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21279                        if (checkin) {
21280                            pw.print("feat,");
21281                            pw.print(feat.name);
21282                            pw.print(",");
21283                            pw.println(feat.version);
21284                        } else {
21285                            pw.print("  ");
21286                            pw.print(feat.name);
21287                            if (feat.version > 0) {
21288                                pw.print(" version=");
21289                                pw.print(feat.version);
21290                            }
21291                            pw.println();
21292                        }
21293                    }
21294                }
21295            }
21296
21297            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21298                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21299                        : "Activity Resolver Table:", "  ", packageName,
21300                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21301                    dumpState.setTitlePrinted(true);
21302                }
21303            }
21304            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21305                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21306                        : "Receiver Resolver Table:", "  ", packageName,
21307                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21308                    dumpState.setTitlePrinted(true);
21309                }
21310            }
21311            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21312                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21313                        : "Service Resolver Table:", "  ", packageName,
21314                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21315                    dumpState.setTitlePrinted(true);
21316                }
21317            }
21318            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21319                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21320                        : "Provider Resolver Table:", "  ", packageName,
21321                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21322                    dumpState.setTitlePrinted(true);
21323                }
21324            }
21325
21326            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21327                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21328                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21329                    int user = mSettings.mPreferredActivities.keyAt(i);
21330                    if (pir.dump(pw,
21331                            dumpState.getTitlePrinted()
21332                                ? "\nPreferred Activities User " + user + ":"
21333                                : "Preferred Activities User " + user + ":", "  ",
21334                            packageName, true, false)) {
21335                        dumpState.setTitlePrinted(true);
21336                    }
21337                }
21338            }
21339
21340            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21341                pw.flush();
21342                FileOutputStream fout = new FileOutputStream(fd);
21343                BufferedOutputStream str = new BufferedOutputStream(fout);
21344                XmlSerializer serializer = new FastXmlSerializer();
21345                try {
21346                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21347                    serializer.startDocument(null, true);
21348                    serializer.setFeature(
21349                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21350                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21351                    serializer.endDocument();
21352                    serializer.flush();
21353                } catch (IllegalArgumentException e) {
21354                    pw.println("Failed writing: " + e);
21355                } catch (IllegalStateException e) {
21356                    pw.println("Failed writing: " + e);
21357                } catch (IOException e) {
21358                    pw.println("Failed writing: " + e);
21359                }
21360            }
21361
21362            if (!checkin
21363                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21364                    && packageName == null) {
21365                pw.println();
21366                int count = mSettings.mPackages.size();
21367                if (count == 0) {
21368                    pw.println("No applications!");
21369                    pw.println();
21370                } else {
21371                    final String prefix = "  ";
21372                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21373                    if (allPackageSettings.size() == 0) {
21374                        pw.println("No domain preferred apps!");
21375                        pw.println();
21376                    } else {
21377                        pw.println("App verification status:");
21378                        pw.println();
21379                        count = 0;
21380                        for (PackageSetting ps : allPackageSettings) {
21381                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21382                            if (ivi == null || ivi.getPackageName() == null) continue;
21383                            pw.println(prefix + "Package: " + ivi.getPackageName());
21384                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21385                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21386                            pw.println();
21387                            count++;
21388                        }
21389                        if (count == 0) {
21390                            pw.println(prefix + "No app verification established.");
21391                            pw.println();
21392                        }
21393                        for (int userId : sUserManager.getUserIds()) {
21394                            pw.println("App linkages for user " + userId + ":");
21395                            pw.println();
21396                            count = 0;
21397                            for (PackageSetting ps : allPackageSettings) {
21398                                final long status = ps.getDomainVerificationStatusForUser(userId);
21399                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21400                                        && !DEBUG_DOMAIN_VERIFICATION) {
21401                                    continue;
21402                                }
21403                                pw.println(prefix + "Package: " + ps.name);
21404                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21405                                String statusStr = IntentFilterVerificationInfo.
21406                                        getStatusStringFromValue(status);
21407                                pw.println(prefix + "Status:  " + statusStr);
21408                                pw.println();
21409                                count++;
21410                            }
21411                            if (count == 0) {
21412                                pw.println(prefix + "No configured app linkages.");
21413                                pw.println();
21414                            }
21415                        }
21416                    }
21417                }
21418            }
21419
21420            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21421                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21422            }
21423
21424            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21425                boolean printedSomething = false;
21426                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21427                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21428                        continue;
21429                    }
21430                    if (!printedSomething) {
21431                        if (dumpState.onTitlePrinted())
21432                            pw.println();
21433                        pw.println("Registered ContentProviders:");
21434                        printedSomething = true;
21435                    }
21436                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21437                    pw.print("    "); pw.println(p.toString());
21438                }
21439                printedSomething = false;
21440                for (Map.Entry<String, PackageParser.Provider> entry :
21441                        mProvidersByAuthority.entrySet()) {
21442                    PackageParser.Provider p = entry.getValue();
21443                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21444                        continue;
21445                    }
21446                    if (!printedSomething) {
21447                        if (dumpState.onTitlePrinted())
21448                            pw.println();
21449                        pw.println("ContentProvider Authorities:");
21450                        printedSomething = true;
21451                    }
21452                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21453                    pw.print("    "); pw.println(p.toString());
21454                    if (p.info != null && p.info.applicationInfo != null) {
21455                        final String appInfo = p.info.applicationInfo.toString();
21456                        pw.print("      applicationInfo="); pw.println(appInfo);
21457                    }
21458                }
21459            }
21460
21461            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21462                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21463            }
21464
21465            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21466                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21467            }
21468
21469            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21470                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21471            }
21472
21473            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21474                if (dumpState.onTitlePrinted()) pw.println();
21475                pw.println("Package Changes:");
21476                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21477                final int K = mChangedPackages.size();
21478                for (int i = 0; i < K; i++) {
21479                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21480                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21481                    final int N = changes.size();
21482                    if (N == 0) {
21483                        pw.print("    "); pw.println("No packages changed");
21484                    } else {
21485                        for (int j = 0; j < N; j++) {
21486                            final String pkgName = changes.valueAt(j);
21487                            final int sequenceNumber = changes.keyAt(j);
21488                            pw.print("    ");
21489                            pw.print("seq=");
21490                            pw.print(sequenceNumber);
21491                            pw.print(", package=");
21492                            pw.println(pkgName);
21493                        }
21494                    }
21495                }
21496            }
21497
21498            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21499                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21500            }
21501
21502            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21503                // XXX should handle packageName != null by dumping only install data that
21504                // the given package is involved with.
21505                if (dumpState.onTitlePrinted()) pw.println();
21506
21507                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21508                ipw.println();
21509                ipw.println("Frozen packages:");
21510                ipw.increaseIndent();
21511                if (mFrozenPackages.size() == 0) {
21512                    ipw.println("(none)");
21513                } else {
21514                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21515                        ipw.println(mFrozenPackages.valueAt(i));
21516                    }
21517                }
21518                ipw.decreaseIndent();
21519            }
21520
21521            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21522                if (dumpState.onTitlePrinted()) pw.println();
21523
21524                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21525                ipw.println();
21526                ipw.println("Loaded volumes:");
21527                ipw.increaseIndent();
21528                if (mLoadedVolumes.size() == 0) {
21529                    ipw.println("(none)");
21530                } else {
21531                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21532                        ipw.println(mLoadedVolumes.valueAt(i));
21533                    }
21534                }
21535                ipw.decreaseIndent();
21536            }
21537
21538            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21539                    && packageName == null) {
21540                if (dumpState.onTitlePrinted()) pw.println();
21541                pw.println("Service permissions:");
21542
21543                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21544                while (filterIterator.hasNext()) {
21545                    final ServiceIntentInfo info = filterIterator.next();
21546                    final ServiceInfo serviceInfo = info.service.info;
21547                    final String permission = serviceInfo.permission;
21548                    if (permission != null) {
21549                        pw.print("    ");
21550                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21551                        pw.print(": ");
21552                        pw.println(permission);
21553                    }
21554                }
21555            }
21556
21557            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21558                if (dumpState.onTitlePrinted()) pw.println();
21559                dumpDexoptStateLPr(pw, packageName);
21560            }
21561
21562            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21563                if (dumpState.onTitlePrinted()) pw.println();
21564                dumpCompilerStatsLPr(pw, packageName);
21565            }
21566
21567            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21568                if (dumpState.onTitlePrinted()) pw.println();
21569                mSettings.dumpReadMessagesLPr(pw, dumpState);
21570
21571                pw.println();
21572                pw.println("Package warning messages:");
21573                dumpCriticalInfo(pw, null);
21574            }
21575
21576            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21577                dumpCriticalInfo(pw, "msg,");
21578            }
21579        }
21580
21581        // PackageInstaller should be called outside of mPackages lock
21582        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21583            // XXX should handle packageName != null by dumping only install data that
21584            // the given package is involved with.
21585            if (dumpState.onTitlePrinted()) pw.println();
21586            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21587        }
21588    }
21589
21590    private void dumpProto(FileDescriptor fd) {
21591        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21592
21593        synchronized (mPackages) {
21594            final long requiredVerifierPackageToken =
21595                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21596            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21597            proto.write(
21598                    PackageServiceDumpProto.PackageShortProto.UID,
21599                    getPackageUid(
21600                            mRequiredVerifierPackage,
21601                            MATCH_DEBUG_TRIAGED_MISSING,
21602                            UserHandle.USER_SYSTEM));
21603            proto.end(requiredVerifierPackageToken);
21604
21605            if (mIntentFilterVerifierComponent != null) {
21606                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21607                final long verifierPackageToken =
21608                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21609                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21610                proto.write(
21611                        PackageServiceDumpProto.PackageShortProto.UID,
21612                        getPackageUid(
21613                                verifierPackageName,
21614                                MATCH_DEBUG_TRIAGED_MISSING,
21615                                UserHandle.USER_SYSTEM));
21616                proto.end(verifierPackageToken);
21617            }
21618
21619            dumpSharedLibrariesProto(proto);
21620            dumpFeaturesProto(proto);
21621            mSettings.dumpPackagesProto(proto);
21622            mSettings.dumpSharedUsersProto(proto);
21623            dumpCriticalInfo(proto);
21624        }
21625        proto.flush();
21626    }
21627
21628    private void dumpFeaturesProto(ProtoOutputStream proto) {
21629        synchronized (mAvailableFeatures) {
21630            final int count = mAvailableFeatures.size();
21631            for (int i = 0; i < count; i++) {
21632                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21633            }
21634        }
21635    }
21636
21637    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21638        final int count = mSharedLibraries.size();
21639        for (int i = 0; i < count; i++) {
21640            final String libName = mSharedLibraries.keyAt(i);
21641            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21642            if (versionedLib == null) {
21643                continue;
21644            }
21645            final int versionCount = versionedLib.size();
21646            for (int j = 0; j < versionCount; j++) {
21647                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21648                final long sharedLibraryToken =
21649                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21650                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21651                final boolean isJar = (libEntry.path != null);
21652                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21653                if (isJar) {
21654                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21655                } else {
21656                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21657                }
21658                proto.end(sharedLibraryToken);
21659            }
21660        }
21661    }
21662
21663    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21664        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21665        ipw.println();
21666        ipw.println("Dexopt state:");
21667        ipw.increaseIndent();
21668        Collection<PackageParser.Package> packages = null;
21669        if (packageName != null) {
21670            PackageParser.Package targetPackage = mPackages.get(packageName);
21671            if (targetPackage != null) {
21672                packages = Collections.singletonList(targetPackage);
21673            } else {
21674                ipw.println("Unable to find package: " + packageName);
21675                return;
21676            }
21677        } else {
21678            packages = mPackages.values();
21679        }
21680
21681        for (PackageParser.Package pkg : packages) {
21682            ipw.println("[" + pkg.packageName + "]");
21683            ipw.increaseIndent();
21684            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21685                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21686            ipw.decreaseIndent();
21687        }
21688    }
21689
21690    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21691        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21692        ipw.println();
21693        ipw.println("Compiler stats:");
21694        ipw.increaseIndent();
21695        Collection<PackageParser.Package> packages = null;
21696        if (packageName != null) {
21697            PackageParser.Package targetPackage = mPackages.get(packageName);
21698            if (targetPackage != null) {
21699                packages = Collections.singletonList(targetPackage);
21700            } else {
21701                ipw.println("Unable to find package: " + packageName);
21702                return;
21703            }
21704        } else {
21705            packages = mPackages.values();
21706        }
21707
21708        for (PackageParser.Package pkg : packages) {
21709            ipw.println("[" + pkg.packageName + "]");
21710            ipw.increaseIndent();
21711
21712            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21713            if (stats == null) {
21714                ipw.println("(No recorded stats)");
21715            } else {
21716                stats.dump(ipw);
21717            }
21718            ipw.decreaseIndent();
21719        }
21720    }
21721
21722    private String dumpDomainString(String packageName) {
21723        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21724                .getList();
21725        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21726
21727        ArraySet<String> result = new ArraySet<>();
21728        if (iviList.size() > 0) {
21729            for (IntentFilterVerificationInfo ivi : iviList) {
21730                for (String host : ivi.getDomains()) {
21731                    result.add(host);
21732                }
21733            }
21734        }
21735        if (filters != null && filters.size() > 0) {
21736            for (IntentFilter filter : filters) {
21737                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21738                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21739                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21740                    result.addAll(filter.getHostsList());
21741                }
21742            }
21743        }
21744
21745        StringBuilder sb = new StringBuilder(result.size() * 16);
21746        for (String domain : result) {
21747            if (sb.length() > 0) sb.append(" ");
21748            sb.append(domain);
21749        }
21750        return sb.toString();
21751    }
21752
21753    // ------- apps on sdcard specific code -------
21754    static final boolean DEBUG_SD_INSTALL = false;
21755
21756    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21757
21758    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21759
21760    private boolean mMediaMounted = false;
21761
21762    static String getEncryptKey() {
21763        try {
21764            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21765                    SD_ENCRYPTION_KEYSTORE_NAME);
21766            if (sdEncKey == null) {
21767                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21768                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21769                if (sdEncKey == null) {
21770                    Slog.e(TAG, "Failed to create encryption keys");
21771                    return null;
21772                }
21773            }
21774            return sdEncKey;
21775        } catch (NoSuchAlgorithmException nsae) {
21776            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21777            return null;
21778        } catch (IOException ioe) {
21779            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21780            return null;
21781        }
21782    }
21783
21784    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21785            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21786        final int size = infos.size();
21787        final String[] packageNames = new String[size];
21788        final int[] packageUids = new int[size];
21789        for (int i = 0; i < size; i++) {
21790            final ApplicationInfo info = infos.get(i);
21791            packageNames[i] = info.packageName;
21792            packageUids[i] = info.uid;
21793        }
21794        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21795                finishedReceiver);
21796    }
21797
21798    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21799            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21800        sendResourcesChangedBroadcast(mediaStatus, replacing,
21801                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21802    }
21803
21804    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21805            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21806        int size = pkgList.length;
21807        if (size > 0) {
21808            // Send broadcasts here
21809            Bundle extras = new Bundle();
21810            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21811            if (uidArr != null) {
21812                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21813            }
21814            if (replacing) {
21815                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21816            }
21817            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21818                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21819            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21820        }
21821    }
21822
21823    private void loadPrivatePackages(final VolumeInfo vol) {
21824        mHandler.post(new Runnable() {
21825            @Override
21826            public void run() {
21827                loadPrivatePackagesInner(vol);
21828            }
21829        });
21830    }
21831
21832    private void loadPrivatePackagesInner(VolumeInfo vol) {
21833        final String volumeUuid = vol.fsUuid;
21834        if (TextUtils.isEmpty(volumeUuid)) {
21835            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21836            return;
21837        }
21838
21839        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21840        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21841        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21842
21843        final VersionInfo ver;
21844        final List<PackageSetting> packages;
21845        synchronized (mPackages) {
21846            ver = mSettings.findOrCreateVersion(volumeUuid);
21847            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21848        }
21849
21850        for (PackageSetting ps : packages) {
21851            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21852            synchronized (mInstallLock) {
21853                final PackageParser.Package pkg;
21854                try {
21855                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21856                    loaded.add(pkg.applicationInfo);
21857
21858                } catch (PackageManagerException e) {
21859                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21860                }
21861
21862                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21863                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21864                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21865                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21866                }
21867            }
21868        }
21869
21870        // Reconcile app data for all started/unlocked users
21871        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21872        final UserManager um = mContext.getSystemService(UserManager.class);
21873        UserManagerInternal umInternal = getUserManagerInternal();
21874        for (UserInfo user : um.getUsers()) {
21875            final int flags;
21876            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21877                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21878            } else if (umInternal.isUserRunning(user.id)) {
21879                flags = StorageManager.FLAG_STORAGE_DE;
21880            } else {
21881                continue;
21882            }
21883
21884            try {
21885                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21886                synchronized (mInstallLock) {
21887                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21888                }
21889            } catch (IllegalStateException e) {
21890                // Device was probably ejected, and we'll process that event momentarily
21891                Slog.w(TAG, "Failed to prepare storage: " + e);
21892            }
21893        }
21894
21895        synchronized (mPackages) {
21896            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21897            if (sdkUpdated) {
21898                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21899                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21900            }
21901            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21902                    mPermissionCallback);
21903
21904            // Yay, everything is now upgraded
21905            ver.forceCurrent();
21906
21907            mSettings.writeLPr();
21908        }
21909
21910        for (PackageFreezer freezer : freezers) {
21911            freezer.close();
21912        }
21913
21914        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21915        sendResourcesChangedBroadcast(true, false, loaded, null);
21916        mLoadedVolumes.add(vol.getId());
21917    }
21918
21919    private void unloadPrivatePackages(final VolumeInfo vol) {
21920        mHandler.post(new Runnable() {
21921            @Override
21922            public void run() {
21923                unloadPrivatePackagesInner(vol);
21924            }
21925        });
21926    }
21927
21928    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21929        final String volumeUuid = vol.fsUuid;
21930        if (TextUtils.isEmpty(volumeUuid)) {
21931            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21932            return;
21933        }
21934
21935        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21936        synchronized (mInstallLock) {
21937        synchronized (mPackages) {
21938            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21939            for (PackageSetting ps : packages) {
21940                if (ps.pkg == null) continue;
21941
21942                final ApplicationInfo info = ps.pkg.applicationInfo;
21943                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21944                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21945
21946                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21947                        "unloadPrivatePackagesInner")) {
21948                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21949                            false, null)) {
21950                        unloaded.add(info);
21951                    } else {
21952                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21953                    }
21954                }
21955
21956                // Try very hard to release any references to this package
21957                // so we don't risk the system server being killed due to
21958                // open FDs
21959                AttributeCache.instance().removePackage(ps.name);
21960            }
21961
21962            mSettings.writeLPr();
21963        }
21964        }
21965
21966        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21967        sendResourcesChangedBroadcast(false, false, unloaded, null);
21968        mLoadedVolumes.remove(vol.getId());
21969
21970        // Try very hard to release any references to this path so we don't risk
21971        // the system server being killed due to open FDs
21972        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21973
21974        for (int i = 0; i < 3; i++) {
21975            System.gc();
21976            System.runFinalization();
21977        }
21978    }
21979
21980    private void assertPackageKnown(String volumeUuid, String packageName)
21981            throws PackageManagerException {
21982        synchronized (mPackages) {
21983            // Normalize package name to handle renamed packages
21984            packageName = normalizePackageNameLPr(packageName);
21985
21986            final PackageSetting ps = mSettings.mPackages.get(packageName);
21987            if (ps == null) {
21988                throw new PackageManagerException("Package " + packageName + " is unknown");
21989            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21990                throw new PackageManagerException(
21991                        "Package " + packageName + " found on unknown volume " + volumeUuid
21992                                + "; expected volume " + ps.volumeUuid);
21993            }
21994        }
21995    }
21996
21997    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21998            throws PackageManagerException {
21999        synchronized (mPackages) {
22000            // Normalize package name to handle renamed packages
22001            packageName = normalizePackageNameLPr(packageName);
22002
22003            final PackageSetting ps = mSettings.mPackages.get(packageName);
22004            if (ps == null) {
22005                throw new PackageManagerException("Package " + packageName + " is unknown");
22006            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22007                throw new PackageManagerException(
22008                        "Package " + packageName + " found on unknown volume " + volumeUuid
22009                                + "; expected volume " + ps.volumeUuid);
22010            } else if (!ps.getInstalled(userId)) {
22011                throw new PackageManagerException(
22012                        "Package " + packageName + " not installed for user " + userId);
22013            }
22014        }
22015    }
22016
22017    private List<String> collectAbsoluteCodePaths() {
22018        synchronized (mPackages) {
22019            List<String> codePaths = new ArrayList<>();
22020            final int packageCount = mSettings.mPackages.size();
22021            for (int i = 0; i < packageCount; i++) {
22022                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22023                codePaths.add(ps.codePath.getAbsolutePath());
22024            }
22025            return codePaths;
22026        }
22027    }
22028
22029    /**
22030     * Examine all apps present on given mounted volume, and destroy apps that
22031     * aren't expected, either due to uninstallation or reinstallation on
22032     * another volume.
22033     */
22034    private void reconcileApps(String volumeUuid) {
22035        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22036        List<File> filesToDelete = null;
22037
22038        final File[] files = FileUtils.listFilesOrEmpty(
22039                Environment.getDataAppDirectory(volumeUuid));
22040        for (File file : files) {
22041            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22042                    && !PackageInstallerService.isStageName(file.getName());
22043            if (!isPackage) {
22044                // Ignore entries which are not packages
22045                continue;
22046            }
22047
22048            String absolutePath = file.getAbsolutePath();
22049
22050            boolean pathValid = false;
22051            final int absoluteCodePathCount = absoluteCodePaths.size();
22052            for (int i = 0; i < absoluteCodePathCount; i++) {
22053                String absoluteCodePath = absoluteCodePaths.get(i);
22054                if (absolutePath.startsWith(absoluteCodePath)) {
22055                    pathValid = true;
22056                    break;
22057                }
22058            }
22059
22060            if (!pathValid) {
22061                if (filesToDelete == null) {
22062                    filesToDelete = new ArrayList<>();
22063                }
22064                filesToDelete.add(file);
22065            }
22066        }
22067
22068        if (filesToDelete != null) {
22069            final int fileToDeleteCount = filesToDelete.size();
22070            for (int i = 0; i < fileToDeleteCount; i++) {
22071                File fileToDelete = filesToDelete.get(i);
22072                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22073                synchronized (mInstallLock) {
22074                    removeCodePathLI(fileToDelete);
22075                }
22076            }
22077        }
22078    }
22079
22080    /**
22081     * Reconcile all app data for the given user.
22082     * <p>
22083     * Verifies that directories exist and that ownership and labeling is
22084     * correct for all installed apps on all mounted volumes.
22085     */
22086    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22087        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22088        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22089            final String volumeUuid = vol.getFsUuid();
22090            synchronized (mInstallLock) {
22091                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22092            }
22093        }
22094    }
22095
22096    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22097            boolean migrateAppData) {
22098        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22099    }
22100
22101    /**
22102     * Reconcile all app data on given mounted volume.
22103     * <p>
22104     * Destroys app data that isn't expected, either due to uninstallation or
22105     * reinstallation on another volume.
22106     * <p>
22107     * Verifies that directories exist and that ownership and labeling is
22108     * correct for all installed apps.
22109     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22110     */
22111    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22112            boolean migrateAppData, boolean onlyCoreApps) {
22113        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22114                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22115        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22116
22117        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22118        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22119
22120        // First look for stale data that doesn't belong, and check if things
22121        // have changed since we did our last restorecon
22122        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22123            if (StorageManager.isFileEncryptedNativeOrEmulated()
22124                    && !StorageManager.isUserKeyUnlocked(userId)) {
22125                throw new RuntimeException(
22126                        "Yikes, someone asked us to reconcile CE storage while " + userId
22127                                + " was still locked; this would have caused massive data loss!");
22128            }
22129
22130            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22131            for (File file : files) {
22132                final String packageName = file.getName();
22133                try {
22134                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22135                } catch (PackageManagerException e) {
22136                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22137                    try {
22138                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22139                                StorageManager.FLAG_STORAGE_CE, 0);
22140                    } catch (InstallerException e2) {
22141                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22142                    }
22143                }
22144            }
22145        }
22146        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22147            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22148            for (File file : files) {
22149                final String packageName = file.getName();
22150                try {
22151                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22152                } catch (PackageManagerException e) {
22153                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22154                    try {
22155                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22156                                StorageManager.FLAG_STORAGE_DE, 0);
22157                    } catch (InstallerException e2) {
22158                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22159                    }
22160                }
22161            }
22162        }
22163
22164        // Ensure that data directories are ready to roll for all packages
22165        // installed for this volume and user
22166        final List<PackageSetting> packages;
22167        synchronized (mPackages) {
22168            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22169        }
22170        int preparedCount = 0;
22171        for (PackageSetting ps : packages) {
22172            final String packageName = ps.name;
22173            if (ps.pkg == null) {
22174                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22175                // TODO: might be due to legacy ASEC apps; we should circle back
22176                // and reconcile again once they're scanned
22177                continue;
22178            }
22179            // Skip non-core apps if requested
22180            if (onlyCoreApps && !ps.pkg.coreApp) {
22181                result.add(packageName);
22182                continue;
22183            }
22184
22185            if (ps.getInstalled(userId)) {
22186                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22187                preparedCount++;
22188            }
22189        }
22190
22191        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22192        return result;
22193    }
22194
22195    /**
22196     * Prepare app data for the given app just after it was installed or
22197     * upgraded. This method carefully only touches users that it's installed
22198     * for, and it forces a restorecon to handle any seinfo changes.
22199     * <p>
22200     * Verifies that directories exist and that ownership and labeling is
22201     * correct for all installed apps. If there is an ownership mismatch, it
22202     * will try recovering system apps by wiping data; third-party app data is
22203     * left intact.
22204     * <p>
22205     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22206     */
22207    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22208        final PackageSetting ps;
22209        synchronized (mPackages) {
22210            ps = mSettings.mPackages.get(pkg.packageName);
22211            mSettings.writeKernelMappingLPr(ps);
22212        }
22213
22214        final UserManager um = mContext.getSystemService(UserManager.class);
22215        UserManagerInternal umInternal = getUserManagerInternal();
22216        for (UserInfo user : um.getUsers()) {
22217            final int flags;
22218            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22219                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22220            } else if (umInternal.isUserRunning(user.id)) {
22221                flags = StorageManager.FLAG_STORAGE_DE;
22222            } else {
22223                continue;
22224            }
22225
22226            if (ps.getInstalled(user.id)) {
22227                // TODO: when user data is locked, mark that we're still dirty
22228                prepareAppDataLIF(pkg, user.id, flags);
22229            }
22230        }
22231    }
22232
22233    /**
22234     * Prepare app data for the given app.
22235     * <p>
22236     * Verifies that directories exist and that ownership and labeling is
22237     * correct for all installed apps. If there is an ownership mismatch, this
22238     * will try recovering system apps by wiping data; third-party app data is
22239     * left intact.
22240     */
22241    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22242        if (pkg == null) {
22243            Slog.wtf(TAG, "Package was null!", new Throwable());
22244            return;
22245        }
22246        prepareAppDataLeafLIF(pkg, userId, flags);
22247        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22248        for (int i = 0; i < childCount; i++) {
22249            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22250        }
22251    }
22252
22253    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22254            boolean maybeMigrateAppData) {
22255        prepareAppDataLIF(pkg, userId, flags);
22256
22257        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22258            // We may have just shuffled around app data directories, so
22259            // prepare them one more time
22260            prepareAppDataLIF(pkg, userId, flags);
22261        }
22262    }
22263
22264    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22265        if (DEBUG_APP_DATA) {
22266            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22267                    + Integer.toHexString(flags));
22268        }
22269
22270        final String volumeUuid = pkg.volumeUuid;
22271        final String packageName = pkg.packageName;
22272        final ApplicationInfo app = pkg.applicationInfo;
22273        final int appId = UserHandle.getAppId(app.uid);
22274
22275        Preconditions.checkNotNull(app.seInfo);
22276
22277        long ceDataInode = -1;
22278        try {
22279            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22280                    appId, app.seInfo, app.targetSdkVersion);
22281        } catch (InstallerException e) {
22282            if (app.isSystemApp()) {
22283                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22284                        + ", but trying to recover: " + e);
22285                destroyAppDataLeafLIF(pkg, userId, flags);
22286                try {
22287                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22288                            appId, app.seInfo, app.targetSdkVersion);
22289                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22290                } catch (InstallerException e2) {
22291                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22292                }
22293            } else {
22294                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22295            }
22296        }
22297        // Prepare the application profiles.
22298        mArtManagerService.prepareAppProfiles(pkg, userId);
22299
22300        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22301            // TODO: mark this structure as dirty so we persist it!
22302            synchronized (mPackages) {
22303                final PackageSetting ps = mSettings.mPackages.get(packageName);
22304                if (ps != null) {
22305                    ps.setCeDataInode(ceDataInode, userId);
22306                }
22307            }
22308        }
22309
22310        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22311    }
22312
22313    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22314        if (pkg == null) {
22315            Slog.wtf(TAG, "Package was null!", new Throwable());
22316            return;
22317        }
22318        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22319        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22320        for (int i = 0; i < childCount; i++) {
22321            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22322        }
22323    }
22324
22325    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22326        final String volumeUuid = pkg.volumeUuid;
22327        final String packageName = pkg.packageName;
22328        final ApplicationInfo app = pkg.applicationInfo;
22329
22330        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22331            // Create a native library symlink only if we have native libraries
22332            // and if the native libraries are 32 bit libraries. We do not provide
22333            // this symlink for 64 bit libraries.
22334            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22335                final String nativeLibPath = app.nativeLibraryDir;
22336                try {
22337                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22338                            nativeLibPath, userId);
22339                } catch (InstallerException e) {
22340                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22341                }
22342            }
22343        }
22344    }
22345
22346    /**
22347     * For system apps on non-FBE devices, this method migrates any existing
22348     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22349     * requested by the app.
22350     */
22351    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22352        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22353                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22354            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22355                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22356            try {
22357                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22358                        storageTarget);
22359            } catch (InstallerException e) {
22360                logCriticalInfo(Log.WARN,
22361                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22362            }
22363            return true;
22364        } else {
22365            return false;
22366        }
22367    }
22368
22369    public PackageFreezer freezePackage(String packageName, String killReason) {
22370        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22371    }
22372
22373    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22374        return new PackageFreezer(packageName, userId, killReason);
22375    }
22376
22377    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22378            String killReason) {
22379        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22380    }
22381
22382    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22383            String killReason) {
22384        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22385            return new PackageFreezer();
22386        } else {
22387            return freezePackage(packageName, userId, killReason);
22388        }
22389    }
22390
22391    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22392            String killReason) {
22393        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22394    }
22395
22396    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22397            String killReason) {
22398        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22399            return new PackageFreezer();
22400        } else {
22401            return freezePackage(packageName, userId, killReason);
22402        }
22403    }
22404
22405    /**
22406     * Class that freezes and kills the given package upon creation, and
22407     * unfreezes it upon closing. This is typically used when doing surgery on
22408     * app code/data to prevent the app from running while you're working.
22409     */
22410    private class PackageFreezer implements AutoCloseable {
22411        private final String mPackageName;
22412        private final PackageFreezer[] mChildren;
22413
22414        private final boolean mWeFroze;
22415
22416        private final AtomicBoolean mClosed = new AtomicBoolean();
22417        private final CloseGuard mCloseGuard = CloseGuard.get();
22418
22419        /**
22420         * Create and return a stub freezer that doesn't actually do anything,
22421         * typically used when someone requested
22422         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22423         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22424         */
22425        public PackageFreezer() {
22426            mPackageName = null;
22427            mChildren = null;
22428            mWeFroze = false;
22429            mCloseGuard.open("close");
22430        }
22431
22432        public PackageFreezer(String packageName, int userId, String killReason) {
22433            synchronized (mPackages) {
22434                mPackageName = packageName;
22435                mWeFroze = mFrozenPackages.add(mPackageName);
22436
22437                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22438                if (ps != null) {
22439                    killApplication(ps.name, ps.appId, userId, killReason);
22440                }
22441
22442                final PackageParser.Package p = mPackages.get(packageName);
22443                if (p != null && p.childPackages != null) {
22444                    final int N = p.childPackages.size();
22445                    mChildren = new PackageFreezer[N];
22446                    for (int i = 0; i < N; i++) {
22447                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22448                                userId, killReason);
22449                    }
22450                } else {
22451                    mChildren = null;
22452                }
22453            }
22454            mCloseGuard.open("close");
22455        }
22456
22457        @Override
22458        protected void finalize() throws Throwable {
22459            try {
22460                if (mCloseGuard != null) {
22461                    mCloseGuard.warnIfOpen();
22462                }
22463
22464                close();
22465            } finally {
22466                super.finalize();
22467            }
22468        }
22469
22470        @Override
22471        public void close() {
22472            mCloseGuard.close();
22473            if (mClosed.compareAndSet(false, true)) {
22474                synchronized (mPackages) {
22475                    if (mWeFroze) {
22476                        mFrozenPackages.remove(mPackageName);
22477                    }
22478
22479                    if (mChildren != null) {
22480                        for (PackageFreezer freezer : mChildren) {
22481                            freezer.close();
22482                        }
22483                    }
22484                }
22485            }
22486        }
22487    }
22488
22489    /**
22490     * Verify that given package is currently frozen.
22491     */
22492    private void checkPackageFrozen(String packageName) {
22493        synchronized (mPackages) {
22494            if (!mFrozenPackages.contains(packageName)) {
22495                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22496            }
22497        }
22498    }
22499
22500    @Override
22501    public int movePackage(final String packageName, final String volumeUuid) {
22502        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22503
22504        final int callingUid = Binder.getCallingUid();
22505        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22506        final int moveId = mNextMoveId.getAndIncrement();
22507        mHandler.post(new Runnable() {
22508            @Override
22509            public void run() {
22510                try {
22511                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22512                } catch (PackageManagerException e) {
22513                    Slog.w(TAG, "Failed to move " + packageName, e);
22514                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22515                }
22516            }
22517        });
22518        return moveId;
22519    }
22520
22521    private void movePackageInternal(final String packageName, final String volumeUuid,
22522            final int moveId, final int callingUid, UserHandle user)
22523                    throws PackageManagerException {
22524        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22525        final PackageManager pm = mContext.getPackageManager();
22526
22527        final boolean currentAsec;
22528        final String currentVolumeUuid;
22529        final File codeFile;
22530        final String installerPackageName;
22531        final String packageAbiOverride;
22532        final int appId;
22533        final String seinfo;
22534        final String label;
22535        final int targetSdkVersion;
22536        final PackageFreezer freezer;
22537        final int[] installedUserIds;
22538
22539        // reader
22540        synchronized (mPackages) {
22541            final PackageParser.Package pkg = mPackages.get(packageName);
22542            final PackageSetting ps = mSettings.mPackages.get(packageName);
22543            if (pkg == null
22544                    || ps == null
22545                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22546                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22547            }
22548            if (pkg.applicationInfo.isSystemApp()) {
22549                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22550                        "Cannot move system application");
22551            }
22552
22553            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22554            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22555                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22556            if (isInternalStorage && !allow3rdPartyOnInternal) {
22557                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22558                        "3rd party apps are not allowed on internal storage");
22559            }
22560
22561            if (pkg.applicationInfo.isExternalAsec()) {
22562                currentAsec = true;
22563                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22564            } else if (pkg.applicationInfo.isForwardLocked()) {
22565                currentAsec = true;
22566                currentVolumeUuid = "forward_locked";
22567            } else {
22568                currentAsec = false;
22569                currentVolumeUuid = ps.volumeUuid;
22570
22571                final File probe = new File(pkg.codePath);
22572                final File probeOat = new File(probe, "oat");
22573                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22574                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22575                            "Move only supported for modern cluster style installs");
22576                }
22577            }
22578
22579            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22580                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22581                        "Package already moved to " + volumeUuid);
22582            }
22583            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22584                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22585                        "Device admin cannot be moved");
22586            }
22587
22588            if (mFrozenPackages.contains(packageName)) {
22589                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22590                        "Failed to move already frozen package");
22591            }
22592
22593            codeFile = new File(pkg.codePath);
22594            installerPackageName = ps.installerPackageName;
22595            packageAbiOverride = ps.cpuAbiOverrideString;
22596            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22597            seinfo = pkg.applicationInfo.seInfo;
22598            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22599            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22600            freezer = freezePackage(packageName, "movePackageInternal");
22601            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22602        }
22603
22604        final Bundle extras = new Bundle();
22605        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22606        extras.putString(Intent.EXTRA_TITLE, label);
22607        mMoveCallbacks.notifyCreated(moveId, extras);
22608
22609        int installFlags;
22610        final boolean moveCompleteApp;
22611        final File measurePath;
22612
22613        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22614            installFlags = INSTALL_INTERNAL;
22615            moveCompleteApp = !currentAsec;
22616            measurePath = Environment.getDataAppDirectory(volumeUuid);
22617        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22618            installFlags = INSTALL_EXTERNAL;
22619            moveCompleteApp = false;
22620            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22621        } else {
22622            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22623            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22624                    || !volume.isMountedWritable()) {
22625                freezer.close();
22626                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22627                        "Move location not mounted private volume");
22628            }
22629
22630            Preconditions.checkState(!currentAsec);
22631
22632            installFlags = INSTALL_INTERNAL;
22633            moveCompleteApp = true;
22634            measurePath = Environment.getDataAppDirectory(volumeUuid);
22635        }
22636
22637        // If we're moving app data around, we need all the users unlocked
22638        if (moveCompleteApp) {
22639            for (int userId : installedUserIds) {
22640                if (StorageManager.isFileEncryptedNativeOrEmulated()
22641                        && !StorageManager.isUserKeyUnlocked(userId)) {
22642                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22643                            "User " + userId + " must be unlocked");
22644                }
22645            }
22646        }
22647
22648        final PackageStats stats = new PackageStats(null, -1);
22649        synchronized (mInstaller) {
22650            for (int userId : installedUserIds) {
22651                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22652                    freezer.close();
22653                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22654                            "Failed to measure package size");
22655                }
22656            }
22657        }
22658
22659        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22660                + stats.dataSize);
22661
22662        final long startFreeBytes = measurePath.getUsableSpace();
22663        final long sizeBytes;
22664        if (moveCompleteApp) {
22665            sizeBytes = stats.codeSize + stats.dataSize;
22666        } else {
22667            sizeBytes = stats.codeSize;
22668        }
22669
22670        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22671            freezer.close();
22672            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22673                    "Not enough free space to move");
22674        }
22675
22676        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22677
22678        final CountDownLatch installedLatch = new CountDownLatch(1);
22679        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22680            @Override
22681            public void onUserActionRequired(Intent intent) throws RemoteException {
22682                throw new IllegalStateException();
22683            }
22684
22685            @Override
22686            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22687                    Bundle extras) throws RemoteException {
22688                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22689                        + PackageManager.installStatusToString(returnCode, msg));
22690
22691                installedLatch.countDown();
22692                freezer.close();
22693
22694                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22695                switch (status) {
22696                    case PackageInstaller.STATUS_SUCCESS:
22697                        mMoveCallbacks.notifyStatusChanged(moveId,
22698                                PackageManager.MOVE_SUCCEEDED);
22699                        break;
22700                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22701                        mMoveCallbacks.notifyStatusChanged(moveId,
22702                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22703                        break;
22704                    default:
22705                        mMoveCallbacks.notifyStatusChanged(moveId,
22706                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22707                        break;
22708                }
22709            }
22710        };
22711
22712        final MoveInfo move;
22713        if (moveCompleteApp) {
22714            // Kick off a thread to report progress estimates
22715            new Thread() {
22716                @Override
22717                public void run() {
22718                    while (true) {
22719                        try {
22720                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22721                                break;
22722                            }
22723                        } catch (InterruptedException ignored) {
22724                        }
22725
22726                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22727                        final int progress = 10 + (int) MathUtils.constrain(
22728                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22729                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22730                    }
22731                }
22732            }.start();
22733
22734            final String dataAppName = codeFile.getName();
22735            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22736                    dataAppName, appId, seinfo, targetSdkVersion);
22737        } else {
22738            move = null;
22739        }
22740
22741        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22742
22743        final Message msg = mHandler.obtainMessage(INIT_COPY);
22744        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22745        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22746                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22747                packageAbiOverride, null /*grantedPermissions*/,
22748                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22749        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22750        msg.obj = params;
22751
22752        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22753                System.identityHashCode(msg.obj));
22754        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22755                System.identityHashCode(msg.obj));
22756
22757        mHandler.sendMessage(msg);
22758    }
22759
22760    @Override
22761    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22762        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22763
22764        final int realMoveId = mNextMoveId.getAndIncrement();
22765        final Bundle extras = new Bundle();
22766        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22767        mMoveCallbacks.notifyCreated(realMoveId, extras);
22768
22769        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22770            @Override
22771            public void onCreated(int moveId, Bundle extras) {
22772                // Ignored
22773            }
22774
22775            @Override
22776            public void onStatusChanged(int moveId, int status, long estMillis) {
22777                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22778            }
22779        };
22780
22781        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22782        storage.setPrimaryStorageUuid(volumeUuid, callback);
22783        return realMoveId;
22784    }
22785
22786    @Override
22787    public int getMoveStatus(int moveId) {
22788        mContext.enforceCallingOrSelfPermission(
22789                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22790        return mMoveCallbacks.mLastStatus.get(moveId);
22791    }
22792
22793    @Override
22794    public void registerMoveCallback(IPackageMoveObserver callback) {
22795        mContext.enforceCallingOrSelfPermission(
22796                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22797        mMoveCallbacks.register(callback);
22798    }
22799
22800    @Override
22801    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22802        mContext.enforceCallingOrSelfPermission(
22803                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22804        mMoveCallbacks.unregister(callback);
22805    }
22806
22807    @Override
22808    public boolean setInstallLocation(int loc) {
22809        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22810                null);
22811        if (getInstallLocation() == loc) {
22812            return true;
22813        }
22814        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22815                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22816            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22817                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22818            return true;
22819        }
22820        return false;
22821   }
22822
22823    @Override
22824    public int getInstallLocation() {
22825        // allow instant app access
22826        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22827                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22828                PackageHelper.APP_INSTALL_AUTO);
22829    }
22830
22831    /** Called by UserManagerService */
22832    void cleanUpUser(UserManagerService userManager, int userHandle) {
22833        synchronized (mPackages) {
22834            mDirtyUsers.remove(userHandle);
22835            mUserNeedsBadging.delete(userHandle);
22836            mSettings.removeUserLPw(userHandle);
22837            mPendingBroadcasts.remove(userHandle);
22838            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22839            removeUnusedPackagesLPw(userManager, userHandle);
22840        }
22841    }
22842
22843    /**
22844     * We're removing userHandle and would like to remove any downloaded packages
22845     * that are no longer in use by any other user.
22846     * @param userHandle the user being removed
22847     */
22848    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22849        final boolean DEBUG_CLEAN_APKS = false;
22850        int [] users = userManager.getUserIds();
22851        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22852        while (psit.hasNext()) {
22853            PackageSetting ps = psit.next();
22854            if (ps.pkg == null) {
22855                continue;
22856            }
22857            final String packageName = ps.pkg.packageName;
22858            // Skip over if system app
22859            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22860                continue;
22861            }
22862            if (DEBUG_CLEAN_APKS) {
22863                Slog.i(TAG, "Checking package " + packageName);
22864            }
22865            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22866            if (keep) {
22867                if (DEBUG_CLEAN_APKS) {
22868                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22869                }
22870            } else {
22871                for (int i = 0; i < users.length; i++) {
22872                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22873                        keep = true;
22874                        if (DEBUG_CLEAN_APKS) {
22875                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22876                                    + users[i]);
22877                        }
22878                        break;
22879                    }
22880                }
22881            }
22882            if (!keep) {
22883                if (DEBUG_CLEAN_APKS) {
22884                    Slog.i(TAG, "  Removing package " + packageName);
22885                }
22886                mHandler.post(new Runnable() {
22887                    public void run() {
22888                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22889                                userHandle, 0);
22890                    } //end run
22891                });
22892            }
22893        }
22894    }
22895
22896    /** Called by UserManagerService */
22897    void createNewUser(int userId, String[] disallowedPackages) {
22898        synchronized (mInstallLock) {
22899            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22900        }
22901        synchronized (mPackages) {
22902            scheduleWritePackageRestrictionsLocked(userId);
22903            scheduleWritePackageListLocked(userId);
22904            applyFactoryDefaultBrowserLPw(userId);
22905            primeDomainVerificationsLPw(userId);
22906        }
22907    }
22908
22909    void onNewUserCreated(final int userId) {
22910        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22911        synchronized(mPackages) {
22912            // If permission review for legacy apps is required, we represent
22913            // dagerous permissions for such apps as always granted runtime
22914            // permissions to keep per user flag state whether review is needed.
22915            // Hence, if a new user is added we have to propagate dangerous
22916            // permission grants for these legacy apps.
22917            if (mSettings.mPermissions.mPermissionReviewRequired) {
22918// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22919                mPermissionManager.updateAllPermissions(
22920                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22921                        mPermissionCallback);
22922            }
22923        }
22924    }
22925
22926    @Override
22927    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22928        mContext.enforceCallingOrSelfPermission(
22929                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22930                "Only package verification agents can read the verifier device identity");
22931
22932        synchronized (mPackages) {
22933            return mSettings.getVerifierDeviceIdentityLPw();
22934        }
22935    }
22936
22937    @Override
22938    public void setPermissionEnforced(String permission, boolean enforced) {
22939        // TODO: Now that we no longer change GID for storage, this should to away.
22940        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22941                "setPermissionEnforced");
22942        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22943            synchronized (mPackages) {
22944                if (mSettings.mReadExternalStorageEnforced == null
22945                        || mSettings.mReadExternalStorageEnforced != enforced) {
22946                    mSettings.mReadExternalStorageEnforced =
22947                            enforced ? Boolean.TRUE : Boolean.FALSE;
22948                    mSettings.writeLPr();
22949                }
22950            }
22951            // kill any non-foreground processes so we restart them and
22952            // grant/revoke the GID.
22953            final IActivityManager am = ActivityManager.getService();
22954            if (am != null) {
22955                final long token = Binder.clearCallingIdentity();
22956                try {
22957                    am.killProcessesBelowForeground("setPermissionEnforcement");
22958                } catch (RemoteException e) {
22959                } finally {
22960                    Binder.restoreCallingIdentity(token);
22961                }
22962            }
22963        } else {
22964            throw new IllegalArgumentException("No selective enforcement for " + permission);
22965        }
22966    }
22967
22968    @Override
22969    @Deprecated
22970    public boolean isPermissionEnforced(String permission) {
22971        // allow instant applications
22972        return true;
22973    }
22974
22975    @Override
22976    public boolean isStorageLow() {
22977        // allow instant applications
22978        final long token = Binder.clearCallingIdentity();
22979        try {
22980            final DeviceStorageMonitorInternal
22981                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22982            if (dsm != null) {
22983                return dsm.isMemoryLow();
22984            } else {
22985                return false;
22986            }
22987        } finally {
22988            Binder.restoreCallingIdentity(token);
22989        }
22990    }
22991
22992    @Override
22993    public IPackageInstaller getPackageInstaller() {
22994        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22995            return null;
22996        }
22997        return mInstallerService;
22998    }
22999
23000    @Override
23001    public IArtManager getArtManager() {
23002        return mArtManagerService;
23003    }
23004
23005    private boolean userNeedsBadging(int userId) {
23006        int index = mUserNeedsBadging.indexOfKey(userId);
23007        if (index < 0) {
23008            final UserInfo userInfo;
23009            final long token = Binder.clearCallingIdentity();
23010            try {
23011                userInfo = sUserManager.getUserInfo(userId);
23012            } finally {
23013                Binder.restoreCallingIdentity(token);
23014            }
23015            final boolean b;
23016            if (userInfo != null && userInfo.isManagedProfile()) {
23017                b = true;
23018            } else {
23019                b = false;
23020            }
23021            mUserNeedsBadging.put(userId, b);
23022            return b;
23023        }
23024        return mUserNeedsBadging.valueAt(index);
23025    }
23026
23027    @Override
23028    public KeySet getKeySetByAlias(String packageName, String alias) {
23029        if (packageName == null || alias == null) {
23030            return null;
23031        }
23032        synchronized(mPackages) {
23033            final PackageParser.Package pkg = mPackages.get(packageName);
23034            if (pkg == null) {
23035                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23036                throw new IllegalArgumentException("Unknown package: " + packageName);
23037            }
23038            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23039            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23040                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23041                throw new IllegalArgumentException("Unknown package: " + packageName);
23042            }
23043            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23044            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23045        }
23046    }
23047
23048    @Override
23049    public KeySet getSigningKeySet(String packageName) {
23050        if (packageName == null) {
23051            return null;
23052        }
23053        synchronized(mPackages) {
23054            final int callingUid = Binder.getCallingUid();
23055            final int callingUserId = UserHandle.getUserId(callingUid);
23056            final PackageParser.Package pkg = mPackages.get(packageName);
23057            if (pkg == null) {
23058                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23059                throw new IllegalArgumentException("Unknown package: " + packageName);
23060            }
23061            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23062            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23063                // filter and pretend the package doesn't exist
23064                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23065                        + ", uid:" + callingUid);
23066                throw new IllegalArgumentException("Unknown package: " + packageName);
23067            }
23068            if (pkg.applicationInfo.uid != callingUid
23069                    && Process.SYSTEM_UID != callingUid) {
23070                throw new SecurityException("May not access signing KeySet of other apps.");
23071            }
23072            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23073            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23074        }
23075    }
23076
23077    @Override
23078    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23079        final int callingUid = Binder.getCallingUid();
23080        if (getInstantAppPackageName(callingUid) != null) {
23081            return false;
23082        }
23083        if (packageName == null || ks == null) {
23084            return false;
23085        }
23086        synchronized(mPackages) {
23087            final PackageParser.Package pkg = mPackages.get(packageName);
23088            if (pkg == null
23089                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23090                            UserHandle.getUserId(callingUid))) {
23091                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23092                throw new IllegalArgumentException("Unknown package: " + packageName);
23093            }
23094            IBinder ksh = ks.getToken();
23095            if (ksh instanceof KeySetHandle) {
23096                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23097                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23098            }
23099            return false;
23100        }
23101    }
23102
23103    @Override
23104    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23105        final int callingUid = Binder.getCallingUid();
23106        if (getInstantAppPackageName(callingUid) != null) {
23107            return false;
23108        }
23109        if (packageName == null || ks == null) {
23110            return false;
23111        }
23112        synchronized(mPackages) {
23113            final PackageParser.Package pkg = mPackages.get(packageName);
23114            if (pkg == null
23115                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23116                            UserHandle.getUserId(callingUid))) {
23117                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23118                throw new IllegalArgumentException("Unknown package: " + packageName);
23119            }
23120            IBinder ksh = ks.getToken();
23121            if (ksh instanceof KeySetHandle) {
23122                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23123                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23124            }
23125            return false;
23126        }
23127    }
23128
23129    private void deletePackageIfUnusedLPr(final String packageName) {
23130        PackageSetting ps = mSettings.mPackages.get(packageName);
23131        if (ps == null) {
23132            return;
23133        }
23134        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23135            // TODO Implement atomic delete if package is unused
23136            // It is currently possible that the package will be deleted even if it is installed
23137            // after this method returns.
23138            mHandler.post(new Runnable() {
23139                public void run() {
23140                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23141                            0, PackageManager.DELETE_ALL_USERS);
23142                }
23143            });
23144        }
23145    }
23146
23147    /**
23148     * Check and throw if the given before/after packages would be considered a
23149     * downgrade.
23150     */
23151    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23152            throws PackageManagerException {
23153        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23154            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23155                    "Update version code " + after.versionCode + " is older than current "
23156                    + before.getLongVersionCode());
23157        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23158            if (after.baseRevisionCode < before.baseRevisionCode) {
23159                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23160                        "Update base revision code " + after.baseRevisionCode
23161                        + " is older than current " + before.baseRevisionCode);
23162            }
23163
23164            if (!ArrayUtils.isEmpty(after.splitNames)) {
23165                for (int i = 0; i < after.splitNames.length; i++) {
23166                    final String splitName = after.splitNames[i];
23167                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23168                    if (j != -1) {
23169                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23170                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23171                                    "Update split " + splitName + " revision code "
23172                                    + after.splitRevisionCodes[i] + " is older than current "
23173                                    + before.splitRevisionCodes[j]);
23174                        }
23175                    }
23176                }
23177            }
23178        }
23179    }
23180
23181    private static class MoveCallbacks extends Handler {
23182        private static final int MSG_CREATED = 1;
23183        private static final int MSG_STATUS_CHANGED = 2;
23184
23185        private final RemoteCallbackList<IPackageMoveObserver>
23186                mCallbacks = new RemoteCallbackList<>();
23187
23188        private final SparseIntArray mLastStatus = new SparseIntArray();
23189
23190        public MoveCallbacks(Looper looper) {
23191            super(looper);
23192        }
23193
23194        public void register(IPackageMoveObserver callback) {
23195            mCallbacks.register(callback);
23196        }
23197
23198        public void unregister(IPackageMoveObserver callback) {
23199            mCallbacks.unregister(callback);
23200        }
23201
23202        @Override
23203        public void handleMessage(Message msg) {
23204            final SomeArgs args = (SomeArgs) msg.obj;
23205            final int n = mCallbacks.beginBroadcast();
23206            for (int i = 0; i < n; i++) {
23207                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23208                try {
23209                    invokeCallback(callback, msg.what, args);
23210                } catch (RemoteException ignored) {
23211                }
23212            }
23213            mCallbacks.finishBroadcast();
23214            args.recycle();
23215        }
23216
23217        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23218                throws RemoteException {
23219            switch (what) {
23220                case MSG_CREATED: {
23221                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23222                    break;
23223                }
23224                case MSG_STATUS_CHANGED: {
23225                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23226                    break;
23227                }
23228            }
23229        }
23230
23231        private void notifyCreated(int moveId, Bundle extras) {
23232            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23233
23234            final SomeArgs args = SomeArgs.obtain();
23235            args.argi1 = moveId;
23236            args.arg2 = extras;
23237            obtainMessage(MSG_CREATED, args).sendToTarget();
23238        }
23239
23240        private void notifyStatusChanged(int moveId, int status) {
23241            notifyStatusChanged(moveId, status, -1);
23242        }
23243
23244        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23245            Slog.v(TAG, "Move " + moveId + " status " + status);
23246
23247            final SomeArgs args = SomeArgs.obtain();
23248            args.argi1 = moveId;
23249            args.argi2 = status;
23250            args.arg3 = estMillis;
23251            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23252
23253            synchronized (mLastStatus) {
23254                mLastStatus.put(moveId, status);
23255            }
23256        }
23257    }
23258
23259    private final static class OnPermissionChangeListeners extends Handler {
23260        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23261
23262        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23263                new RemoteCallbackList<>();
23264
23265        public OnPermissionChangeListeners(Looper looper) {
23266            super(looper);
23267        }
23268
23269        @Override
23270        public void handleMessage(Message msg) {
23271            switch (msg.what) {
23272                case MSG_ON_PERMISSIONS_CHANGED: {
23273                    final int uid = msg.arg1;
23274                    handleOnPermissionsChanged(uid);
23275                } break;
23276            }
23277        }
23278
23279        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23280            mPermissionListeners.register(listener);
23281
23282        }
23283
23284        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23285            mPermissionListeners.unregister(listener);
23286        }
23287
23288        public void onPermissionsChanged(int uid) {
23289            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23290                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23291            }
23292        }
23293
23294        private void handleOnPermissionsChanged(int uid) {
23295            final int count = mPermissionListeners.beginBroadcast();
23296            try {
23297                for (int i = 0; i < count; i++) {
23298                    IOnPermissionsChangeListener callback = mPermissionListeners
23299                            .getBroadcastItem(i);
23300                    try {
23301                        callback.onPermissionsChanged(uid);
23302                    } catch (RemoteException e) {
23303                        Log.e(TAG, "Permission listener is dead", e);
23304                    }
23305                }
23306            } finally {
23307                mPermissionListeners.finishBroadcast();
23308            }
23309        }
23310    }
23311
23312    private class PackageManagerNative extends IPackageManagerNative.Stub {
23313        @Override
23314        public String[] getNamesForUids(int[] uids) throws RemoteException {
23315            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23316            // massage results so they can be parsed by the native binder
23317            for (int i = results.length - 1; i >= 0; --i) {
23318                if (results[i] == null) {
23319                    results[i] = "";
23320                }
23321            }
23322            return results;
23323        }
23324
23325        // NB: this differentiates between preloads and sideloads
23326        @Override
23327        public String getInstallerForPackage(String packageName) throws RemoteException {
23328            final String installerName = getInstallerPackageName(packageName);
23329            if (!TextUtils.isEmpty(installerName)) {
23330                return installerName;
23331            }
23332            // differentiate between preload and sideload
23333            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23334            ApplicationInfo appInfo = getApplicationInfo(packageName,
23335                                    /*flags*/ 0,
23336                                    /*userId*/ callingUser);
23337            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23338                return "preload";
23339            }
23340            return "";
23341        }
23342
23343        @Override
23344        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23345            try {
23346                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23347                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23348                if (pInfo != null) {
23349                    return pInfo.getLongVersionCode();
23350                }
23351            } catch (Exception e) {
23352            }
23353            return 0;
23354        }
23355    }
23356
23357    private class PackageManagerInternalImpl extends PackageManagerInternal {
23358        @Override
23359        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23360                int flagValues, int userId) {
23361            PackageManagerService.this.updatePermissionFlags(
23362                    permName, packageName, flagMask, flagValues, userId);
23363        }
23364
23365        @Override
23366        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23367            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23368        }
23369
23370        @Override
23371        public boolean isInstantApp(String packageName, int userId) {
23372            return PackageManagerService.this.isInstantApp(packageName, userId);
23373        }
23374
23375        @Override
23376        public String getInstantAppPackageName(int uid) {
23377            return PackageManagerService.this.getInstantAppPackageName(uid);
23378        }
23379
23380        @Override
23381        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23382            synchronized (mPackages) {
23383                return PackageManagerService.this.filterAppAccessLPr(
23384                        (PackageSetting) pkg.mExtras, callingUid, userId);
23385            }
23386        }
23387
23388        @Override
23389        public PackageParser.Package getPackage(String packageName) {
23390            synchronized (mPackages) {
23391                packageName = resolveInternalPackageNameLPr(
23392                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23393                return mPackages.get(packageName);
23394            }
23395        }
23396
23397        @Override
23398        public PackageList getPackageList(PackageListObserver observer) {
23399            synchronized (mPackages) {
23400                final int N = mPackages.size();
23401                final ArrayList<String> list = new ArrayList<>(N);
23402                for (int i = 0; i < N; i++) {
23403                    list.add(mPackages.keyAt(i));
23404                }
23405                final PackageList packageList = new PackageList(list, observer);
23406                if (observer != null) {
23407                    mPackageListObservers.add(packageList);
23408                }
23409                return packageList;
23410            }
23411        }
23412
23413        @Override
23414        public void removePackageListObserver(PackageListObserver observer) {
23415            synchronized (mPackages) {
23416                mPackageListObservers.remove(observer);
23417            }
23418        }
23419
23420        @Override
23421        public PackageParser.Package getDisabledPackage(String packageName) {
23422            synchronized (mPackages) {
23423                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23424                return (ps != null) ? ps.pkg : null;
23425            }
23426        }
23427
23428        @Override
23429        public String getKnownPackageName(int knownPackage, int userId) {
23430            switch(knownPackage) {
23431                case PackageManagerInternal.PACKAGE_BROWSER:
23432                    return getDefaultBrowserPackageName(userId);
23433                case PackageManagerInternal.PACKAGE_INSTALLER:
23434                    return mRequiredInstallerPackage;
23435                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23436                    return mSetupWizardPackage;
23437                case PackageManagerInternal.PACKAGE_SYSTEM:
23438                    return "android";
23439                case PackageManagerInternal.PACKAGE_VERIFIER:
23440                    return mRequiredVerifierPackage;
23441            }
23442            return null;
23443        }
23444
23445        @Override
23446        public boolean isResolveActivityComponent(ComponentInfo component) {
23447            return mResolveActivity.packageName.equals(component.packageName)
23448                    && mResolveActivity.name.equals(component.name);
23449        }
23450
23451        @Override
23452        public void setLocationPackagesProvider(PackagesProvider provider) {
23453            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23454        }
23455
23456        @Override
23457        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23458            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23459        }
23460
23461        @Override
23462        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23463            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23464        }
23465
23466        @Override
23467        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23468            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23469        }
23470
23471        @Override
23472        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23473            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23474        }
23475
23476        @Override
23477        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23478            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23479        }
23480
23481        @Override
23482        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23483            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23484        }
23485
23486        @Override
23487        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23488            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23489        }
23490
23491        @Override
23492        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23493            synchronized (mPackages) {
23494                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23495            }
23496            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23497        }
23498
23499        @Override
23500        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23501            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23502                    packageName, userId);
23503        }
23504
23505        @Override
23506        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23507            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23508                    packageName, userId);
23509        }
23510
23511        @Override
23512        public void setKeepUninstalledPackages(final List<String> packageList) {
23513            Preconditions.checkNotNull(packageList);
23514            List<String> removedFromList = null;
23515            synchronized (mPackages) {
23516                if (mKeepUninstalledPackages != null) {
23517                    final int packagesCount = mKeepUninstalledPackages.size();
23518                    for (int i = 0; i < packagesCount; i++) {
23519                        String oldPackage = mKeepUninstalledPackages.get(i);
23520                        if (packageList != null && packageList.contains(oldPackage)) {
23521                            continue;
23522                        }
23523                        if (removedFromList == null) {
23524                            removedFromList = new ArrayList<>();
23525                        }
23526                        removedFromList.add(oldPackage);
23527                    }
23528                }
23529                mKeepUninstalledPackages = new ArrayList<>(packageList);
23530                if (removedFromList != null) {
23531                    final int removedCount = removedFromList.size();
23532                    for (int i = 0; i < removedCount; i++) {
23533                        deletePackageIfUnusedLPr(removedFromList.get(i));
23534                    }
23535                }
23536            }
23537        }
23538
23539        @Override
23540        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23541            synchronized (mPackages) {
23542                return mPermissionManager.isPermissionsReviewRequired(
23543                        mPackages.get(packageName), userId);
23544            }
23545        }
23546
23547        @Override
23548        public PackageInfo getPackageInfo(
23549                String packageName, int flags, int filterCallingUid, int userId) {
23550            return PackageManagerService.this
23551                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23552                            flags, filterCallingUid, userId);
23553        }
23554
23555        @Override
23556        public int getPackageUid(String packageName, int flags, int userId) {
23557            return PackageManagerService.this
23558                    .getPackageUid(packageName, flags, userId);
23559        }
23560
23561        @Override
23562        public ApplicationInfo getApplicationInfo(
23563                String packageName, int flags, int filterCallingUid, int userId) {
23564            return PackageManagerService.this
23565                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23566        }
23567
23568        @Override
23569        public ActivityInfo getActivityInfo(
23570                ComponentName component, int flags, int filterCallingUid, int userId) {
23571            return PackageManagerService.this
23572                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23573        }
23574
23575        @Override
23576        public List<ResolveInfo> queryIntentActivities(
23577                Intent intent, int flags, int filterCallingUid, int userId) {
23578            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23579            return PackageManagerService.this
23580                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23581                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23582        }
23583
23584        @Override
23585        public List<ResolveInfo> queryIntentServices(
23586                Intent intent, int flags, int callingUid, int userId) {
23587            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23588            return PackageManagerService.this
23589                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23590                            false);
23591        }
23592
23593        @Override
23594        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23595                int userId) {
23596            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23597        }
23598
23599        @Override
23600        public void setDeviceAndProfileOwnerPackages(
23601                int deviceOwnerUserId, String deviceOwnerPackage,
23602                SparseArray<String> profileOwnerPackages) {
23603            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23604                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23605        }
23606
23607        @Override
23608        public boolean isPackageDataProtected(int userId, String packageName) {
23609            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23610        }
23611
23612        @Override
23613        public boolean isPackageEphemeral(int userId, String packageName) {
23614            synchronized (mPackages) {
23615                final PackageSetting ps = mSettings.mPackages.get(packageName);
23616                return ps != null ? ps.getInstantApp(userId) : false;
23617            }
23618        }
23619
23620        @Override
23621        public boolean wasPackageEverLaunched(String packageName, int userId) {
23622            synchronized (mPackages) {
23623                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23624            }
23625        }
23626
23627        @Override
23628        public void grantRuntimePermission(String packageName, String permName, int userId,
23629                boolean overridePolicy) {
23630            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23631                    permName, packageName, overridePolicy, getCallingUid(), userId,
23632                    mPermissionCallback);
23633        }
23634
23635        @Override
23636        public void revokeRuntimePermission(String packageName, String permName, int userId,
23637                boolean overridePolicy) {
23638            mPermissionManager.revokeRuntimePermission(
23639                    permName, packageName, overridePolicy, getCallingUid(), userId,
23640                    mPermissionCallback);
23641        }
23642
23643        @Override
23644        public String getNameForUid(int uid) {
23645            return PackageManagerService.this.getNameForUid(uid);
23646        }
23647
23648        @Override
23649        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23650                Intent origIntent, String resolvedType, String callingPackage,
23651                Bundle verificationBundle, int userId) {
23652            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23653                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23654                    userId);
23655        }
23656
23657        @Override
23658        public void grantEphemeralAccess(int userId, Intent intent,
23659                int targetAppId, int ephemeralAppId) {
23660            synchronized (mPackages) {
23661                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23662                        targetAppId, ephemeralAppId);
23663            }
23664        }
23665
23666        @Override
23667        public boolean isInstantAppInstallerComponent(ComponentName component) {
23668            synchronized (mPackages) {
23669                return mInstantAppInstallerActivity != null
23670                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23671            }
23672        }
23673
23674        @Override
23675        public void pruneInstantApps() {
23676            mInstantAppRegistry.pruneInstantApps();
23677        }
23678
23679        @Override
23680        public String getSetupWizardPackageName() {
23681            return mSetupWizardPackage;
23682        }
23683
23684        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23685            if (policy != null) {
23686                mExternalSourcesPolicy = policy;
23687            }
23688        }
23689
23690        @Override
23691        public boolean isPackagePersistent(String packageName) {
23692            synchronized (mPackages) {
23693                PackageParser.Package pkg = mPackages.get(packageName);
23694                return pkg != null
23695                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23696                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23697                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23698                        : false;
23699            }
23700        }
23701
23702        @Override
23703        public boolean isLegacySystemApp(Package pkg) {
23704            synchronized (mPackages) {
23705                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23706                return mPromoteSystemApps
23707                        && ps.isSystem()
23708                        && mExistingSystemPackages.contains(ps.name);
23709            }
23710        }
23711
23712        @Override
23713        public List<PackageInfo> getOverlayPackages(int userId) {
23714            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23715            synchronized (mPackages) {
23716                for (PackageParser.Package p : mPackages.values()) {
23717                    if (p.mOverlayTarget != null) {
23718                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23719                        if (pkg != null) {
23720                            overlayPackages.add(pkg);
23721                        }
23722                    }
23723                }
23724            }
23725            return overlayPackages;
23726        }
23727
23728        @Override
23729        public List<String> getTargetPackageNames(int userId) {
23730            List<String> targetPackages = new ArrayList<>();
23731            synchronized (mPackages) {
23732                for (PackageParser.Package p : mPackages.values()) {
23733                    if (p.mOverlayTarget == null) {
23734                        targetPackages.add(p.packageName);
23735                    }
23736                }
23737            }
23738            return targetPackages;
23739        }
23740
23741        @Override
23742        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23743                @Nullable List<String> overlayPackageNames) {
23744            synchronized (mPackages) {
23745                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23746                    Slog.e(TAG, "failed to find package " + targetPackageName);
23747                    return false;
23748                }
23749                ArrayList<String> overlayPaths = null;
23750                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23751                    final int N = overlayPackageNames.size();
23752                    overlayPaths = new ArrayList<>(N);
23753                    for (int i = 0; i < N; i++) {
23754                        final String packageName = overlayPackageNames.get(i);
23755                        final PackageParser.Package pkg = mPackages.get(packageName);
23756                        if (pkg == null) {
23757                            Slog.e(TAG, "failed to find package " + packageName);
23758                            return false;
23759                        }
23760                        overlayPaths.add(pkg.baseCodePath);
23761                    }
23762                }
23763
23764                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23765                ps.setOverlayPaths(overlayPaths, userId);
23766                return true;
23767            }
23768        }
23769
23770        @Override
23771        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23772                int flags, int userId, boolean resolveForStart) {
23773            return resolveIntentInternal(
23774                    intent, resolvedType, flags, userId, resolveForStart);
23775        }
23776
23777        @Override
23778        public ResolveInfo resolveService(Intent intent, String resolvedType,
23779                int flags, int userId, int callingUid) {
23780            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23781        }
23782
23783        @Override
23784        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23785            return PackageManagerService.this.resolveContentProviderInternal(
23786                    name, flags, userId);
23787        }
23788
23789        @Override
23790        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23791            synchronized (mPackages) {
23792                mIsolatedOwners.put(isolatedUid, ownerUid);
23793            }
23794        }
23795
23796        @Override
23797        public void removeIsolatedUid(int isolatedUid) {
23798            synchronized (mPackages) {
23799                mIsolatedOwners.delete(isolatedUid);
23800            }
23801        }
23802
23803        @Override
23804        public int getUidTargetSdkVersion(int uid) {
23805            synchronized (mPackages) {
23806                return getUidTargetSdkVersionLockedLPr(uid);
23807            }
23808        }
23809
23810        @Override
23811        public int getPackageTargetSdkVersion(String packageName) {
23812            synchronized (mPackages) {
23813                return getPackageTargetSdkVersionLockedLPr(packageName);
23814            }
23815        }
23816
23817        @Override
23818        public boolean canAccessInstantApps(int callingUid, int userId) {
23819            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23820        }
23821
23822        @Override
23823        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23824            synchronized (mPackages) {
23825                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23826            }
23827        }
23828
23829        @Override
23830        public void notifyPackageUse(String packageName, int reason) {
23831            synchronized (mPackages) {
23832                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23833            }
23834        }
23835    }
23836
23837    @Override
23838    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23839        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23840        synchronized (mPackages) {
23841            final long identity = Binder.clearCallingIdentity();
23842            try {
23843                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23844                        packageNames, userId);
23845            } finally {
23846                Binder.restoreCallingIdentity(identity);
23847            }
23848        }
23849    }
23850
23851    @Override
23852    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23853        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23854        synchronized (mPackages) {
23855            final long identity = Binder.clearCallingIdentity();
23856            try {
23857                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23858                        packageNames, userId);
23859            } finally {
23860                Binder.restoreCallingIdentity(identity);
23861            }
23862        }
23863    }
23864
23865    private static void enforceSystemOrPhoneCaller(String tag) {
23866        int callingUid = Binder.getCallingUid();
23867        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23868            throw new SecurityException(
23869                    "Cannot call " + tag + " from UID " + callingUid);
23870        }
23871    }
23872
23873    boolean isHistoricalPackageUsageAvailable() {
23874        return mPackageUsage.isHistoricalPackageUsageAvailable();
23875    }
23876
23877    /**
23878     * Return a <b>copy</b> of the collection of packages known to the package manager.
23879     * @return A copy of the values of mPackages.
23880     */
23881    Collection<PackageParser.Package> getPackages() {
23882        synchronized (mPackages) {
23883            return new ArrayList<>(mPackages.values());
23884        }
23885    }
23886
23887    /**
23888     * Logs process start information (including base APK hash) to the security log.
23889     * @hide
23890     */
23891    @Override
23892    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23893            String apkFile, int pid) {
23894        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23895            return;
23896        }
23897        if (!SecurityLog.isLoggingEnabled()) {
23898            return;
23899        }
23900        Bundle data = new Bundle();
23901        data.putLong("startTimestamp", System.currentTimeMillis());
23902        data.putString("processName", processName);
23903        data.putInt("uid", uid);
23904        data.putString("seinfo", seinfo);
23905        data.putString("apkFile", apkFile);
23906        data.putInt("pid", pid);
23907        Message msg = mProcessLoggingHandler.obtainMessage(
23908                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23909        msg.setData(data);
23910        mProcessLoggingHandler.sendMessage(msg);
23911    }
23912
23913    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23914        return mCompilerStats.getPackageStats(pkgName);
23915    }
23916
23917    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23918        return getOrCreateCompilerPackageStats(pkg.packageName);
23919    }
23920
23921    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23922        return mCompilerStats.getOrCreatePackageStats(pkgName);
23923    }
23924
23925    public void deleteCompilerPackageStats(String pkgName) {
23926        mCompilerStats.deletePackageStats(pkgName);
23927    }
23928
23929    @Override
23930    public int getInstallReason(String packageName, int userId) {
23931        final int callingUid = Binder.getCallingUid();
23932        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23933                true /* requireFullPermission */, false /* checkShell */,
23934                "get install reason");
23935        synchronized (mPackages) {
23936            final PackageSetting ps = mSettings.mPackages.get(packageName);
23937            if (filterAppAccessLPr(ps, callingUid, userId)) {
23938                return PackageManager.INSTALL_REASON_UNKNOWN;
23939            }
23940            if (ps != null) {
23941                return ps.getInstallReason(userId);
23942            }
23943        }
23944        return PackageManager.INSTALL_REASON_UNKNOWN;
23945    }
23946
23947    @Override
23948    public boolean canRequestPackageInstalls(String packageName, int userId) {
23949        return canRequestPackageInstallsInternal(packageName, 0, userId,
23950                true /* throwIfPermNotDeclared*/);
23951    }
23952
23953    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23954            boolean throwIfPermNotDeclared) {
23955        int callingUid = Binder.getCallingUid();
23956        int uid = getPackageUid(packageName, 0, userId);
23957        if (callingUid != uid && callingUid != Process.ROOT_UID
23958                && callingUid != Process.SYSTEM_UID) {
23959            throw new SecurityException(
23960                    "Caller uid " + callingUid + " does not own package " + packageName);
23961        }
23962        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23963        if (info == null) {
23964            return false;
23965        }
23966        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23967            return false;
23968        }
23969        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23970        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23971        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23972            if (throwIfPermNotDeclared) {
23973                throw new SecurityException("Need to declare " + appOpPermission
23974                        + " to call this api");
23975            } else {
23976                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23977                return false;
23978            }
23979        }
23980        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23981            return false;
23982        }
23983        if (mExternalSourcesPolicy != null) {
23984            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23985            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23986                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23987            }
23988        }
23989        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23990    }
23991
23992    @Override
23993    public ComponentName getInstantAppResolverSettingsComponent() {
23994        return mInstantAppResolverSettingsComponent;
23995    }
23996
23997    @Override
23998    public ComponentName getInstantAppInstallerComponent() {
23999        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24000            return null;
24001        }
24002        return mInstantAppInstallerActivity == null
24003                ? null : mInstantAppInstallerActivity.getComponentName();
24004    }
24005
24006    @Override
24007    public String getInstantAppAndroidId(String packageName, int userId) {
24008        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24009                "getInstantAppAndroidId");
24010        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24011                true /* requireFullPermission */, false /* checkShell */,
24012                "getInstantAppAndroidId");
24013        // Make sure the target is an Instant App.
24014        if (!isInstantApp(packageName, userId)) {
24015            return null;
24016        }
24017        synchronized (mPackages) {
24018            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24019        }
24020    }
24021
24022    boolean canHaveOatDir(String packageName) {
24023        synchronized (mPackages) {
24024            PackageParser.Package p = mPackages.get(packageName);
24025            if (p == null) {
24026                return false;
24027            }
24028            return p.canHaveOatDir();
24029        }
24030    }
24031
24032    private String getOatDir(PackageParser.Package pkg) {
24033        if (!pkg.canHaveOatDir()) {
24034            return null;
24035        }
24036        File codePath = new File(pkg.codePath);
24037        if (codePath.isDirectory()) {
24038            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24039        }
24040        return null;
24041    }
24042
24043    void deleteOatArtifactsOfPackage(String packageName) {
24044        final String[] instructionSets;
24045        final List<String> codePaths;
24046        final String oatDir;
24047        final PackageParser.Package pkg;
24048        synchronized (mPackages) {
24049            pkg = mPackages.get(packageName);
24050        }
24051        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24052        codePaths = pkg.getAllCodePaths();
24053        oatDir = getOatDir(pkg);
24054
24055        for (String codePath : codePaths) {
24056            for (String isa : instructionSets) {
24057                try {
24058                    mInstaller.deleteOdex(codePath, isa, oatDir);
24059                } catch (InstallerException e) {
24060                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24061                }
24062            }
24063        }
24064    }
24065
24066    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24067        Set<String> unusedPackages = new HashSet<>();
24068        long currentTimeInMillis = System.currentTimeMillis();
24069        synchronized (mPackages) {
24070            for (PackageParser.Package pkg : mPackages.values()) {
24071                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24072                if (ps == null) {
24073                    continue;
24074                }
24075                PackageDexUsage.PackageUseInfo packageUseInfo =
24076                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24077                if (PackageManagerServiceUtils
24078                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24079                                downgradeTimeThresholdMillis, packageUseInfo,
24080                                pkg.getLatestPackageUseTimeInMills(),
24081                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24082                    unusedPackages.add(pkg.packageName);
24083                }
24084            }
24085        }
24086        return unusedPackages;
24087    }
24088
24089    @Override
24090    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24091            int userId) {
24092        final int callingUid = Binder.getCallingUid();
24093        final int callingAppId = UserHandle.getAppId(callingUid);
24094
24095        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24096                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24097
24098        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24099                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24100            throw new SecurityException("Caller must have the "
24101                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24102        }
24103
24104        synchronized(mPackages) {
24105            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24106            scheduleWritePackageRestrictionsLocked(userId);
24107        }
24108    }
24109
24110    @Nullable
24111    @Override
24112    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24113        final int callingUid = Binder.getCallingUid();
24114        final int callingAppId = UserHandle.getAppId(callingUid);
24115
24116        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24117                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24118
24119        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24120                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24121            throw new SecurityException("Caller must have the "
24122                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24123        }
24124
24125        synchronized(mPackages) {
24126            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24127        }
24128    }
24129}
24130
24131interface PackageSender {
24132    /**
24133     * @param userIds User IDs where the action occurred on a full application
24134     * @param instantUserIds User IDs where the action occurred on an instant application
24135     */
24136    void sendPackageBroadcast(final String action, final String pkg,
24137        final Bundle extras, final int flags, final String targetPkg,
24138        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24139    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24140        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24141    void notifyPackageAdded(String packageName);
24142    void notifyPackageRemoved(String packageName);
24143}
24144