PackageManagerService.java revision 1dbe6d02849cb4af87bbd26b7537e11badead3b1
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_EPHEMERAL = Build.IS_DEBUGGABLE;
427    private static final boolean DEBUG_TRIAGED_MISSING = false;
428    private static final boolean DEBUG_APP_DATA = false;
429
430    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
431    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
432
433    private static final boolean HIDE_EPHEMERAL_APIS = false;
434
435    private static final boolean ENABLE_FREE_CACHE_V2 =
436            SystemProperties.getBoolean("fw.free_cache_v2", true);
437
438    private static final int RADIO_UID = Process.PHONE_UID;
439    private static final int LOG_UID = Process.LOG_UID;
440    private static final int NFC_UID = Process.NFC_UID;
441    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
442    private static final int SHELL_UID = Process.SHELL_UID;
443    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    }
586
587    /**
588     * The set of all protected actions [i.e. those actions for which a high priority
589     * intent filter is disallowed].
590     */
591    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
592    static {
593        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
594        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
596        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
597    }
598
599    // Compilation reasons.
600    public static final int REASON_FIRST_BOOT = 0;
601    public static final int REASON_BOOT = 1;
602    public static final int REASON_INSTALL = 2;
603    public static final int REASON_BACKGROUND_DEXOPT = 3;
604    public static final int REASON_AB_OTA = 4;
605    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
606    public static final int REASON_SHARED = 6;
607
608    public static final int REASON_LAST = REASON_SHARED;
609
610    /**
611     * Version number for the package parser cache. Increment this whenever the format or
612     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
613     */
614    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
615
616    /**
617     * Whether the package parser cache is enabled.
618     */
619    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
620
621    /**
622     * Permissions required in order to receive instant application lifecycle broadcasts.
623     */
624    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
625            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
626
627    final ServiceThread mHandlerThread;
628
629    final PackageHandler mHandler;
630
631    private final ProcessLoggingHandler mProcessLoggingHandler;
632
633    /**
634     * Messages for {@link #mHandler} that need to wait for system ready before
635     * being dispatched.
636     */
637    private ArrayList<Message> mPostSystemReadyMessages;
638
639    final int mSdkVersion = Build.VERSION.SDK_INT;
640
641    final Context mContext;
642    final boolean mFactoryTest;
643    final boolean mOnlyCore;
644    final DisplayMetrics mMetrics;
645    final int mDefParseFlags;
646    final String[] mSeparateProcesses;
647    final boolean mIsUpgrade;
648    final boolean mIsPreNUpgrade;
649    final boolean mIsPreNMR1Upgrade;
650
651    // Have we told the Activity Manager to whitelist the default container service by uid yet?
652    @GuardedBy("mPackages")
653    boolean mDefaultContainerWhitelisted = false;
654
655    @GuardedBy("mPackages")
656    private boolean mDexOptDialogShown;
657
658    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
659    // LOCK HELD.  Can be called with mInstallLock held.
660    @GuardedBy("mInstallLock")
661    final Installer mInstaller;
662
663    /** Directory where installed applications are stored */
664    private static final File sAppInstallDir =
665            new File(Environment.getDataDirectory(), "app");
666    /** Directory where installed application's 32-bit native libraries are copied. */
667    private static final File sAppLib32InstallDir =
668            new File(Environment.getDataDirectory(), "app-lib");
669    /** Directory where code and non-resource assets of forward-locked applications are stored */
670    private static final File sDrmAppPrivateInstallDir =
671            new File(Environment.getDataDirectory(), "app-private");
672
673    // ----------------------------------------------------------------
674
675    // Lock for state used when installing and doing other long running
676    // operations.  Methods that must be called with this lock held have
677    // the suffix "LI".
678    final Object mInstallLock = new Object();
679
680    // ----------------------------------------------------------------
681
682    // Keys are String (package name), values are Package.  This also serves
683    // as the lock for the global state.  Methods that must be called with
684    // this lock held have the prefix "LP".
685    @GuardedBy("mPackages")
686    final ArrayMap<String, PackageParser.Package> mPackages =
687            new ArrayMap<String, PackageParser.Package>();
688
689    final ArrayMap<String, Set<String>> mKnownCodebase =
690            new ArrayMap<String, Set<String>>();
691
692    // Keys are isolated uids and values are the uid of the application
693    // that created the isolated proccess.
694    @GuardedBy("mPackages")
695    final SparseIntArray mIsolatedOwners = new SparseIntArray();
696
697    /**
698     * Tracks new system packages [received in an OTA] that we expect to
699     * find updated user-installed versions. Keys are package name, values
700     * are package location.
701     */
702    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
703    /**
704     * Tracks high priority intent filters for protected actions. During boot, certain
705     * filter actions are protected and should never be allowed to have a high priority
706     * intent filter for them. However, there is one, and only one exception -- the
707     * setup wizard. It must be able to define a high priority intent filter for these
708     * actions to ensure there are no escapes from the wizard. We need to delay processing
709     * of these during boot as we need to look at all of the system packages in order
710     * to know which component is the setup wizard.
711     */
712    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
713    /**
714     * Whether or not processing protected filters should be deferred.
715     */
716    private boolean mDeferProtectedFilters = true;
717
718    /**
719     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
720     */
721    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
722    /**
723     * Whether or not system app permissions should be promoted from install to runtime.
724     */
725    boolean mPromoteSystemApps;
726
727    @GuardedBy("mPackages")
728    final Settings mSettings;
729
730    /**
731     * Set of package names that are currently "frozen", which means active
732     * surgery is being done on the code/data for that package. The platform
733     * will refuse to launch frozen packages to avoid race conditions.
734     *
735     * @see PackageFreezer
736     */
737    @GuardedBy("mPackages")
738    final ArraySet<String> mFrozenPackages = new ArraySet<>();
739
740    final ProtectedPackages mProtectedPackages;
741
742    @GuardedBy("mLoadedVolumes")
743    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
744
745    boolean mFirstBoot;
746
747    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
748
749    @GuardedBy("mAvailableFeatures")
750    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
751
752    private final InstantAppRegistry mInstantAppRegistry;
753
754    @GuardedBy("mPackages")
755    int mChangedPackagesSequenceNumber;
756    /**
757     * List of changed [installed, removed or updated] packages.
758     * mapping from user id -> sequence number -> package name
759     */
760    @GuardedBy("mPackages")
761    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
762    /**
763     * The sequence number of the last change to a package.
764     * mapping from user id -> package name -> sequence number
765     */
766    @GuardedBy("mPackages")
767    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
768
769    @GuardedBy("mPackages")
770    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
771
772    class PackageParserCallback implements PackageParser.Callback {
773        @Override public final boolean hasFeature(String feature) {
774            return PackageManagerService.this.hasSystemFeature(feature, 0);
775        }
776
777        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
778                Collection<PackageParser.Package> allPackages, String targetPackageName) {
779            List<PackageParser.Package> overlayPackages = null;
780            for (PackageParser.Package p : allPackages) {
781                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
782                    if (overlayPackages == null) {
783                        overlayPackages = new ArrayList<PackageParser.Package>();
784                    }
785                    overlayPackages.add(p);
786                }
787            }
788            if (overlayPackages != null) {
789                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
790                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
791                        return p1.mOverlayPriority - p2.mOverlayPriority;
792                    }
793                };
794                Collections.sort(overlayPackages, cmp);
795            }
796            return overlayPackages;
797        }
798
799        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
800                String targetPackageName, String targetPath) {
801            if ("android".equals(targetPackageName)) {
802                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
803                // native AssetManager.
804                return null;
805            }
806            List<PackageParser.Package> overlayPackages =
807                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
808            if (overlayPackages == null || overlayPackages.isEmpty()) {
809                return null;
810            }
811            List<String> overlayPathList = null;
812            for (PackageParser.Package overlayPackage : overlayPackages) {
813                if (targetPath == null) {
814                    if (overlayPathList == null) {
815                        overlayPathList = new ArrayList<String>();
816                    }
817                    overlayPathList.add(overlayPackage.baseCodePath);
818                    continue;
819                }
820
821                try {
822                    // Creates idmaps for system to parse correctly the Android manifest of the
823                    // target package.
824                    //
825                    // OverlayManagerService will update each of them with a correct gid from its
826                    // target package app id.
827                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
828                            UserHandle.getSharedAppGid(
829                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
830                    if (overlayPathList == null) {
831                        overlayPathList = new ArrayList<String>();
832                    }
833                    overlayPathList.add(overlayPackage.baseCodePath);
834                } catch (InstallerException e) {
835                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
836                            overlayPackage.baseCodePath);
837                }
838            }
839            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
840        }
841
842        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
843            synchronized (mPackages) {
844                return getStaticOverlayPathsLocked(
845                        mPackages.values(), targetPackageName, targetPath);
846            }
847        }
848
849        @Override public final String[] getOverlayApks(String targetPackageName) {
850            return getStaticOverlayPaths(targetPackageName, null);
851        }
852
853        @Override public final String[] getOverlayPaths(String targetPackageName,
854                String targetPath) {
855            return getStaticOverlayPaths(targetPackageName, targetPath);
856        }
857    }
858
859    class ParallelPackageParserCallback extends PackageParserCallback {
860        List<PackageParser.Package> mOverlayPackages = null;
861
862        void findStaticOverlayPackages() {
863            synchronized (mPackages) {
864                for (PackageParser.Package p : mPackages.values()) {
865                    if (p.mOverlayIsStatic) {
866                        if (mOverlayPackages == null) {
867                            mOverlayPackages = new ArrayList<PackageParser.Package>();
868                        }
869                        mOverlayPackages.add(p);
870                    }
871                }
872            }
873        }
874
875        @Override
876        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
877            // We can trust mOverlayPackages without holding mPackages because package uninstall
878            // can't happen while running parallel parsing.
879            // Moreover holding mPackages on each parsing thread causes dead-lock.
880            return mOverlayPackages == null ? null :
881                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
882        }
883    }
884
885    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
886    final ParallelPackageParserCallback mParallelPackageParserCallback =
887            new ParallelPackageParserCallback();
888
889    public static final class SharedLibraryEntry {
890        public final @Nullable String path;
891        public final @Nullable String apk;
892        public final @NonNull SharedLibraryInfo info;
893
894        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
895                String declaringPackageName, long declaringPackageVersionCode) {
896            path = _path;
897            apk = _apk;
898            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
899                    declaringPackageName, declaringPackageVersionCode), null);
900        }
901    }
902
903    // Currently known shared libraries.
904    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
905    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
906            new ArrayMap<>();
907
908    // All available activities, for your resolving pleasure.
909    final ActivityIntentResolver mActivities =
910            new ActivityIntentResolver();
911
912    // All available receivers, for your resolving pleasure.
913    final ActivityIntentResolver mReceivers =
914            new ActivityIntentResolver();
915
916    // All available services, for your resolving pleasure.
917    final ServiceIntentResolver mServices = new ServiceIntentResolver();
918
919    // All available providers, for your resolving pleasure.
920    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
921
922    // Mapping from provider base names (first directory in content URI codePath)
923    // to the provider information.
924    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
925            new ArrayMap<String, PackageParser.Provider>();
926
927    // Mapping from instrumentation class names to info about them.
928    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
929            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
930
931    // Packages whose data we have transfered into another package, thus
932    // should no longer exist.
933    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
934
935    // Broadcast actions that are only available to the system.
936    @GuardedBy("mProtectedBroadcasts")
937    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
938
939    /** List of packages waiting for verification. */
940    final SparseArray<PackageVerificationState> mPendingVerification
941            = new SparseArray<PackageVerificationState>();
942
943    final PackageInstallerService mInstallerService;
944
945    final ArtManagerService mArtManagerService;
946
947    private final PackageDexOptimizer mPackageDexOptimizer;
948    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
949    // is used by other apps).
950    private final DexManager mDexManager;
951
952    private AtomicInteger mNextMoveId = new AtomicInteger();
953    private final MoveCallbacks mMoveCallbacks;
954
955    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
956
957    // Cache of users who need badging.
958    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
959
960    /** Token for keys in mPendingVerification. */
961    private int mPendingVerificationToken = 0;
962
963    volatile boolean mSystemReady;
964    volatile boolean mSafeMode;
965    volatile boolean mHasSystemUidErrors;
966    private volatile boolean mEphemeralAppsDisabled;
967
968    ApplicationInfo mAndroidApplication;
969    final ActivityInfo mResolveActivity = new ActivityInfo();
970    final ResolveInfo mResolveInfo = new ResolveInfo();
971    ComponentName mResolveComponentName;
972    PackageParser.Package mPlatformPackage;
973    ComponentName mCustomResolverComponentName;
974
975    boolean mResolverReplaced = false;
976
977    private final @Nullable ComponentName mIntentFilterVerifierComponent;
978    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
979
980    private int mIntentFilterVerificationToken = 0;
981
982    /** The service connection to the ephemeral resolver */
983    final EphemeralResolverConnection mInstantAppResolverConnection;
984    /** Component used to show resolver settings for Instant Apps */
985    final ComponentName mInstantAppResolverSettingsComponent;
986
987    /** Activity used to install instant applications */
988    ActivityInfo mInstantAppInstallerActivity;
989    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
990
991    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
992            = new SparseArray<IntentFilterVerificationState>();
993
994    // TODO remove this and go through mPermissonManager directly
995    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
996    private final PermissionManagerInternal mPermissionManager;
997
998    // List of packages names to keep cached, even if they are uninstalled for all users
999    private List<String> mKeepUninstalledPackages;
1000
1001    private UserManagerInternal mUserManagerInternal;
1002    private ActivityManagerInternal mActivityManagerInternal;
1003
1004    private DeviceIdleController.LocalService mDeviceIdleController;
1005
1006    private File mCacheDir;
1007
1008    private Future<?> mPrepareAppDataFuture;
1009
1010    private static class IFVerificationParams {
1011        PackageParser.Package pkg;
1012        boolean replacing;
1013        int userId;
1014        int verifierUid;
1015
1016        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1017                int _userId, int _verifierUid) {
1018            pkg = _pkg;
1019            replacing = _replacing;
1020            userId = _userId;
1021            replacing = _replacing;
1022            verifierUid = _verifierUid;
1023        }
1024    }
1025
1026    private interface IntentFilterVerifier<T extends IntentFilter> {
1027        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1028                                               T filter, String packageName);
1029        void startVerifications(int userId);
1030        void receiveVerificationResponse(int verificationId);
1031    }
1032
1033    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1034        private Context mContext;
1035        private ComponentName mIntentFilterVerifierComponent;
1036        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1037
1038        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1039            mContext = context;
1040            mIntentFilterVerifierComponent = verifierComponent;
1041        }
1042
1043        private String getDefaultScheme() {
1044            return IntentFilter.SCHEME_HTTPS;
1045        }
1046
1047        @Override
1048        public void startVerifications(int userId) {
1049            // Launch verifications requests
1050            int count = mCurrentIntentFilterVerifications.size();
1051            for (int n=0; n<count; n++) {
1052                int verificationId = mCurrentIntentFilterVerifications.get(n);
1053                final IntentFilterVerificationState ivs =
1054                        mIntentFilterVerificationStates.get(verificationId);
1055
1056                String packageName = ivs.getPackageName();
1057
1058                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1059                final int filterCount = filters.size();
1060                ArraySet<String> domainsSet = new ArraySet<>();
1061                for (int m=0; m<filterCount; m++) {
1062                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1063                    domainsSet.addAll(filter.getHostsList());
1064                }
1065                synchronized (mPackages) {
1066                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1067                            packageName, domainsSet) != null) {
1068                        scheduleWriteSettingsLocked();
1069                    }
1070                }
1071                sendVerificationRequest(verificationId, ivs);
1072            }
1073            mCurrentIntentFilterVerifications.clear();
1074        }
1075
1076        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1077            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1078            verificationIntent.putExtra(
1079                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1080                    verificationId);
1081            verificationIntent.putExtra(
1082                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1083                    getDefaultScheme());
1084            verificationIntent.putExtra(
1085                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1086                    ivs.getHostsString());
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1089                    ivs.getPackageName());
1090            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1091            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1092
1093            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1094            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1095                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1096                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1097
1098            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1099            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1100                    "Sending IntentFilter verification broadcast");
1101        }
1102
1103        public void receiveVerificationResponse(int verificationId) {
1104            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1105
1106            final boolean verified = ivs.isVerified();
1107
1108            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1109            final int count = filters.size();
1110            if (DEBUG_DOMAIN_VERIFICATION) {
1111                Slog.i(TAG, "Received verification response " + verificationId
1112                        + " for " + count + " filters, verified=" + verified);
1113            }
1114            for (int n=0; n<count; n++) {
1115                PackageParser.ActivityIntentInfo filter = filters.get(n);
1116                filter.setVerified(verified);
1117
1118                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1119                        + " verified with result:" + verified + " and hosts:"
1120                        + ivs.getHostsString());
1121            }
1122
1123            mIntentFilterVerificationStates.remove(verificationId);
1124
1125            final String packageName = ivs.getPackageName();
1126            IntentFilterVerificationInfo ivi = null;
1127
1128            synchronized (mPackages) {
1129                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1130            }
1131            if (ivi == null) {
1132                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1133                        + verificationId + " packageName:" + packageName);
1134                return;
1135            }
1136            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1137                    "Updating IntentFilterVerificationInfo for package " + packageName
1138                            +" verificationId:" + verificationId);
1139
1140            synchronized (mPackages) {
1141                if (verified) {
1142                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1143                } else {
1144                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1145                }
1146                scheduleWriteSettingsLocked();
1147
1148                final int userId = ivs.getUserId();
1149                if (userId != UserHandle.USER_ALL) {
1150                    final int userStatus =
1151                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1152
1153                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1154                    boolean needUpdate = false;
1155
1156                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1157                    // already been set by the User thru the Disambiguation dialog
1158                    switch (userStatus) {
1159                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1160                            if (verified) {
1161                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1162                            } else {
1163                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1164                            }
1165                            needUpdate = true;
1166                            break;
1167
1168                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1169                            if (verified) {
1170                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1171                                needUpdate = true;
1172                            }
1173                            break;
1174
1175                        default:
1176                            // Nothing to do
1177                    }
1178
1179                    if (needUpdate) {
1180                        mSettings.updateIntentFilterVerificationStatusLPw(
1181                                packageName, updatedStatus, userId);
1182                        scheduleWritePackageRestrictionsLocked(userId);
1183                    }
1184                }
1185            }
1186        }
1187
1188        @Override
1189        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1190                    ActivityIntentInfo filter, String packageName) {
1191            if (!hasValidDomains(filter)) {
1192                return false;
1193            }
1194            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1195            if (ivs == null) {
1196                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1197                        packageName);
1198            }
1199            if (DEBUG_DOMAIN_VERIFICATION) {
1200                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1201            }
1202            ivs.addFilter(filter);
1203            return true;
1204        }
1205
1206        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1207                int userId, int verificationId, String packageName) {
1208            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1209                    verifierUid, userId, packageName);
1210            ivs.setPendingState();
1211            synchronized (mPackages) {
1212                mIntentFilterVerificationStates.append(verificationId, ivs);
1213                mCurrentIntentFilterVerifications.add(verificationId);
1214            }
1215            return ivs;
1216        }
1217    }
1218
1219    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1220        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1221                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1222                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1223    }
1224
1225    // Set of pending broadcasts for aggregating enable/disable of components.
1226    static class PendingPackageBroadcasts {
1227        // for each user id, a map of <package name -> components within that package>
1228        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1229
1230        public PendingPackageBroadcasts() {
1231            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1232        }
1233
1234        public ArrayList<String> get(int userId, String packageName) {
1235            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1236            return packages.get(packageName);
1237        }
1238
1239        public void put(int userId, String packageName, ArrayList<String> components) {
1240            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1241            packages.put(packageName, components);
1242        }
1243
1244        public void remove(int userId, String packageName) {
1245            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1246            if (packages != null) {
1247                packages.remove(packageName);
1248            }
1249        }
1250
1251        public void remove(int userId) {
1252            mUidMap.remove(userId);
1253        }
1254
1255        public int userIdCount() {
1256            return mUidMap.size();
1257        }
1258
1259        public int userIdAt(int n) {
1260            return mUidMap.keyAt(n);
1261        }
1262
1263        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1264            return mUidMap.get(userId);
1265        }
1266
1267        public int size() {
1268            // total number of pending broadcast entries across all userIds
1269            int num = 0;
1270            for (int i = 0; i< mUidMap.size(); i++) {
1271                num += mUidMap.valueAt(i).size();
1272            }
1273            return num;
1274        }
1275
1276        public void clear() {
1277            mUidMap.clear();
1278        }
1279
1280        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1281            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1282            if (map == null) {
1283                map = new ArrayMap<String, ArrayList<String>>();
1284                mUidMap.put(userId, map);
1285            }
1286            return map;
1287        }
1288    }
1289    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1290
1291    // Service Connection to remote media container service to copy
1292    // package uri's from external media onto secure containers
1293    // or internal storage.
1294    private IMediaContainerService mContainerService = null;
1295
1296    static final int SEND_PENDING_BROADCAST = 1;
1297    static final int MCS_BOUND = 3;
1298    static final int END_COPY = 4;
1299    static final int INIT_COPY = 5;
1300    static final int MCS_UNBIND = 6;
1301    static final int START_CLEANING_PACKAGE = 7;
1302    static final int FIND_INSTALL_LOC = 8;
1303    static final int POST_INSTALL = 9;
1304    static final int MCS_RECONNECT = 10;
1305    static final int MCS_GIVE_UP = 11;
1306    static final int WRITE_SETTINGS = 13;
1307    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1308    static final int PACKAGE_VERIFIED = 15;
1309    static final int CHECK_PENDING_VERIFICATION = 16;
1310    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1311    static final int INTENT_FILTER_VERIFIED = 18;
1312    static final int WRITE_PACKAGE_LIST = 19;
1313    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1314
1315    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1316
1317    // Delay time in millisecs
1318    static final int BROADCAST_DELAY = 10 * 1000;
1319
1320    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1321            2 * 60 * 60 * 1000L; /* two hours */
1322
1323    static UserManagerService sUserManager;
1324
1325    // Stores a list of users whose package restrictions file needs to be updated
1326    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1327
1328    final private DefaultContainerConnection mDefContainerConn =
1329            new DefaultContainerConnection();
1330    class DefaultContainerConnection implements ServiceConnection {
1331        public void onServiceConnected(ComponentName name, IBinder service) {
1332            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1333            final IMediaContainerService imcs = IMediaContainerService.Stub
1334                    .asInterface(Binder.allowBlocking(service));
1335            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1336        }
1337
1338        public void onServiceDisconnected(ComponentName name) {
1339            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1340        }
1341    }
1342
1343    // Recordkeeping of restore-after-install operations that are currently in flight
1344    // between the Package Manager and the Backup Manager
1345    static class PostInstallData {
1346        public InstallArgs args;
1347        public PackageInstalledInfo res;
1348
1349        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1350            args = _a;
1351            res = _r;
1352        }
1353    }
1354
1355    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1356    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1357
1358    // XML tags for backup/restore of various bits of state
1359    private static final String TAG_PREFERRED_BACKUP = "pa";
1360    private static final String TAG_DEFAULT_APPS = "da";
1361    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1362
1363    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1364    private static final String TAG_ALL_GRANTS = "rt-grants";
1365    private static final String TAG_GRANT = "grant";
1366    private static final String ATTR_PACKAGE_NAME = "pkg";
1367
1368    private static final String TAG_PERMISSION = "perm";
1369    private static final String ATTR_PERMISSION_NAME = "name";
1370    private static final String ATTR_IS_GRANTED = "g";
1371    private static final String ATTR_USER_SET = "set";
1372    private static final String ATTR_USER_FIXED = "fixed";
1373    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1374
1375    // System/policy permission grants are not backed up
1376    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1377            FLAG_PERMISSION_POLICY_FIXED
1378            | FLAG_PERMISSION_SYSTEM_FIXED
1379            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1380
1381    // And we back up these user-adjusted states
1382    private static final int USER_RUNTIME_GRANT_MASK =
1383            FLAG_PERMISSION_USER_SET
1384            | FLAG_PERMISSION_USER_FIXED
1385            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1386
1387    final @Nullable String mRequiredVerifierPackage;
1388    final @NonNull String mRequiredInstallerPackage;
1389    final @NonNull String mRequiredUninstallerPackage;
1390    final @Nullable String mSetupWizardPackage;
1391    final @Nullable String mStorageManagerPackage;
1392    final @NonNull String mServicesSystemSharedLibraryPackageName;
1393    final @NonNull String mSharedSystemSharedLibraryPackageName;
1394
1395    private final PackageUsage mPackageUsage = new PackageUsage();
1396    private final CompilerStats mCompilerStats = new CompilerStats();
1397
1398    class PackageHandler extends Handler {
1399        private boolean mBound = false;
1400        final ArrayList<HandlerParams> mPendingInstalls =
1401            new ArrayList<HandlerParams>();
1402
1403        private boolean connectToService() {
1404            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1405                    " DefaultContainerService");
1406            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1407            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1408            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1409                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1410                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1411                mBound = true;
1412                return true;
1413            }
1414            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415            return false;
1416        }
1417
1418        private void disconnectService() {
1419            mContainerService = null;
1420            mBound = false;
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1422            mContext.unbindService(mDefContainerConn);
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1424        }
1425
1426        PackageHandler(Looper looper) {
1427            super(looper);
1428        }
1429
1430        public void handleMessage(Message msg) {
1431            try {
1432                doHandleMessage(msg);
1433            } finally {
1434                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1435            }
1436        }
1437
1438        void doHandleMessage(Message msg) {
1439            switch (msg.what) {
1440                case INIT_COPY: {
1441                    HandlerParams params = (HandlerParams) msg.obj;
1442                    int idx = mPendingInstalls.size();
1443                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1444                    // If a bind was already initiated we dont really
1445                    // need to do anything. The pending install
1446                    // will be processed later on.
1447                    if (!mBound) {
1448                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1449                                System.identityHashCode(mHandler));
1450                        // If this is the only one pending we might
1451                        // have to bind to the service again.
1452                        if (!connectToService()) {
1453                            Slog.e(TAG, "Failed to bind to media container service");
1454                            params.serviceError();
1455                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1456                                    System.identityHashCode(mHandler));
1457                            if (params.traceMethod != null) {
1458                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1459                                        params.traceCookie);
1460                            }
1461                            return;
1462                        } else {
1463                            // Once we bind to the service, the first
1464                            // pending request will be processed.
1465                            mPendingInstalls.add(idx, params);
1466                        }
1467                    } else {
1468                        mPendingInstalls.add(idx, params);
1469                        // Already bound to the service. Just make
1470                        // sure we trigger off processing the first request.
1471                        if (idx == 0) {
1472                            mHandler.sendEmptyMessage(MCS_BOUND);
1473                        }
1474                    }
1475                    break;
1476                }
1477                case MCS_BOUND: {
1478                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1479                    if (msg.obj != null) {
1480                        mContainerService = (IMediaContainerService) msg.obj;
1481                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1482                                System.identityHashCode(mHandler));
1483                    }
1484                    if (mContainerService == null) {
1485                        if (!mBound) {
1486                            // Something seriously wrong since we are not bound and we are not
1487                            // waiting for connection. Bail out.
1488                            Slog.e(TAG, "Cannot bind to media container service");
1489                            for (HandlerParams params : mPendingInstalls) {
1490                                // Indicate service bind error
1491                                params.serviceError();
1492                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1493                                        System.identityHashCode(params));
1494                                if (params.traceMethod != null) {
1495                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1496                                            params.traceMethod, params.traceCookie);
1497                                }
1498                                return;
1499                            }
1500                            mPendingInstalls.clear();
1501                        } else {
1502                            Slog.w(TAG, "Waiting to connect to media container service");
1503                        }
1504                    } else if (mPendingInstalls.size() > 0) {
1505                        HandlerParams params = mPendingInstalls.get(0);
1506                        if (params != null) {
1507                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1508                                    System.identityHashCode(params));
1509                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1510                            if (params.startCopy()) {
1511                                // We are done...  look for more work or to
1512                                // go idle.
1513                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1514                                        "Checking for more work or unbind...");
1515                                // Delete pending install
1516                                if (mPendingInstalls.size() > 0) {
1517                                    mPendingInstalls.remove(0);
1518                                }
1519                                if (mPendingInstalls.size() == 0) {
1520                                    if (mBound) {
1521                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1522                                                "Posting delayed MCS_UNBIND");
1523                                        removeMessages(MCS_UNBIND);
1524                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1525                                        // Unbind after a little delay, to avoid
1526                                        // continual thrashing.
1527                                        sendMessageDelayed(ubmsg, 10000);
1528                                    }
1529                                } else {
1530                                    // There are more pending requests in queue.
1531                                    // Just post MCS_BOUND message to trigger processing
1532                                    // of next pending install.
1533                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1534                                            "Posting MCS_BOUND for next work");
1535                                    mHandler.sendEmptyMessage(MCS_BOUND);
1536                                }
1537                            }
1538                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1539                        }
1540                    } else {
1541                        // Should never happen ideally.
1542                        Slog.w(TAG, "Empty queue");
1543                    }
1544                    break;
1545                }
1546                case MCS_RECONNECT: {
1547                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1548                    if (mPendingInstalls.size() > 0) {
1549                        if (mBound) {
1550                            disconnectService();
1551                        }
1552                        if (!connectToService()) {
1553                            Slog.e(TAG, "Failed to bind to media container service");
1554                            for (HandlerParams params : mPendingInstalls) {
1555                                // Indicate service bind error
1556                                params.serviceError();
1557                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1558                                        System.identityHashCode(params));
1559                            }
1560                            mPendingInstalls.clear();
1561                        }
1562                    }
1563                    break;
1564                }
1565                case MCS_UNBIND: {
1566                    // If there is no actual work left, then time to unbind.
1567                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1568
1569                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1570                        if (mBound) {
1571                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1572
1573                            disconnectService();
1574                        }
1575                    } else if (mPendingInstalls.size() > 0) {
1576                        // There are more pending requests in queue.
1577                        // Just post MCS_BOUND message to trigger processing
1578                        // of next pending install.
1579                        mHandler.sendEmptyMessage(MCS_BOUND);
1580                    }
1581
1582                    break;
1583                }
1584                case MCS_GIVE_UP: {
1585                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1586                    HandlerParams params = mPendingInstalls.remove(0);
1587                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1588                            System.identityHashCode(params));
1589                    break;
1590                }
1591                case SEND_PENDING_BROADCAST: {
1592                    String packages[];
1593                    ArrayList<String> components[];
1594                    int size = 0;
1595                    int uids[];
1596                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1597                    synchronized (mPackages) {
1598                        if (mPendingBroadcasts == null) {
1599                            return;
1600                        }
1601                        size = mPendingBroadcasts.size();
1602                        if (size <= 0) {
1603                            // Nothing to be done. Just return
1604                            return;
1605                        }
1606                        packages = new String[size];
1607                        components = new ArrayList[size];
1608                        uids = new int[size];
1609                        int i = 0;  // filling out the above arrays
1610
1611                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1612                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1613                            Iterator<Map.Entry<String, ArrayList<String>>> it
1614                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1615                                            .entrySet().iterator();
1616                            while (it.hasNext() && i < size) {
1617                                Map.Entry<String, ArrayList<String>> ent = it.next();
1618                                packages[i] = ent.getKey();
1619                                components[i] = ent.getValue();
1620                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1621                                uids[i] = (ps != null)
1622                                        ? UserHandle.getUid(packageUserId, ps.appId)
1623                                        : -1;
1624                                i++;
1625                            }
1626                        }
1627                        size = i;
1628                        mPendingBroadcasts.clear();
1629                    }
1630                    // Send broadcasts
1631                    for (int i = 0; i < size; i++) {
1632                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1633                    }
1634                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1635                    break;
1636                }
1637                case START_CLEANING_PACKAGE: {
1638                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1639                    final String packageName = (String)msg.obj;
1640                    final int userId = msg.arg1;
1641                    final boolean andCode = msg.arg2 != 0;
1642                    synchronized (mPackages) {
1643                        if (userId == UserHandle.USER_ALL) {
1644                            int[] users = sUserManager.getUserIds();
1645                            for (int user : users) {
1646                                mSettings.addPackageToCleanLPw(
1647                                        new PackageCleanItem(user, packageName, andCode));
1648                            }
1649                        } else {
1650                            mSettings.addPackageToCleanLPw(
1651                                    new PackageCleanItem(userId, packageName, andCode));
1652                        }
1653                    }
1654                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1655                    startCleaningPackages();
1656                } break;
1657                case POST_INSTALL: {
1658                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1659
1660                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1661                    final boolean didRestore = (msg.arg2 != 0);
1662                    mRunningInstalls.delete(msg.arg1);
1663
1664                    if (data != null) {
1665                        InstallArgs args = data.args;
1666                        PackageInstalledInfo parentRes = data.res;
1667
1668                        final boolean grantPermissions = (args.installFlags
1669                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1670                        final boolean killApp = (args.installFlags
1671                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1672                        final boolean virtualPreload = ((args.installFlags
1673                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1674                        final String[] grantedPermissions = args.installGrantPermissions;
1675
1676                        // Handle the parent package
1677                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1678                                virtualPreload, grantedPermissions, didRestore,
1679                                args.installerPackageName, args.observer);
1680
1681                        // Handle the child packages
1682                        final int childCount = (parentRes.addedChildPackages != null)
1683                                ? parentRes.addedChildPackages.size() : 0;
1684                        for (int i = 0; i < childCount; i++) {
1685                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1686                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1687                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1688                                    args.installerPackageName, args.observer);
1689                        }
1690
1691                        // Log tracing if needed
1692                        if (args.traceMethod != null) {
1693                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1694                                    args.traceCookie);
1695                        }
1696                    } else {
1697                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1698                    }
1699
1700                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1701                } break;
1702                case WRITE_SETTINGS: {
1703                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1704                    synchronized (mPackages) {
1705                        removeMessages(WRITE_SETTINGS);
1706                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1707                        mSettings.writeLPr();
1708                        mDirtyUsers.clear();
1709                    }
1710                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1711                } break;
1712                case WRITE_PACKAGE_RESTRICTIONS: {
1713                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1714                    synchronized (mPackages) {
1715                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1716                        for (int userId : mDirtyUsers) {
1717                            mSettings.writePackageRestrictionsLPr(userId);
1718                        }
1719                        mDirtyUsers.clear();
1720                    }
1721                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1722                } break;
1723                case WRITE_PACKAGE_LIST: {
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1725                    synchronized (mPackages) {
1726                        removeMessages(WRITE_PACKAGE_LIST);
1727                        mSettings.writePackageListLPr(msg.arg1);
1728                    }
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1730                } break;
1731                case CHECK_PENDING_VERIFICATION: {
1732                    final int verificationId = msg.arg1;
1733                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1734
1735                    if ((state != null) && !state.timeoutExtended()) {
1736                        final InstallArgs args = state.getInstallArgs();
1737                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1738
1739                        Slog.i(TAG, "Verification timed out for " + originUri);
1740                        mPendingVerification.remove(verificationId);
1741
1742                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1743
1744                        final UserHandle user = args.getUser();
1745                        if (getDefaultVerificationResponse(user)
1746                                == PackageManager.VERIFICATION_ALLOW) {
1747                            Slog.i(TAG, "Continuing with installation of " + originUri);
1748                            state.setVerifierResponse(Binder.getCallingUid(),
1749                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1750                            broadcastPackageVerified(verificationId, originUri,
1751                                    PackageManager.VERIFICATION_ALLOW, user);
1752                            try {
1753                                ret = args.copyApk(mContainerService, true);
1754                            } catch (RemoteException e) {
1755                                Slog.e(TAG, "Could not contact the ContainerService");
1756                            }
1757                        } else {
1758                            broadcastPackageVerified(verificationId, originUri,
1759                                    PackageManager.VERIFICATION_REJECT, user);
1760                        }
1761
1762                        Trace.asyncTraceEnd(
1763                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1764
1765                        processPendingInstall(args, ret);
1766                        mHandler.sendEmptyMessage(MCS_UNBIND);
1767                    }
1768                    break;
1769                }
1770                case PACKAGE_VERIFIED: {
1771                    final int verificationId = msg.arg1;
1772
1773                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1774                    if (state == null) {
1775                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1776                        break;
1777                    }
1778
1779                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1780
1781                    state.setVerifierResponse(response.callerUid, response.code);
1782
1783                    if (state.isVerificationComplete()) {
1784                        mPendingVerification.remove(verificationId);
1785
1786                        final InstallArgs args = state.getInstallArgs();
1787                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1788
1789                        int ret;
1790                        if (state.isInstallAllowed()) {
1791                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1792                            broadcastPackageVerified(verificationId, originUri,
1793                                    response.code, state.getInstallArgs().getUser());
1794                            try {
1795                                ret = args.copyApk(mContainerService, true);
1796                            } catch (RemoteException e) {
1797                                Slog.e(TAG, "Could not contact the ContainerService");
1798                            }
1799                        } else {
1800                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1801                        }
1802
1803                        Trace.asyncTraceEnd(
1804                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1805
1806                        processPendingInstall(args, ret);
1807                        mHandler.sendEmptyMessage(MCS_UNBIND);
1808                    }
1809
1810                    break;
1811                }
1812                case START_INTENT_FILTER_VERIFICATIONS: {
1813                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1814                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1815                            params.replacing, params.pkg);
1816                    break;
1817                }
1818                case INTENT_FILTER_VERIFIED: {
1819                    final int verificationId = msg.arg1;
1820
1821                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1822                            verificationId);
1823                    if (state == null) {
1824                        Slog.w(TAG, "Invalid IntentFilter verification token "
1825                                + verificationId + " received");
1826                        break;
1827                    }
1828
1829                    final int userId = state.getUserId();
1830
1831                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1832                            "Processing IntentFilter verification with token:"
1833                            + verificationId + " and userId:" + userId);
1834
1835                    final IntentFilterVerificationResponse response =
1836                            (IntentFilterVerificationResponse) msg.obj;
1837
1838                    state.setVerifierResponse(response.callerUid, response.code);
1839
1840                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1841                            "IntentFilter verification with token:" + verificationId
1842                            + " and userId:" + userId
1843                            + " is settings verifier response with response code:"
1844                            + response.code);
1845
1846                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1847                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1848                                + response.getFailedDomainsString());
1849                    }
1850
1851                    if (state.isVerificationComplete()) {
1852                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1853                    } else {
1854                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1855                                "IntentFilter verification with token:" + verificationId
1856                                + " was not said to be complete");
1857                    }
1858
1859                    break;
1860                }
1861                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1862                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1863                            mInstantAppResolverConnection,
1864                            (InstantAppRequest) msg.obj,
1865                            mInstantAppInstallerActivity,
1866                            mHandler);
1867                }
1868            }
1869        }
1870    }
1871
1872    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1873        @Override
1874        public void onGidsChanged(int appId, int userId) {
1875            mHandler.post(new Runnable() {
1876                @Override
1877                public void run() {
1878                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1879                }
1880            });
1881        }
1882        @Override
1883        public void onPermissionGranted(int uid, int userId) {
1884            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1885
1886            // Not critical; if this is lost, the application has to request again.
1887            synchronized (mPackages) {
1888                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1889            }
1890        }
1891        @Override
1892        public void onInstallPermissionGranted() {
1893            synchronized (mPackages) {
1894                scheduleWriteSettingsLocked();
1895            }
1896        }
1897        @Override
1898        public void onPermissionRevoked(int uid, int userId) {
1899            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1900
1901            synchronized (mPackages) {
1902                // Critical; after this call the application should never have the permission
1903                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1904            }
1905
1906            final int appId = UserHandle.getAppId(uid);
1907            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1908        }
1909        @Override
1910        public void onInstallPermissionRevoked() {
1911            synchronized (mPackages) {
1912                scheduleWriteSettingsLocked();
1913            }
1914        }
1915        @Override
1916        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1917            synchronized (mPackages) {
1918                for (int userId : updatedUserIds) {
1919                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1920                }
1921            }
1922        }
1923        @Override
1924        public void onInstallPermissionUpdated() {
1925            synchronized (mPackages) {
1926                scheduleWriteSettingsLocked();
1927            }
1928        }
1929        @Override
1930        public void onPermissionRemoved() {
1931            synchronized (mPackages) {
1932                mSettings.writeLPr();
1933            }
1934        }
1935    };
1936
1937    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1938            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1939            boolean launchedForRestore, String installerPackage,
1940            IPackageInstallObserver2 installObserver) {
1941        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1942            // Send the removed broadcasts
1943            if (res.removedInfo != null) {
1944                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1945            }
1946
1947            // Now that we successfully installed the package, grant runtime
1948            // permissions if requested before broadcasting the install. Also
1949            // for legacy apps in permission review mode we clear the permission
1950            // review flag which is used to emulate runtime permissions for
1951            // legacy apps.
1952            if (grantPermissions) {
1953                final int callingUid = Binder.getCallingUid();
1954                mPermissionManager.grantRequestedRuntimePermissions(
1955                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1956                        mPermissionCallback);
1957            }
1958
1959            final boolean update = res.removedInfo != null
1960                    && res.removedInfo.removedPackage != null;
1961            final String installerPackageName =
1962                    res.installerPackageName != null
1963                            ? res.installerPackageName
1964                            : res.removedInfo != null
1965                                    ? res.removedInfo.installerPackageName
1966                                    : null;
1967
1968            // If this is the first time we have child packages for a disabled privileged
1969            // app that had no children, we grant requested runtime permissions to the new
1970            // children if the parent on the system image had them already granted.
1971            if (res.pkg.parentPackage != null) {
1972                final int callingUid = Binder.getCallingUid();
1973                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1974                        res.pkg, callingUid, mPermissionCallback);
1975            }
1976
1977            synchronized (mPackages) {
1978                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1979            }
1980
1981            final String packageName = res.pkg.applicationInfo.packageName;
1982
1983            // Determine the set of users who are adding this package for
1984            // the first time vs. those who are seeing an update.
1985            int[] firstUserIds = EMPTY_INT_ARRAY;
1986            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1987            int[] updateUserIds = EMPTY_INT_ARRAY;
1988            int[] instantUserIds = EMPTY_INT_ARRAY;
1989            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1990            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1991            for (int newUser : res.newUsers) {
1992                final boolean isInstantApp = ps.getInstantApp(newUser);
1993                if (allNewUsers) {
1994                    if (isInstantApp) {
1995                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1996                    } else {
1997                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1998                    }
1999                    continue;
2000                }
2001                boolean isNew = true;
2002                for (int origUser : res.origUsers) {
2003                    if (origUser == newUser) {
2004                        isNew = false;
2005                        break;
2006                    }
2007                }
2008                if (isNew) {
2009                    if (isInstantApp) {
2010                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2011                    } else {
2012                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2013                    }
2014                } else {
2015                    if (isInstantApp) {
2016                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2017                    } else {
2018                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2019                    }
2020                }
2021            }
2022
2023            // Send installed broadcasts if the package is not a static shared lib.
2024            if (res.pkg.staticSharedLibName == null) {
2025                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2026
2027                // Send added for users that see the package for the first time
2028                // sendPackageAddedForNewUsers also deals with system apps
2029                int appId = UserHandle.getAppId(res.uid);
2030                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2031                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2032                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2033
2034                // Send added for users that don't see the package for the first time
2035                Bundle extras = new Bundle(1);
2036                extras.putInt(Intent.EXTRA_UID, res.uid);
2037                if (update) {
2038                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2039                }
2040                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2041                        extras, 0 /*flags*/,
2042                        null /*targetPackage*/, null /*finishedReceiver*/,
2043                        updateUserIds, instantUserIds);
2044                if (installerPackageName != null) {
2045                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2046                            extras, 0 /*flags*/,
2047                            installerPackageName, null /*finishedReceiver*/,
2048                            updateUserIds, instantUserIds);
2049                }
2050
2051                // Send replaced for users that don't see the package for the first time
2052                if (update) {
2053                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2054                            packageName, extras, 0 /*flags*/,
2055                            null /*targetPackage*/, null /*finishedReceiver*/,
2056                            updateUserIds, instantUserIds);
2057                    if (installerPackageName != null) {
2058                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2059                                extras, 0 /*flags*/,
2060                                installerPackageName, null /*finishedReceiver*/,
2061                                updateUserIds, instantUserIds);
2062                    }
2063                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2064                            null /*package*/, null /*extras*/, 0 /*flags*/,
2065                            packageName /*targetPackage*/,
2066                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2067                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2068                    // First-install and we did a restore, so we're responsible for the
2069                    // first-launch broadcast.
2070                    if (DEBUG_BACKUP) {
2071                        Slog.i(TAG, "Post-restore of " + packageName
2072                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2073                    }
2074                    sendFirstLaunchBroadcast(packageName, installerPackage,
2075                            firstUserIds, firstInstantUserIds);
2076                }
2077
2078                // Send broadcast package appeared if forward locked/external for all users
2079                // treat asec-hosted packages like removable media on upgrade
2080                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2081                    if (DEBUG_INSTALL) {
2082                        Slog.i(TAG, "upgrading pkg " + res.pkg
2083                                + " is ASEC-hosted -> AVAILABLE");
2084                    }
2085                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2086                    ArrayList<String> pkgList = new ArrayList<>(1);
2087                    pkgList.add(packageName);
2088                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2089                }
2090            }
2091
2092            // Work that needs to happen on first install within each user
2093            if (firstUserIds != null && firstUserIds.length > 0) {
2094                synchronized (mPackages) {
2095                    for (int userId : firstUserIds) {
2096                        // If this app is a browser and it's newly-installed for some
2097                        // users, clear any default-browser state in those users. The
2098                        // app's nature doesn't depend on the user, so we can just check
2099                        // its browser nature in any user and generalize.
2100                        if (packageIsBrowser(packageName, userId)) {
2101                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2102                        }
2103
2104                        // We may also need to apply pending (restored) runtime
2105                        // permission grants within these users.
2106                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2107                    }
2108                }
2109            }
2110
2111            if (allNewUsers && !update) {
2112                notifyPackageAdded(packageName);
2113            }
2114
2115            // Log current value of "unknown sources" setting
2116            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2117                    getUnknownSourcesSettings());
2118
2119            // Remove the replaced package's older resources safely now
2120            // We delete after a gc for applications  on sdcard.
2121            if (res.removedInfo != null && res.removedInfo.args != null) {
2122                Runtime.getRuntime().gc();
2123                synchronized (mInstallLock) {
2124                    res.removedInfo.args.doPostDeleteLI(true);
2125                }
2126            } else {
2127                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2128                // and not block here.
2129                VMRuntime.getRuntime().requestConcurrentGC();
2130            }
2131
2132            // Notify DexManager that the package was installed for new users.
2133            // The updated users should already be indexed and the package code paths
2134            // should not change.
2135            // Don't notify the manager for ephemeral apps as they are not expected to
2136            // survive long enough to benefit of background optimizations.
2137            for (int userId : firstUserIds) {
2138                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2139                // There's a race currently where some install events may interleave with an uninstall.
2140                // This can lead to package info being null (b/36642664).
2141                if (info != null) {
2142                    mDexManager.notifyPackageInstalled(info, userId);
2143                }
2144            }
2145        }
2146
2147        // If someone is watching installs - notify them
2148        if (installObserver != null) {
2149            try {
2150                Bundle extras = extrasForInstallResult(res);
2151                installObserver.onPackageInstalled(res.name, res.returnCode,
2152                        res.returnMsg, extras);
2153            } catch (RemoteException e) {
2154                Slog.i(TAG, "Observer no longer exists.");
2155            }
2156        }
2157    }
2158
2159    private StorageEventListener mStorageListener = new StorageEventListener() {
2160        @Override
2161        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2162            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2163                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2164                    final String volumeUuid = vol.getFsUuid();
2165
2166                    // Clean up any users or apps that were removed or recreated
2167                    // while this volume was missing
2168                    sUserManager.reconcileUsers(volumeUuid);
2169                    reconcileApps(volumeUuid);
2170
2171                    // Clean up any install sessions that expired or were
2172                    // cancelled while this volume was missing
2173                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2174
2175                    loadPrivatePackages(vol);
2176
2177                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2178                    unloadPrivatePackages(vol);
2179                }
2180            }
2181        }
2182
2183        @Override
2184        public void onVolumeForgotten(String fsUuid) {
2185            if (TextUtils.isEmpty(fsUuid)) {
2186                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2187                return;
2188            }
2189
2190            // Remove any apps installed on the forgotten volume
2191            synchronized (mPackages) {
2192                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2193                for (PackageSetting ps : packages) {
2194                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2195                    deletePackageVersioned(new VersionedPackage(ps.name,
2196                            PackageManager.VERSION_CODE_HIGHEST),
2197                            new LegacyPackageDeleteObserver(null).getBinder(),
2198                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2199                    // Try very hard to release any references to this package
2200                    // so we don't risk the system server being killed due to
2201                    // open FDs
2202                    AttributeCache.instance().removePackage(ps.name);
2203                }
2204
2205                mSettings.onVolumeForgotten(fsUuid);
2206                mSettings.writeLPr();
2207            }
2208        }
2209    };
2210
2211    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2212        Bundle extras = null;
2213        switch (res.returnCode) {
2214            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2215                extras = new Bundle();
2216                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2217                        res.origPermission);
2218                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2219                        res.origPackage);
2220                break;
2221            }
2222            case PackageManager.INSTALL_SUCCEEDED: {
2223                extras = new Bundle();
2224                extras.putBoolean(Intent.EXTRA_REPLACING,
2225                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2226                break;
2227            }
2228        }
2229        return extras;
2230    }
2231
2232    void scheduleWriteSettingsLocked() {
2233        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2234            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2235        }
2236    }
2237
2238    void scheduleWritePackageListLocked(int userId) {
2239        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2240            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2241            msg.arg1 = userId;
2242            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2243        }
2244    }
2245
2246    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2247        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2248        scheduleWritePackageRestrictionsLocked(userId);
2249    }
2250
2251    void scheduleWritePackageRestrictionsLocked(int userId) {
2252        final int[] userIds = (userId == UserHandle.USER_ALL)
2253                ? sUserManager.getUserIds() : new int[]{userId};
2254        for (int nextUserId : userIds) {
2255            if (!sUserManager.exists(nextUserId)) return;
2256            mDirtyUsers.add(nextUserId);
2257            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2258                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2259            }
2260        }
2261    }
2262
2263    public static PackageManagerService main(Context context, Installer installer,
2264            boolean factoryTest, boolean onlyCore) {
2265        // Self-check for initial settings.
2266        PackageManagerServiceCompilerMapping.checkProperties();
2267
2268        PackageManagerService m = new PackageManagerService(context, installer,
2269                factoryTest, onlyCore);
2270        m.enableSystemUserPackages();
2271        ServiceManager.addService("package", m);
2272        final PackageManagerNative pmn = m.new PackageManagerNative();
2273        ServiceManager.addService("package_native", pmn);
2274        return m;
2275    }
2276
2277    private void enableSystemUserPackages() {
2278        if (!UserManager.isSplitSystemUser()) {
2279            return;
2280        }
2281        // For system user, enable apps based on the following conditions:
2282        // - app is whitelisted or belong to one of these groups:
2283        //   -- system app which has no launcher icons
2284        //   -- system app which has INTERACT_ACROSS_USERS permission
2285        //   -- system IME app
2286        // - app is not in the blacklist
2287        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2288        Set<String> enableApps = new ArraySet<>();
2289        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2290                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2291                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2292        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2293        enableApps.addAll(wlApps);
2294        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2295                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2296        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2297        enableApps.removeAll(blApps);
2298        Log.i(TAG, "Applications installed for system user: " + enableApps);
2299        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2300                UserHandle.SYSTEM);
2301        final int allAppsSize = allAps.size();
2302        synchronized (mPackages) {
2303            for (int i = 0; i < allAppsSize; i++) {
2304                String pName = allAps.get(i);
2305                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2306                // Should not happen, but we shouldn't be failing if it does
2307                if (pkgSetting == null) {
2308                    continue;
2309                }
2310                boolean install = enableApps.contains(pName);
2311                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2312                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2313                            + " for system user");
2314                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2315                }
2316            }
2317            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2318        }
2319    }
2320
2321    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2322        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2323                Context.DISPLAY_SERVICE);
2324        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2325    }
2326
2327    /**
2328     * Requests that files preopted on a secondary system partition be copied to the data partition
2329     * if possible.  Note that the actual copying of the files is accomplished by init for security
2330     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2331     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2332     */
2333    private static void requestCopyPreoptedFiles() {
2334        final int WAIT_TIME_MS = 100;
2335        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2336        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2337            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2338            // We will wait for up to 100 seconds.
2339            final long timeStart = SystemClock.uptimeMillis();
2340            final long timeEnd = timeStart + 100 * 1000;
2341            long timeNow = timeStart;
2342            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2343                try {
2344                    Thread.sleep(WAIT_TIME_MS);
2345                } catch (InterruptedException e) {
2346                    // Do nothing
2347                }
2348                timeNow = SystemClock.uptimeMillis();
2349                if (timeNow > timeEnd) {
2350                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2351                    Slog.wtf(TAG, "cppreopt did not finish!");
2352                    break;
2353                }
2354            }
2355
2356            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2357        }
2358    }
2359
2360    public PackageManagerService(Context context, Installer installer,
2361            boolean factoryTest, boolean onlyCore) {
2362        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2363        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2364        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2365                SystemClock.uptimeMillis());
2366
2367        if (mSdkVersion <= 0) {
2368            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2369        }
2370
2371        mContext = context;
2372
2373        mFactoryTest = factoryTest;
2374        mOnlyCore = onlyCore;
2375        mMetrics = new DisplayMetrics();
2376        mInstaller = installer;
2377
2378        // Create sub-components that provide services / data. Order here is important.
2379        synchronized (mInstallLock) {
2380        synchronized (mPackages) {
2381            // Expose private service for system components to use.
2382            LocalServices.addService(
2383                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2384            sUserManager = new UserManagerService(context, this,
2385                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2386            mPermissionManager = PermissionManagerService.create(context,
2387                    new DefaultPermissionGrantedCallback() {
2388                        @Override
2389                        public void onDefaultRuntimePermissionsGranted(int userId) {
2390                            synchronized(mPackages) {
2391                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2392                            }
2393                        }
2394                    }, mPackages /*externalLock*/);
2395            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2396            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2397        }
2398        }
2399        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413
2414        String separateProcesses = SystemProperties.get("debug.separate_processes");
2415        if (separateProcesses != null && separateProcesses.length() > 0) {
2416            if ("*".equals(separateProcesses)) {
2417                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2418                mSeparateProcesses = null;
2419                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2420            } else {
2421                mDefParseFlags = 0;
2422                mSeparateProcesses = separateProcesses.split(",");
2423                Slog.w(TAG, "Running with debug.separate_processes: "
2424                        + separateProcesses);
2425            }
2426        } else {
2427            mDefParseFlags = 0;
2428            mSeparateProcesses = null;
2429        }
2430
2431        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2432                "*dexopt*");
2433        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2434                installer, mInstallLock);
2435        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2436                dexManagerListener);
2437        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2438        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2439
2440        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2441                FgThread.get().getLooper());
2442
2443        getDefaultDisplayMetrics(context, mMetrics);
2444
2445        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2446        SystemConfig systemConfig = SystemConfig.getInstance();
2447        mAvailableFeatures = systemConfig.getAvailableFeatures();
2448        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2449
2450        mProtectedPackages = new ProtectedPackages(mContext);
2451
2452        synchronized (mInstallLock) {
2453        // writer
2454        synchronized (mPackages) {
2455            mHandlerThread = new ServiceThread(TAG,
2456                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2457            mHandlerThread.start();
2458            mHandler = new PackageHandler(mHandlerThread.getLooper());
2459            mProcessLoggingHandler = new ProcessLoggingHandler();
2460            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2461            mInstantAppRegistry = new InstantAppRegistry(this);
2462
2463            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2464            final int builtInLibCount = libConfig.size();
2465            for (int i = 0; i < builtInLibCount; i++) {
2466                String name = libConfig.keyAt(i);
2467                String path = libConfig.valueAt(i);
2468                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2469                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2470            }
2471
2472            SELinuxMMAC.readInstallPolicy();
2473
2474            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2475            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2476            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2477
2478            // Clean up orphaned packages for which the code path doesn't exist
2479            // and they are an update to a system app - caused by bug/32321269
2480            final int packageSettingCount = mSettings.mPackages.size();
2481            for (int i = packageSettingCount - 1; i >= 0; i--) {
2482                PackageSetting ps = mSettings.mPackages.valueAt(i);
2483                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2484                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2485                    mSettings.mPackages.removeAt(i);
2486                    mSettings.enableSystemPackageLPw(ps.name);
2487                }
2488            }
2489
2490            if (mFirstBoot) {
2491                requestCopyPreoptedFiles();
2492            }
2493
2494            String customResolverActivity = Resources.getSystem().getString(
2495                    R.string.config_customResolverActivity);
2496            if (TextUtils.isEmpty(customResolverActivity)) {
2497                customResolverActivity = null;
2498            } else {
2499                mCustomResolverComponentName = ComponentName.unflattenFromString(
2500                        customResolverActivity);
2501            }
2502
2503            long startTime = SystemClock.uptimeMillis();
2504
2505            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2506                    startTime);
2507
2508            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2509            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2510
2511            if (bootClassPath == null) {
2512                Slog.w(TAG, "No BOOTCLASSPATH found!");
2513            }
2514
2515            if (systemServerClassPath == null) {
2516                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2517            }
2518
2519            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2520
2521            final VersionInfo ver = mSettings.getInternalVersion();
2522            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2523            if (mIsUpgrade) {
2524                logCriticalInfo(Log.INFO,
2525                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2526            }
2527
2528            // when upgrading from pre-M, promote system app permissions from install to runtime
2529            mPromoteSystemApps =
2530                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2531
2532            // When upgrading from pre-N, we need to handle package extraction like first boot,
2533            // as there is no profiling data available.
2534            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2535
2536            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2537
2538            // save off the names of pre-existing system packages prior to scanning; we don't
2539            // want to automatically grant runtime permissions for new system apps
2540            if (mPromoteSystemApps) {
2541                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2542                while (pkgSettingIter.hasNext()) {
2543                    PackageSetting ps = pkgSettingIter.next();
2544                    if (isSystemApp(ps)) {
2545                        mExistingSystemPackages.add(ps.name);
2546                    }
2547                }
2548            }
2549
2550            mCacheDir = preparePackageParserCache(mIsUpgrade);
2551
2552            // Set flag to monitor and not change apk file paths when
2553            // scanning install directories.
2554            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2555
2556            if (mIsUpgrade || mFirstBoot) {
2557                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2558            }
2559
2560            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2561            // For security and version matching reason, only consider
2562            // overlay packages if they reside in the right directory.
2563            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2564                    mDefParseFlags
2565                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2566                    scanFlags
2567                    | SCAN_AS_SYSTEM
2568                    | SCAN_AS_VENDOR,
2569                    0);
2570            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2571                    mDefParseFlags
2572                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2573                    scanFlags
2574                    | SCAN_AS_SYSTEM
2575                    | SCAN_AS_PRODUCT,
2576                    0);
2577
2578            mParallelPackageParserCallback.findStaticOverlayPackages();
2579
2580            // Find base frameworks (resource packages without code).
2581            scanDirTracedLI(frameworkDir,
2582                    mDefParseFlags
2583                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2584                    scanFlags
2585                    | SCAN_NO_DEX
2586                    | SCAN_AS_SYSTEM
2587                    | SCAN_AS_PRIVILEGED,
2588                    0);
2589
2590            // Collected privileged system packages.
2591            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2592            scanDirTracedLI(privilegedAppDir,
2593                    mDefParseFlags
2594                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2595                    scanFlags
2596                    | SCAN_AS_SYSTEM
2597                    | SCAN_AS_PRIVILEGED,
2598                    0);
2599
2600            // Collect ordinary system packages.
2601            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2602            scanDirTracedLI(systemAppDir,
2603                    mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2605                    scanFlags
2606                    | SCAN_AS_SYSTEM,
2607                    0);
2608
2609            // Collected privileged vendor packages.
2610            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2611            try {
2612                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2613            } catch (IOException e) {
2614                // failed to look up canonical path, continue with original one
2615            }
2616            scanDirTracedLI(privilegedVendorAppDir,
2617                    mDefParseFlags
2618                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2619                    scanFlags
2620                    | SCAN_AS_SYSTEM
2621                    | SCAN_AS_VENDOR
2622                    | SCAN_AS_PRIVILEGED,
2623                    0);
2624
2625            // Collect ordinary vendor packages.
2626            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2627            try {
2628                vendorAppDir = vendorAppDir.getCanonicalFile();
2629            } catch (IOException e) {
2630                // failed to look up canonical path, continue with original one
2631            }
2632            scanDirTracedLI(vendorAppDir,
2633                    mDefParseFlags
2634                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2635                    scanFlags
2636                    | SCAN_AS_SYSTEM
2637                    | SCAN_AS_VENDOR,
2638                    0);
2639
2640            // Collect all OEM packages.
2641            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2642            scanDirTracedLI(oemAppDir,
2643                    mDefParseFlags
2644                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2645                    scanFlags
2646                    | SCAN_AS_SYSTEM
2647                    | SCAN_AS_OEM,
2648                    0);
2649
2650            // Collected privileged product packages.
2651            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2652            try {
2653                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2654            } catch (IOException e) {
2655                // failed to look up canonical path, continue with original one
2656            }
2657            scanDirTracedLI(privilegedProductAppDir,
2658                    mDefParseFlags
2659                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2660                    scanFlags
2661                    | SCAN_AS_SYSTEM
2662                    | SCAN_AS_PRODUCT
2663                    | SCAN_AS_PRIVILEGED,
2664                    0);
2665
2666            // Collect ordinary product packages.
2667            File productAppDir = new File(Environment.getProductDirectory(), "app");
2668            try {
2669                productAppDir = productAppDir.getCanonicalFile();
2670            } catch (IOException e) {
2671                // failed to look up canonical path, continue with original one
2672            }
2673            scanDirTracedLI(productAppDir,
2674                    mDefParseFlags
2675                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2676                    scanFlags
2677                    | SCAN_AS_SYSTEM
2678                    | SCAN_AS_PRODUCT,
2679                    0);
2680
2681            // Prune any system packages that no longer exist.
2682            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2683            // Stub packages must either be replaced with full versions in the /data
2684            // partition or be disabled.
2685            final List<String> stubSystemApps = new ArrayList<>();
2686            if (!mOnlyCore) {
2687                // do this first before mucking with mPackages for the "expecting better" case
2688                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2689                while (pkgIterator.hasNext()) {
2690                    final PackageParser.Package pkg = pkgIterator.next();
2691                    if (pkg.isStub) {
2692                        stubSystemApps.add(pkg.packageName);
2693                    }
2694                }
2695
2696                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2697                while (psit.hasNext()) {
2698                    PackageSetting ps = psit.next();
2699
2700                    /*
2701                     * If this is not a system app, it can't be a
2702                     * disable system app.
2703                     */
2704                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2705                        continue;
2706                    }
2707
2708                    /*
2709                     * If the package is scanned, it's not erased.
2710                     */
2711                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2712                    if (scannedPkg != null) {
2713                        /*
2714                         * If the system app is both scanned and in the
2715                         * disabled packages list, then it must have been
2716                         * added via OTA. Remove it from the currently
2717                         * scanned package so the previously user-installed
2718                         * application can be scanned.
2719                         */
2720                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2721                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2722                                    + ps.name + "; removing system app.  Last known codePath="
2723                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2724                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2725                                    + scannedPkg.getLongVersionCode());
2726                            removePackageLI(scannedPkg, true);
2727                            mExpectingBetter.put(ps.name, ps.codePath);
2728                        }
2729
2730                        continue;
2731                    }
2732
2733                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2734                        psit.remove();
2735                        logCriticalInfo(Log.WARN, "System package " + ps.name
2736                                + " no longer exists; it's data will be wiped");
2737                        // Actual deletion of code and data will be handled by later
2738                        // reconciliation step
2739                    } else {
2740                        // we still have a disabled system package, but, it still might have
2741                        // been removed. check the code path still exists and check there's
2742                        // still a package. the latter can happen if an OTA keeps the same
2743                        // code path, but, changes the package name.
2744                        final PackageSetting disabledPs =
2745                                mSettings.getDisabledSystemPkgLPr(ps.name);
2746                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2747                                || disabledPs.pkg == null) {
2748if (REFACTOR_DEBUG) {
2749Slog.e("TODD",
2750        "Possibly deleted app: " + ps.dumpState_temp()
2751        + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath)
2752        + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString()));
2753}
2754                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2755                        }
2756                    }
2757                }
2758            }
2759
2760            //look for any incomplete package installations
2761            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2762            for (int i = 0; i < deletePkgsList.size(); i++) {
2763                // Actual deletion of code and data will be handled by later
2764                // reconciliation step
2765                final String packageName = deletePkgsList.get(i).name;
2766                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2767                synchronized (mPackages) {
2768                    mSettings.removePackageLPw(packageName);
2769                }
2770            }
2771
2772            //delete tmp files
2773            deleteTempPackageFiles();
2774
2775            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2776
2777            // Remove any shared userIDs that have no associated packages
2778            mSettings.pruneSharedUsersLPw();
2779            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2780            final int systemPackagesCount = mPackages.size();
2781            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2782                    + " ms, packageCount: " + systemPackagesCount
2783                    + " , timePerPackage: "
2784                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2785                    + " , cached: " + cachedSystemApps);
2786            if (mIsUpgrade && systemPackagesCount > 0) {
2787                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2788                        ((int) systemScanTime) / systemPackagesCount);
2789            }
2790            if (!mOnlyCore) {
2791                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2792                        SystemClock.uptimeMillis());
2793                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2794
2795                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2796                        | PackageParser.PARSE_FORWARD_LOCK,
2797                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2798
2799                // Remove disable package settings for updated system apps that were
2800                // removed via an OTA. If the update is no longer present, remove the
2801                // app completely. Otherwise, revoke their system privileges.
2802                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2803                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2804                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2805if (REFACTOR_DEBUG) {
2806Slog.e("TODD",
2807        "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null));
2808}
2809                    final String msg;
2810                    if (deletedPkg == null) {
2811                        // should have found an update, but, we didn't; remove everything
2812                        msg = "Updated system package " + deletedAppName
2813                                + " no longer exists; removing its data";
2814                        // Actual deletion of code and data will be handled by later
2815                        // reconciliation step
2816                    } else {
2817                        // found an update; revoke system privileges
2818                        msg = "Updated system package + " + deletedAppName
2819                                + " no longer exists; revoking system privileges";
2820
2821                        // Don't do anything if a stub is removed from the system image. If
2822                        // we were to remove the uncompressed version from the /data partition,
2823                        // this is where it'd be done.
2824
2825                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2826                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2827                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2828                    }
2829                    logCriticalInfo(Log.WARN, msg);
2830                }
2831
2832                /*
2833                 * Make sure all system apps that we expected to appear on
2834                 * the userdata partition actually showed up. If they never
2835                 * appeared, crawl back and revive the system version.
2836                 */
2837                for (int i = 0; i < mExpectingBetter.size(); i++) {
2838                    final String packageName = mExpectingBetter.keyAt(i);
2839                    if (!mPackages.containsKey(packageName)) {
2840                        final File scanFile = mExpectingBetter.valueAt(i);
2841
2842                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2843                                + " but never showed up; reverting to system");
2844
2845                        final @ParseFlags int reparseFlags;
2846                        final @ScanFlags int rescanFlags;
2847                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2848                            reparseFlags =
2849                                    mDefParseFlags |
2850                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2851                            rescanFlags =
2852                                    scanFlags
2853                                    | SCAN_AS_SYSTEM
2854                                    | SCAN_AS_PRIVILEGED;
2855                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2856                            reparseFlags =
2857                                    mDefParseFlags |
2858                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2859                            rescanFlags =
2860                                    scanFlags
2861                                    | SCAN_AS_SYSTEM;
2862                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2863                            reparseFlags =
2864                                    mDefParseFlags |
2865                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2866                            rescanFlags =
2867                                    scanFlags
2868                                    | SCAN_AS_SYSTEM
2869                                    | SCAN_AS_VENDOR
2870                                    | SCAN_AS_PRIVILEGED;
2871                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2872                            reparseFlags =
2873                                    mDefParseFlags |
2874                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2875                            rescanFlags =
2876                                    scanFlags
2877                                    | SCAN_AS_SYSTEM
2878                                    | SCAN_AS_VENDOR;
2879                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2880                            reparseFlags =
2881                                    mDefParseFlags |
2882                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2883                            rescanFlags =
2884                                    scanFlags
2885                                    | SCAN_AS_SYSTEM
2886                                    | SCAN_AS_OEM;
2887                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2888                            reparseFlags =
2889                                    mDefParseFlags |
2890                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2891                            rescanFlags =
2892                                    scanFlags
2893                                    | SCAN_AS_SYSTEM
2894                                    | SCAN_AS_PRODUCT
2895                                    | SCAN_AS_PRIVILEGED;
2896                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2897                            reparseFlags =
2898                                    mDefParseFlags |
2899                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2900                            rescanFlags =
2901                                    scanFlags
2902                                    | SCAN_AS_SYSTEM
2903                                    | SCAN_AS_PRODUCT;
2904                        } else {
2905                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2906                            continue;
2907                        }
2908
2909                        mSettings.enableSystemPackageLPw(packageName);
2910
2911                        try {
2912                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2913                        } catch (PackageManagerException e) {
2914                            Slog.e(TAG, "Failed to parse original system package: "
2915                                    + e.getMessage());
2916                        }
2917                    }
2918                }
2919
2920                // Uncompress and install any stubbed system applications.
2921                // This must be done last to ensure all stubs are replaced or disabled.
2922                decompressSystemApplications(stubSystemApps, scanFlags);
2923
2924                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2925                                - cachedSystemApps;
2926
2927                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2928                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2929                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2930                        + " ms, packageCount: " + dataPackagesCount
2931                        + " , timePerPackage: "
2932                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2933                        + " , cached: " + cachedNonSystemApps);
2934                if (mIsUpgrade && dataPackagesCount > 0) {
2935                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2936                            ((int) dataScanTime) / dataPackagesCount);
2937                }
2938            }
2939            mExpectingBetter.clear();
2940
2941            // Resolve the storage manager.
2942            mStorageManagerPackage = getStorageManagerPackageName();
2943
2944            // Resolve protected action filters. Only the setup wizard is allowed to
2945            // have a high priority filter for these actions.
2946            mSetupWizardPackage = getSetupWizardPackageName();
2947            if (mProtectedFilters.size() > 0) {
2948                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2949                    Slog.i(TAG, "No setup wizard;"
2950                        + " All protected intents capped to priority 0");
2951                }
2952                for (ActivityIntentInfo filter : mProtectedFilters) {
2953                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2954                        if (DEBUG_FILTERS) {
2955                            Slog.i(TAG, "Found setup wizard;"
2956                                + " allow priority " + filter.getPriority() + ";"
2957                                + " package: " + filter.activity.info.packageName
2958                                + " activity: " + filter.activity.className
2959                                + " priority: " + filter.getPriority());
2960                        }
2961                        // skip setup wizard; allow it to keep the high priority filter
2962                        continue;
2963                    }
2964                    if (DEBUG_FILTERS) {
2965                        Slog.i(TAG, "Protected action; cap priority to 0;"
2966                                + " package: " + filter.activity.info.packageName
2967                                + " activity: " + filter.activity.className
2968                                + " origPrio: " + filter.getPriority());
2969                    }
2970                    filter.setPriority(0);
2971                }
2972            }
2973            mDeferProtectedFilters = false;
2974            mProtectedFilters.clear();
2975
2976            // Now that we know all of the shared libraries, update all clients to have
2977            // the correct library paths.
2978            updateAllSharedLibrariesLPw(null);
2979
2980            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2981                // NOTE: We ignore potential failures here during a system scan (like
2982                // the rest of the commands above) because there's precious little we
2983                // can do about it. A settings error is reported, though.
2984                final List<String> changedAbiCodePath =
2985                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2986                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2987                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2988                        final String codePathString = changedAbiCodePath.get(i);
2989                        try {
2990                            mInstaller.rmdex(codePathString,
2991                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2992                        } catch (InstallerException ignored) {
2993                        }
2994                    }
2995                }
2996            }
2997
2998            // Now that we know all the packages we are keeping,
2999            // read and update their last usage times.
3000            mPackageUsage.read(mPackages);
3001            mCompilerStats.read();
3002
3003            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3004                    SystemClock.uptimeMillis());
3005            Slog.i(TAG, "Time to scan packages: "
3006                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3007                    + " seconds");
3008
3009            // If the platform SDK has changed since the last time we booted,
3010            // we need to re-grant app permission to catch any new ones that
3011            // appear.  This is really a hack, and means that apps can in some
3012            // cases get permissions that the user didn't initially explicitly
3013            // allow...  it would be nice to have some better way to handle
3014            // this situation.
3015            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3016            if (sdkUpdated) {
3017                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3018                        + mSdkVersion + "; regranting permissions for internal storage");
3019            }
3020            mPermissionManager.updateAllPermissions(
3021                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3022                    mPermissionCallback);
3023            ver.sdkVersion = mSdkVersion;
3024
3025            // If this is the first boot or an update from pre-M, and it is a normal
3026            // boot, then we need to initialize the default preferred apps across
3027            // all defined users.
3028            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3029                for (UserInfo user : sUserManager.getUsers(true)) {
3030                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3031                    applyFactoryDefaultBrowserLPw(user.id);
3032                    primeDomainVerificationsLPw(user.id);
3033                }
3034            }
3035
3036            // Prepare storage for system user really early during boot,
3037            // since core system apps like SettingsProvider and SystemUI
3038            // can't wait for user to start
3039            final int storageFlags;
3040            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3041                storageFlags = StorageManager.FLAG_STORAGE_DE;
3042            } else {
3043                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3044            }
3045            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3046                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3047                    true /* onlyCoreApps */);
3048            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3049                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3050                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3051                traceLog.traceBegin("AppDataFixup");
3052                try {
3053                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3054                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3055                } catch (InstallerException e) {
3056                    Slog.w(TAG, "Trouble fixing GIDs", e);
3057                }
3058                traceLog.traceEnd();
3059
3060                traceLog.traceBegin("AppDataPrepare");
3061                if (deferPackages == null || deferPackages.isEmpty()) {
3062                    return;
3063                }
3064                int count = 0;
3065                for (String pkgName : deferPackages) {
3066                    PackageParser.Package pkg = null;
3067                    synchronized (mPackages) {
3068                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3069                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3070                            pkg = ps.pkg;
3071                        }
3072                    }
3073                    if (pkg != null) {
3074                        synchronized (mInstallLock) {
3075                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3076                                    true /* maybeMigrateAppData */);
3077                        }
3078                        count++;
3079                    }
3080                }
3081                traceLog.traceEnd();
3082                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3083            }, "prepareAppData");
3084
3085            // If this is first boot after an OTA, and a normal boot, then
3086            // we need to clear code cache directories.
3087            // Note that we do *not* clear the application profiles. These remain valid
3088            // across OTAs and are used to drive profile verification (post OTA) and
3089            // profile compilation (without waiting to collect a fresh set of profiles).
3090            if (mIsUpgrade && !onlyCore) {
3091                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3092                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3093                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3094                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3095                        // No apps are running this early, so no need to freeze
3096                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3097                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3098                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3099                    }
3100                }
3101                ver.fingerprint = Build.FINGERPRINT;
3102            }
3103
3104            checkDefaultBrowser();
3105
3106            // clear only after permissions and other defaults have been updated
3107            mExistingSystemPackages.clear();
3108            mPromoteSystemApps = false;
3109
3110            // All the changes are done during package scanning.
3111            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3112
3113            // can downgrade to reader
3114            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3115            mSettings.writeLPr();
3116            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3117            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3118                    SystemClock.uptimeMillis());
3119
3120            if (!mOnlyCore) {
3121                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3122                mRequiredInstallerPackage = getRequiredInstallerLPr();
3123                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3124                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3125                if (mIntentFilterVerifierComponent != null) {
3126                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3127                            mIntentFilterVerifierComponent);
3128                } else {
3129                    mIntentFilterVerifier = null;
3130                }
3131                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3132                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3133                        SharedLibraryInfo.VERSION_UNDEFINED);
3134                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3135                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3136                        SharedLibraryInfo.VERSION_UNDEFINED);
3137            } else {
3138                mRequiredVerifierPackage = null;
3139                mRequiredInstallerPackage = null;
3140                mRequiredUninstallerPackage = null;
3141                mIntentFilterVerifierComponent = null;
3142                mIntentFilterVerifier = null;
3143                mServicesSystemSharedLibraryPackageName = null;
3144                mSharedSystemSharedLibraryPackageName = null;
3145            }
3146
3147            mInstallerService = new PackageInstallerService(context, this);
3148            final Pair<ComponentName, String> instantAppResolverComponent =
3149                    getInstantAppResolverLPr();
3150            if (instantAppResolverComponent != null) {
3151                if (DEBUG_EPHEMERAL) {
3152                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3153                }
3154                mInstantAppResolverConnection = new EphemeralResolverConnection(
3155                        mContext, instantAppResolverComponent.first,
3156                        instantAppResolverComponent.second);
3157                mInstantAppResolverSettingsComponent =
3158                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3159            } else {
3160                mInstantAppResolverConnection = null;
3161                mInstantAppResolverSettingsComponent = null;
3162            }
3163            updateInstantAppInstallerLocked(null);
3164
3165            // Read and update the usage of dex files.
3166            // Do this at the end of PM init so that all the packages have their
3167            // data directory reconciled.
3168            // At this point we know the code paths of the packages, so we can validate
3169            // the disk file and build the internal cache.
3170            // The usage file is expected to be small so loading and verifying it
3171            // should take a fairly small time compare to the other activities (e.g. package
3172            // scanning).
3173            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3174            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3175            for (int userId : currentUserIds) {
3176                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3177            }
3178            mDexManager.load(userPackages);
3179            if (mIsUpgrade) {
3180                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3181                        (int) (SystemClock.uptimeMillis() - startTime));
3182            }
3183        } // synchronized (mPackages)
3184        } // synchronized (mInstallLock)
3185
3186        // Now after opening every single application zip, make sure they
3187        // are all flushed.  Not really needed, but keeps things nice and
3188        // tidy.
3189        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3190        Runtime.getRuntime().gc();
3191        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3192
3193        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3194        FallbackCategoryProvider.loadFallbacks();
3195        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3196
3197        // The initial scanning above does many calls into installd while
3198        // holding the mPackages lock, but we're mostly interested in yelling
3199        // once we have a booted system.
3200        mInstaller.setWarnIfHeld(mPackages);
3201
3202        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3203    }
3204
3205    /**
3206     * Uncompress and install stub applications.
3207     * <p>In order to save space on the system partition, some applications are shipped in a
3208     * compressed form. In addition the compressed bits for the full application, the
3209     * system image contains a tiny stub comprised of only the Android manifest.
3210     * <p>During the first boot, attempt to uncompress and install the full application. If
3211     * the application can't be installed for any reason, disable the stub and prevent
3212     * uncompressing the full application during future boots.
3213     * <p>In order to forcefully attempt an installation of a full application, go to app
3214     * settings and enable the application.
3215     */
3216    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3217        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3218            final String pkgName = stubSystemApps.get(i);
3219            // skip if the system package is already disabled
3220            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3221                stubSystemApps.remove(i);
3222                continue;
3223            }
3224            // skip if the package isn't installed (?!); this should never happen
3225            final PackageParser.Package pkg = mPackages.get(pkgName);
3226            if (pkg == null) {
3227                stubSystemApps.remove(i);
3228                continue;
3229            }
3230            // skip if the package has been disabled by the user
3231            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3232            if (ps != null) {
3233                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3234                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3235                    stubSystemApps.remove(i);
3236                    continue;
3237                }
3238            }
3239
3240            if (DEBUG_COMPRESSION) {
3241                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3242            }
3243
3244            // uncompress the binary to its eventual destination on /data
3245            final File scanFile = decompressPackage(pkg);
3246            if (scanFile == null) {
3247                continue;
3248            }
3249
3250            // install the package to replace the stub on /system
3251            try {
3252                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3253                removePackageLI(pkg, true /*chatty*/);
3254                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3255                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3256                        UserHandle.USER_SYSTEM, "android");
3257                stubSystemApps.remove(i);
3258                continue;
3259            } catch (PackageManagerException e) {
3260                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3261            }
3262
3263            // any failed attempt to install the package will be cleaned up later
3264        }
3265
3266        // disable any stub still left; these failed to install the full application
3267        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3268            final String pkgName = stubSystemApps.get(i);
3269            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3270            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3271                    UserHandle.USER_SYSTEM, "android");
3272            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3273        }
3274    }
3275
3276    /**
3277     * Decompresses the given package on the system image onto
3278     * the /data partition.
3279     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3280     */
3281    private File decompressPackage(PackageParser.Package pkg) {
3282        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3283        if (compressedFiles == null || compressedFiles.length == 0) {
3284            if (DEBUG_COMPRESSION) {
3285                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3286            }
3287            return null;
3288        }
3289        final File dstCodePath =
3290                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3291        int ret = PackageManager.INSTALL_SUCCEEDED;
3292        try {
3293            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3294            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3295            for (File srcFile : compressedFiles) {
3296                final String srcFileName = srcFile.getName();
3297                final String dstFileName = srcFileName.substring(
3298                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3299                final File dstFile = new File(dstCodePath, dstFileName);
3300                ret = decompressFile(srcFile, dstFile);
3301                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3302                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3303                            + "; pkg: " + pkg.packageName
3304                            + ", file: " + dstFileName);
3305                    break;
3306                }
3307            }
3308        } catch (ErrnoException e) {
3309            logCriticalInfo(Log.ERROR, "Failed to decompress"
3310                    + "; pkg: " + pkg.packageName
3311                    + ", err: " + e.errno);
3312        }
3313        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3314            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3315            NativeLibraryHelper.Handle handle = null;
3316            try {
3317                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3318                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3319                        null /*abiOverride*/);
3320            } catch (IOException e) {
3321                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3322                        + "; pkg: " + pkg.packageName);
3323                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3324            } finally {
3325                IoUtils.closeQuietly(handle);
3326            }
3327        }
3328        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3329            if (dstCodePath == null || !dstCodePath.exists()) {
3330                return null;
3331            }
3332            removeCodePathLI(dstCodePath);
3333            return null;
3334        }
3335
3336        return dstCodePath;
3337    }
3338
3339    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3340        // we're only interested in updating the installer appliction when 1) it's not
3341        // already set or 2) the modified package is the installer
3342        if (mInstantAppInstallerActivity != null
3343                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3344                        .equals(modifiedPackage)) {
3345            return;
3346        }
3347        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3348    }
3349
3350    private static File preparePackageParserCache(boolean isUpgrade) {
3351        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3352            return null;
3353        }
3354
3355        // Disable package parsing on eng builds to allow for faster incremental development.
3356        if (Build.IS_ENG) {
3357            return null;
3358        }
3359
3360        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3361            Slog.i(TAG, "Disabling package parser cache due to system property.");
3362            return null;
3363        }
3364
3365        // The base directory for the package parser cache lives under /data/system/.
3366        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3367                "package_cache");
3368        if (cacheBaseDir == null) {
3369            return null;
3370        }
3371
3372        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3373        // This also serves to "GC" unused entries when the package cache version changes (which
3374        // can only happen during upgrades).
3375        if (isUpgrade) {
3376            FileUtils.deleteContents(cacheBaseDir);
3377        }
3378
3379
3380        // Return the versioned package cache directory. This is something like
3381        // "/data/system/package_cache/1"
3382        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3383
3384        // The following is a workaround to aid development on non-numbered userdebug
3385        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3386        // the system partition is newer.
3387        //
3388        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3389        // that starts with "eng." to signify that this is an engineering build and not
3390        // destined for release.
3391        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3392            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3393
3394            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3395            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3396            // in general and should not be used for production changes. In this specific case,
3397            // we know that they will work.
3398            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3399            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3400                FileUtils.deleteContents(cacheBaseDir);
3401                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3402            }
3403        }
3404
3405        return cacheDir;
3406    }
3407
3408    @Override
3409    public boolean isFirstBoot() {
3410        // allow instant applications
3411        return mFirstBoot;
3412    }
3413
3414    @Override
3415    public boolean isOnlyCoreApps() {
3416        // allow instant applications
3417        return mOnlyCore;
3418    }
3419
3420    @Override
3421    public boolean isUpgrade() {
3422        // allow instant applications
3423        // The system property allows testing ota flow when upgraded to the same image.
3424        return mIsUpgrade || SystemProperties.getBoolean(
3425                "persist.pm.mock-upgrade", false /* default */);
3426    }
3427
3428    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3429        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3430
3431        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3432                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3433                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3434        if (matches.size() == 1) {
3435            return matches.get(0).getComponentInfo().packageName;
3436        } else if (matches.size() == 0) {
3437            Log.e(TAG, "There should probably be a verifier, but, none were found");
3438            return null;
3439        }
3440        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3441    }
3442
3443    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3444        synchronized (mPackages) {
3445            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3446            if (libraryEntry == null) {
3447                throw new IllegalStateException("Missing required shared library:" + name);
3448            }
3449            return libraryEntry.apk;
3450        }
3451    }
3452
3453    private @NonNull String getRequiredInstallerLPr() {
3454        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3455        intent.addCategory(Intent.CATEGORY_DEFAULT);
3456        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3457
3458        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3459                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3460                UserHandle.USER_SYSTEM);
3461        if (matches.size() == 1) {
3462            ResolveInfo resolveInfo = matches.get(0);
3463            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3464                throw new RuntimeException("The installer must be a privileged app");
3465            }
3466            return matches.get(0).getComponentInfo().packageName;
3467        } else {
3468            throw new RuntimeException("There must be exactly one installer; found " + matches);
3469        }
3470    }
3471
3472    private @NonNull String getRequiredUninstallerLPr() {
3473        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3474        intent.addCategory(Intent.CATEGORY_DEFAULT);
3475        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3476
3477        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3478                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3479                UserHandle.USER_SYSTEM);
3480        if (resolveInfo == null ||
3481                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3482            throw new RuntimeException("There must be exactly one uninstaller; found "
3483                    + resolveInfo);
3484        }
3485        return resolveInfo.getComponentInfo().packageName;
3486    }
3487
3488    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3489        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3490
3491        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3492                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3493                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3494        ResolveInfo best = null;
3495        final int N = matches.size();
3496        for (int i = 0; i < N; i++) {
3497            final ResolveInfo cur = matches.get(i);
3498            final String packageName = cur.getComponentInfo().packageName;
3499            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3500                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3501                continue;
3502            }
3503
3504            if (best == null || cur.priority > best.priority) {
3505                best = cur;
3506            }
3507        }
3508
3509        if (best != null) {
3510            return best.getComponentInfo().getComponentName();
3511        }
3512        Slog.w(TAG, "Intent filter verifier not found");
3513        return null;
3514    }
3515
3516    @Override
3517    public @Nullable ComponentName getInstantAppResolverComponent() {
3518        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3519            return null;
3520        }
3521        synchronized (mPackages) {
3522            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3523            if (instantAppResolver == null) {
3524                return null;
3525            }
3526            return instantAppResolver.first;
3527        }
3528    }
3529
3530    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3531        final String[] packageArray =
3532                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3533        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3534            if (DEBUG_EPHEMERAL) {
3535                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3536            }
3537            return null;
3538        }
3539
3540        final int callingUid = Binder.getCallingUid();
3541        final int resolveFlags =
3542                MATCH_DIRECT_BOOT_AWARE
3543                | MATCH_DIRECT_BOOT_UNAWARE
3544                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3545        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3546        final Intent resolverIntent = new Intent(actionName);
3547        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3548                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3549        // temporarily look for the old action
3550        if (resolvers.size() == 0) {
3551            if (DEBUG_EPHEMERAL) {
3552                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3553            }
3554            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3555            resolverIntent.setAction(actionName);
3556            resolvers = queryIntentServicesInternal(resolverIntent, null,
3557                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3558        }
3559        final int N = resolvers.size();
3560        if (N == 0) {
3561            if (DEBUG_EPHEMERAL) {
3562                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3563            }
3564            return null;
3565        }
3566
3567        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3568        for (int i = 0; i < N; i++) {
3569            final ResolveInfo info = resolvers.get(i);
3570
3571            if (info.serviceInfo == null) {
3572                continue;
3573            }
3574
3575            final String packageName = info.serviceInfo.packageName;
3576            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3577                if (DEBUG_EPHEMERAL) {
3578                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3579                            + " pkg: " + packageName + ", info:" + info);
3580                }
3581                continue;
3582            }
3583
3584            if (DEBUG_EPHEMERAL) {
3585                Slog.v(TAG, "Ephemeral resolver found;"
3586                        + " pkg: " + packageName + ", info:" + info);
3587            }
3588            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3589        }
3590        if (DEBUG_EPHEMERAL) {
3591            Slog.v(TAG, "Ephemeral resolver NOT found");
3592        }
3593        return null;
3594    }
3595
3596    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3597        String[] orderedActions = Build.IS_ENG
3598                ? new String[]{
3599                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3600                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE,
3601                        Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE}
3602                : new String[]{
3603                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE,
3604                        Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE};
3605
3606        final int resolveFlags =
3607                MATCH_DIRECT_BOOT_AWARE
3608                        | MATCH_DIRECT_BOOT_UNAWARE
3609                        | Intent.FLAG_IGNORE_EPHEMERAL
3610                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3611        final Intent intent = new Intent();
3612        intent.addCategory(Intent.CATEGORY_DEFAULT);
3613        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3614        List<ResolveInfo> matches = null;
3615        for (String action : orderedActions) {
3616            intent.setAction(action);
3617            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3618                    resolveFlags, UserHandle.USER_SYSTEM);
3619            if (matches.isEmpty()) {
3620                if (DEBUG_EPHEMERAL) {
3621                    Slog.d(TAG, "Instant App installer not found with " + action);
3622                }
3623            } else {
3624                break;
3625            }
3626        }
3627        Iterator<ResolveInfo> iter = matches.iterator();
3628        while (iter.hasNext()) {
3629            final ResolveInfo rInfo = iter.next();
3630            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3631            if (ps != null) {
3632                final PermissionsState permissionsState = ps.getPermissionsState();
3633                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3634                        || Build.IS_ENG) {
3635                    continue;
3636                }
3637            }
3638            iter.remove();
3639        }
3640        if (matches.size() == 0) {
3641            return null;
3642        } else if (matches.size() == 1) {
3643            return (ActivityInfo) matches.get(0).getComponentInfo();
3644        } else {
3645            throw new RuntimeException(
3646                    "There must be at most one ephemeral installer; found " + matches);
3647        }
3648    }
3649
3650    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3651            @NonNull ComponentName resolver) {
3652        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3653                .addCategory(Intent.CATEGORY_DEFAULT)
3654                .setPackage(resolver.getPackageName());
3655        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3656        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3657                UserHandle.USER_SYSTEM);
3658        // temporarily look for the old action
3659        if (matches.isEmpty()) {
3660            if (DEBUG_EPHEMERAL) {
3661                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3662            }
3663            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3664            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3665                    UserHandle.USER_SYSTEM);
3666        }
3667        if (matches.isEmpty()) {
3668            return null;
3669        }
3670        return matches.get(0).getComponentInfo().getComponentName();
3671    }
3672
3673    private void primeDomainVerificationsLPw(int userId) {
3674        if (DEBUG_DOMAIN_VERIFICATION) {
3675            Slog.d(TAG, "Priming domain verifications in user " + userId);
3676        }
3677
3678        SystemConfig systemConfig = SystemConfig.getInstance();
3679        ArraySet<String> packages = systemConfig.getLinkedApps();
3680
3681        for (String packageName : packages) {
3682            PackageParser.Package pkg = mPackages.get(packageName);
3683            if (pkg != null) {
3684                if (!pkg.isSystem()) {
3685                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3686                    continue;
3687                }
3688
3689                ArraySet<String> domains = null;
3690                for (PackageParser.Activity a : pkg.activities) {
3691                    for (ActivityIntentInfo filter : a.intents) {
3692                        if (hasValidDomains(filter)) {
3693                            if (domains == null) {
3694                                domains = new ArraySet<String>();
3695                            }
3696                            domains.addAll(filter.getHostsList());
3697                        }
3698                    }
3699                }
3700
3701                if (domains != null && domains.size() > 0) {
3702                    if (DEBUG_DOMAIN_VERIFICATION) {
3703                        Slog.v(TAG, "      + " + packageName);
3704                    }
3705                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3706                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3707                    // and then 'always' in the per-user state actually used for intent resolution.
3708                    final IntentFilterVerificationInfo ivi;
3709                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3710                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3711                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3712                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3713                } else {
3714                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3715                            + "' does not handle web links");
3716                }
3717            } else {
3718                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3719            }
3720        }
3721
3722        scheduleWritePackageRestrictionsLocked(userId);
3723        scheduleWriteSettingsLocked();
3724    }
3725
3726    private void applyFactoryDefaultBrowserLPw(int userId) {
3727        // The default browser app's package name is stored in a string resource,
3728        // with a product-specific overlay used for vendor customization.
3729        String browserPkg = mContext.getResources().getString(
3730                com.android.internal.R.string.default_browser);
3731        if (!TextUtils.isEmpty(browserPkg)) {
3732            // non-empty string => required to be a known package
3733            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3734            if (ps == null) {
3735                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3736                browserPkg = null;
3737            } else {
3738                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3739            }
3740        }
3741
3742        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3743        // default.  If there's more than one, just leave everything alone.
3744        if (browserPkg == null) {
3745            calculateDefaultBrowserLPw(userId);
3746        }
3747    }
3748
3749    private void calculateDefaultBrowserLPw(int userId) {
3750        List<String> allBrowsers = resolveAllBrowserApps(userId);
3751        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3752        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3753    }
3754
3755    private List<String> resolveAllBrowserApps(int userId) {
3756        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3757        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3758                PackageManager.MATCH_ALL, userId);
3759
3760        final int count = list.size();
3761        List<String> result = new ArrayList<String>(count);
3762        for (int i=0; i<count; i++) {
3763            ResolveInfo info = list.get(i);
3764            if (info.activityInfo == null
3765                    || !info.handleAllWebDataURI
3766                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3767                    || result.contains(info.activityInfo.packageName)) {
3768                continue;
3769            }
3770            result.add(info.activityInfo.packageName);
3771        }
3772
3773        return result;
3774    }
3775
3776    private boolean packageIsBrowser(String packageName, int userId) {
3777        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3778                PackageManager.MATCH_ALL, userId);
3779        final int N = list.size();
3780        for (int i = 0; i < N; i++) {
3781            ResolveInfo info = list.get(i);
3782            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3783                return true;
3784            }
3785        }
3786        return false;
3787    }
3788
3789    private void checkDefaultBrowser() {
3790        final int myUserId = UserHandle.myUserId();
3791        final String packageName = getDefaultBrowserPackageName(myUserId);
3792        if (packageName != null) {
3793            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3794            if (info == null) {
3795                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3796                synchronized (mPackages) {
3797                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3798                }
3799            }
3800        }
3801    }
3802
3803    @Override
3804    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3805            throws RemoteException {
3806        try {
3807            return super.onTransact(code, data, reply, flags);
3808        } catch (RuntimeException e) {
3809            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3810                Slog.wtf(TAG, "Package Manager Crash", e);
3811            }
3812            throw e;
3813        }
3814    }
3815
3816    static int[] appendInts(int[] cur, int[] add) {
3817        if (add == null) return cur;
3818        if (cur == null) return add;
3819        final int N = add.length;
3820        for (int i=0; i<N; i++) {
3821            cur = appendInt(cur, add[i]);
3822        }
3823        return cur;
3824    }
3825
3826    /**
3827     * Returns whether or not a full application can see an instant application.
3828     * <p>
3829     * Currently, there are three cases in which this can occur:
3830     * <ol>
3831     * <li>The calling application is a "special" process. Special processes
3832     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3833     * <li>The calling application has the permission
3834     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3835     * <li>The calling application is the default launcher on the
3836     *     system partition.</li>
3837     * </ol>
3838     */
3839    private boolean canViewInstantApps(int callingUid, int userId) {
3840        if (callingUid < Process.FIRST_APPLICATION_UID) {
3841            return true;
3842        }
3843        if (mContext.checkCallingOrSelfPermission(
3844                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3845            return true;
3846        }
3847        if (mContext.checkCallingOrSelfPermission(
3848                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3849            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3850            if (homeComponent != null
3851                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3852                return true;
3853            }
3854        }
3855        return false;
3856    }
3857
3858    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3859        if (!sUserManager.exists(userId)) return null;
3860        if (ps == null) {
3861            return null;
3862        }
3863        PackageParser.Package p = ps.pkg;
3864        if (p == null) {
3865            return null;
3866        }
3867        final int callingUid = Binder.getCallingUid();
3868        // Filter out ephemeral app metadata:
3869        //   * The system/shell/root can see metadata for any app
3870        //   * An installed app can see metadata for 1) other installed apps
3871        //     and 2) ephemeral apps that have explicitly interacted with it
3872        //   * Ephemeral apps can only see their own data and exposed installed apps
3873        //   * Holding a signature permission allows seeing instant apps
3874        if (filterAppAccessLPr(ps, callingUid, userId)) {
3875            return null;
3876        }
3877
3878        final PermissionsState permissionsState = ps.getPermissionsState();
3879
3880        // Compute GIDs only if requested
3881        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3882                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3883        // Compute granted permissions only if package has requested permissions
3884        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3885                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3886        final PackageUserState state = ps.readUserState(userId);
3887
3888        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3889                && ps.isSystem()) {
3890            flags |= MATCH_ANY_USER;
3891        }
3892
3893        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3894                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3895
3896        if (packageInfo == null) {
3897            return null;
3898        }
3899
3900        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3901                resolveExternalPackageNameLPr(p);
3902
3903        return packageInfo;
3904    }
3905
3906    @Override
3907    public void checkPackageStartable(String packageName, int userId) {
3908        final int callingUid = Binder.getCallingUid();
3909        if (getInstantAppPackageName(callingUid) != null) {
3910            throw new SecurityException("Instant applications don't have access to this method");
3911        }
3912        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3913        synchronized (mPackages) {
3914            final PackageSetting ps = mSettings.mPackages.get(packageName);
3915            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3916                throw new SecurityException("Package " + packageName + " was not found!");
3917            }
3918
3919            if (!ps.getInstalled(userId)) {
3920                throw new SecurityException(
3921                        "Package " + packageName + " was not installed for user " + userId + "!");
3922            }
3923
3924            if (mSafeMode && !ps.isSystem()) {
3925                throw new SecurityException("Package " + packageName + " not a system app!");
3926            }
3927
3928            if (mFrozenPackages.contains(packageName)) {
3929                throw new SecurityException("Package " + packageName + " is currently frozen!");
3930            }
3931
3932            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3933                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3934            }
3935        }
3936    }
3937
3938    @Override
3939    public boolean isPackageAvailable(String packageName, int userId) {
3940        if (!sUserManager.exists(userId)) return false;
3941        final int callingUid = Binder.getCallingUid();
3942        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3943                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3944        synchronized (mPackages) {
3945            PackageParser.Package p = mPackages.get(packageName);
3946            if (p != null) {
3947                final PackageSetting ps = (PackageSetting) p.mExtras;
3948                if (filterAppAccessLPr(ps, callingUid, userId)) {
3949                    return false;
3950                }
3951                if (ps != null) {
3952                    final PackageUserState state = ps.readUserState(userId);
3953                    if (state != null) {
3954                        return PackageParser.isAvailable(state);
3955                    }
3956                }
3957            }
3958        }
3959        return false;
3960    }
3961
3962    @Override
3963    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3964        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3965                flags, Binder.getCallingUid(), userId);
3966    }
3967
3968    @Override
3969    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3970            int flags, int userId) {
3971        return getPackageInfoInternal(versionedPackage.getPackageName(),
3972                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3973    }
3974
3975    /**
3976     * Important: The provided filterCallingUid is used exclusively to filter out packages
3977     * that can be seen based on user state. It's typically the original caller uid prior
3978     * to clearing. Because it can only be provided by trusted code, it's value can be
3979     * trusted and will be used as-is; unlike userId which will be validated by this method.
3980     */
3981    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3982            int flags, int filterCallingUid, int userId) {
3983        if (!sUserManager.exists(userId)) return null;
3984        flags = updateFlagsForPackage(flags, userId, packageName);
3985        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3986                false /* requireFullPermission */, false /* checkShell */, "get package info");
3987
3988        // reader
3989        synchronized (mPackages) {
3990            // Normalize package name to handle renamed packages and static libs
3991            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3992
3993            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3994            if (matchFactoryOnly) {
3995                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3996                if (ps != null) {
3997                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3998                        return null;
3999                    }
4000                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4001                        return null;
4002                    }
4003                    return generatePackageInfo(ps, flags, userId);
4004                }
4005            }
4006
4007            PackageParser.Package p = mPackages.get(packageName);
4008            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4009                return null;
4010            }
4011            if (DEBUG_PACKAGE_INFO)
4012                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4013            if (p != null) {
4014                final PackageSetting ps = (PackageSetting) p.mExtras;
4015                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4016                    return null;
4017                }
4018                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4019                    return null;
4020                }
4021                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4022            }
4023            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4024                final PackageSetting ps = mSettings.mPackages.get(packageName);
4025                if (ps == null) return null;
4026                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4027                    return null;
4028                }
4029                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4030                    return null;
4031                }
4032                return generatePackageInfo(ps, flags, userId);
4033            }
4034        }
4035        return null;
4036    }
4037
4038    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4039        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4040            return true;
4041        }
4042        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4043            return true;
4044        }
4045        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4046            return true;
4047        }
4048        return false;
4049    }
4050
4051    private boolean isComponentVisibleToInstantApp(
4052            @Nullable ComponentName component, @ComponentType int type) {
4053        if (type == TYPE_ACTIVITY) {
4054            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4055            return activity != null
4056                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4057                    : false;
4058        } else if (type == TYPE_RECEIVER) {
4059            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4060            return activity != null
4061                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4062                    : false;
4063        } else if (type == TYPE_SERVICE) {
4064            final PackageParser.Service service = mServices.mServices.get(component);
4065            return service != null
4066                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4067                    : false;
4068        } else if (type == TYPE_PROVIDER) {
4069            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4070            return provider != null
4071                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4072                    : false;
4073        } else if (type == TYPE_UNKNOWN) {
4074            return isComponentVisibleToInstantApp(component);
4075        }
4076        return false;
4077    }
4078
4079    /**
4080     * Returns whether or not access to the application should be filtered.
4081     * <p>
4082     * Access may be limited based upon whether the calling or target applications
4083     * are instant applications.
4084     *
4085     * @see #canAccessInstantApps(int)
4086     */
4087    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4088            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4089        // if we're in an isolated process, get the real calling UID
4090        if (Process.isIsolated(callingUid)) {
4091            callingUid = mIsolatedOwners.get(callingUid);
4092        }
4093        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4094        final boolean callerIsInstantApp = instantAppPkgName != null;
4095        if (ps == null) {
4096            if (callerIsInstantApp) {
4097                // pretend the application exists, but, needs to be filtered
4098                return true;
4099            }
4100            return false;
4101        }
4102        // if the target and caller are the same application, don't filter
4103        if (isCallerSameApp(ps.name, callingUid)) {
4104            return false;
4105        }
4106        if (callerIsInstantApp) {
4107            // request for a specific component; if it hasn't been explicitly exposed, filter
4108            if (component != null) {
4109                return !isComponentVisibleToInstantApp(component, componentType);
4110            }
4111            // request for application; if no components have been explicitly exposed, filter
4112            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4113        }
4114        if (ps.getInstantApp(userId)) {
4115            // caller can see all components of all instant applications, don't filter
4116            if (canViewInstantApps(callingUid, userId)) {
4117                return false;
4118            }
4119            // request for a specific instant application component, filter
4120            if (component != null) {
4121                return true;
4122            }
4123            // request for an instant application; if the caller hasn't been granted access, filter
4124            return !mInstantAppRegistry.isInstantAccessGranted(
4125                    userId, UserHandle.getAppId(callingUid), ps.appId);
4126        }
4127        return false;
4128    }
4129
4130    /**
4131     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4132     */
4133    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4134        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4135    }
4136
4137    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4138            int flags) {
4139        // Callers can access only the libs they depend on, otherwise they need to explicitly
4140        // ask for the shared libraries given the caller is allowed to access all static libs.
4141        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4142            // System/shell/root get to see all static libs
4143            final int appId = UserHandle.getAppId(uid);
4144            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4145                    || appId == Process.ROOT_UID) {
4146                return false;
4147            }
4148        }
4149
4150        // No package means no static lib as it is always on internal storage
4151        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4152            return false;
4153        }
4154
4155        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4156                ps.pkg.staticSharedLibVersion);
4157        if (libEntry == null) {
4158            return false;
4159        }
4160
4161        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4162        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4163        if (uidPackageNames == null) {
4164            return true;
4165        }
4166
4167        for (String uidPackageName : uidPackageNames) {
4168            if (ps.name.equals(uidPackageName)) {
4169                return false;
4170            }
4171            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4172            if (uidPs != null) {
4173                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4174                        libEntry.info.getName());
4175                if (index < 0) {
4176                    continue;
4177                }
4178                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4179                    return false;
4180                }
4181            }
4182        }
4183        return true;
4184    }
4185
4186    @Override
4187    public String[] currentToCanonicalPackageNames(String[] names) {
4188        final int callingUid = Binder.getCallingUid();
4189        if (getInstantAppPackageName(callingUid) != null) {
4190            return names;
4191        }
4192        final String[] out = new String[names.length];
4193        // reader
4194        synchronized (mPackages) {
4195            final int callingUserId = UserHandle.getUserId(callingUid);
4196            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4197            for (int i=names.length-1; i>=0; i--) {
4198                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4199                boolean translateName = false;
4200                if (ps != null && ps.realName != null) {
4201                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4202                    translateName = !targetIsInstantApp
4203                            || canViewInstantApps
4204                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4205                                    UserHandle.getAppId(callingUid), ps.appId);
4206                }
4207                out[i] = translateName ? ps.realName : names[i];
4208            }
4209        }
4210        return out;
4211    }
4212
4213    @Override
4214    public String[] canonicalToCurrentPackageNames(String[] names) {
4215        final int callingUid = Binder.getCallingUid();
4216        if (getInstantAppPackageName(callingUid) != null) {
4217            return names;
4218        }
4219        final String[] out = new String[names.length];
4220        // reader
4221        synchronized (mPackages) {
4222            final int callingUserId = UserHandle.getUserId(callingUid);
4223            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4224            for (int i=names.length-1; i>=0; i--) {
4225                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4226                boolean translateName = false;
4227                if (cur != null) {
4228                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4229                    final boolean targetIsInstantApp =
4230                            ps != null && ps.getInstantApp(callingUserId);
4231                    translateName = !targetIsInstantApp
4232                            || canViewInstantApps
4233                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4234                                    UserHandle.getAppId(callingUid), ps.appId);
4235                }
4236                out[i] = translateName ? cur : names[i];
4237            }
4238        }
4239        return out;
4240    }
4241
4242    @Override
4243    public int getPackageUid(String packageName, int flags, int userId) {
4244        if (!sUserManager.exists(userId)) return -1;
4245        final int callingUid = Binder.getCallingUid();
4246        flags = updateFlagsForPackage(flags, userId, packageName);
4247        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4248                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4249
4250        // reader
4251        synchronized (mPackages) {
4252            final PackageParser.Package p = mPackages.get(packageName);
4253            if (p != null && p.isMatch(flags)) {
4254                PackageSetting ps = (PackageSetting) p.mExtras;
4255                if (filterAppAccessLPr(ps, callingUid, userId)) {
4256                    return -1;
4257                }
4258                return UserHandle.getUid(userId, p.applicationInfo.uid);
4259            }
4260            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4261                final PackageSetting ps = mSettings.mPackages.get(packageName);
4262                if (ps != null && ps.isMatch(flags)
4263                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4264                    return UserHandle.getUid(userId, ps.appId);
4265                }
4266            }
4267        }
4268
4269        return -1;
4270    }
4271
4272    @Override
4273    public int[] getPackageGids(String packageName, int flags, int userId) {
4274        if (!sUserManager.exists(userId)) return null;
4275        final int callingUid = Binder.getCallingUid();
4276        flags = updateFlagsForPackage(flags, userId, packageName);
4277        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4278                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4279
4280        // reader
4281        synchronized (mPackages) {
4282            final PackageParser.Package p = mPackages.get(packageName);
4283            if (p != null && p.isMatch(flags)) {
4284                PackageSetting ps = (PackageSetting) p.mExtras;
4285                if (filterAppAccessLPr(ps, callingUid, userId)) {
4286                    return null;
4287                }
4288                // TODO: Shouldn't this be checking for package installed state for userId and
4289                // return null?
4290                return ps.getPermissionsState().computeGids(userId);
4291            }
4292            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4293                final PackageSetting ps = mSettings.mPackages.get(packageName);
4294                if (ps != null && ps.isMatch(flags)
4295                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4296                    return ps.getPermissionsState().computeGids(userId);
4297                }
4298            }
4299        }
4300
4301        return null;
4302    }
4303
4304    @Override
4305    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4306        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4307    }
4308
4309    @Override
4310    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4311            int flags) {
4312        final List<PermissionInfo> permissionList =
4313                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4314        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4315    }
4316
4317    @Override
4318    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4319        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4320    }
4321
4322    @Override
4323    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4324        final List<PermissionGroupInfo> permissionList =
4325                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4326        return (permissionList == null)
4327                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4328    }
4329
4330    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4331            int filterCallingUid, int userId) {
4332        if (!sUserManager.exists(userId)) return null;
4333        PackageSetting ps = mSettings.mPackages.get(packageName);
4334        if (ps != null) {
4335            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4336                return null;
4337            }
4338            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4339                return null;
4340            }
4341            if (ps.pkg == null) {
4342                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4343                if (pInfo != null) {
4344                    return pInfo.applicationInfo;
4345                }
4346                return null;
4347            }
4348            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4349                    ps.readUserState(userId), userId);
4350            if (ai != null) {
4351                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4352            }
4353            return ai;
4354        }
4355        return null;
4356    }
4357
4358    @Override
4359    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4360        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4361    }
4362
4363    /**
4364     * Important: The provided filterCallingUid is used exclusively to filter out applications
4365     * that can be seen based on user state. It's typically the original caller uid prior
4366     * to clearing. Because it can only be provided by trusted code, it's value can be
4367     * trusted and will be used as-is; unlike userId which will be validated by this method.
4368     */
4369    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4370            int filterCallingUid, int userId) {
4371        if (!sUserManager.exists(userId)) return null;
4372        flags = updateFlagsForApplication(flags, userId, packageName);
4373        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4374                false /* requireFullPermission */, false /* checkShell */, "get application info");
4375
4376        // writer
4377        synchronized (mPackages) {
4378            // Normalize package name to handle renamed packages and static libs
4379            packageName = resolveInternalPackageNameLPr(packageName,
4380                    PackageManager.VERSION_CODE_HIGHEST);
4381
4382            PackageParser.Package p = mPackages.get(packageName);
4383            if (DEBUG_PACKAGE_INFO) Log.v(
4384                    TAG, "getApplicationInfo " + packageName
4385                    + ": " + p);
4386            if (p != null) {
4387                PackageSetting ps = mSettings.mPackages.get(packageName);
4388                if (ps == null) return null;
4389                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4390                    return null;
4391                }
4392                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4393                    return null;
4394                }
4395                // Note: isEnabledLP() does not apply here - always return info
4396                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4397                        p, flags, ps.readUserState(userId), userId);
4398                if (ai != null) {
4399                    ai.packageName = resolveExternalPackageNameLPr(p);
4400                }
4401                return ai;
4402            }
4403            if ("android".equals(packageName)||"system".equals(packageName)) {
4404                return mAndroidApplication;
4405            }
4406            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4407                // Already generates the external package name
4408                return generateApplicationInfoFromSettingsLPw(packageName,
4409                        flags, filterCallingUid, userId);
4410            }
4411        }
4412        return null;
4413    }
4414
4415    private String normalizePackageNameLPr(String packageName) {
4416        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4417        return normalizedPackageName != null ? normalizedPackageName : packageName;
4418    }
4419
4420    @Override
4421    public void deletePreloadsFileCache() {
4422        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4423            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4424        }
4425        File dir = Environment.getDataPreloadsFileCacheDirectory();
4426        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4427        FileUtils.deleteContents(dir);
4428    }
4429
4430    @Override
4431    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4432            final int storageFlags, final IPackageDataObserver observer) {
4433        mContext.enforceCallingOrSelfPermission(
4434                android.Manifest.permission.CLEAR_APP_CACHE, null);
4435        mHandler.post(() -> {
4436            boolean success = false;
4437            try {
4438                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4439                success = true;
4440            } catch (IOException e) {
4441                Slog.w(TAG, e);
4442            }
4443            if (observer != null) {
4444                try {
4445                    observer.onRemoveCompleted(null, success);
4446                } catch (RemoteException e) {
4447                    Slog.w(TAG, e);
4448                }
4449            }
4450        });
4451    }
4452
4453    @Override
4454    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4455            final int storageFlags, final IntentSender pi) {
4456        mContext.enforceCallingOrSelfPermission(
4457                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4458        mHandler.post(() -> {
4459            boolean success = false;
4460            try {
4461                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4462                success = true;
4463            } catch (IOException e) {
4464                Slog.w(TAG, e);
4465            }
4466            if (pi != null) {
4467                try {
4468                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4469                } catch (SendIntentException e) {
4470                    Slog.w(TAG, e);
4471                }
4472            }
4473        });
4474    }
4475
4476    /**
4477     * Blocking call to clear various types of cached data across the system
4478     * until the requested bytes are available.
4479     */
4480    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4481        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4482        final File file = storage.findPathForUuid(volumeUuid);
4483        if (file.getUsableSpace() >= bytes) return;
4484
4485        if (ENABLE_FREE_CACHE_V2) {
4486            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4487                    volumeUuid);
4488            final boolean aggressive = (storageFlags
4489                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4490            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4491
4492            // 1. Pre-flight to determine if we have any chance to succeed
4493            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4494            if (internalVolume && (aggressive || SystemProperties
4495                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4496                deletePreloadsFileCache();
4497                if (file.getUsableSpace() >= bytes) return;
4498            }
4499
4500            // 3. Consider parsed APK data (aggressive only)
4501            if (internalVolume && aggressive) {
4502                FileUtils.deleteContents(mCacheDir);
4503                if (file.getUsableSpace() >= bytes) return;
4504            }
4505
4506            // 4. Consider cached app data (above quotas)
4507            try {
4508                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4509                        Installer.FLAG_FREE_CACHE_V2);
4510            } catch (InstallerException ignored) {
4511            }
4512            if (file.getUsableSpace() >= bytes) return;
4513
4514            // 5. Consider shared libraries with refcount=0 and age>min cache period
4515            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4516                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4517                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4518                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4519                return;
4520            }
4521
4522            // 6. Consider dexopt output (aggressive only)
4523            // TODO: Implement
4524
4525            // 7. Consider installed instant apps unused longer than min cache period
4526            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4527                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4528                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4529                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4530                return;
4531            }
4532
4533            // 8. Consider cached app data (below quotas)
4534            try {
4535                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4536                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4537            } catch (InstallerException ignored) {
4538            }
4539            if (file.getUsableSpace() >= bytes) return;
4540
4541            // 9. Consider DropBox entries
4542            // TODO: Implement
4543
4544            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4545            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4546                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4547                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4548                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4549                return;
4550            }
4551        } else {
4552            try {
4553                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4554            } catch (InstallerException ignored) {
4555            }
4556            if (file.getUsableSpace() >= bytes) return;
4557        }
4558
4559        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4560    }
4561
4562    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4563            throws IOException {
4564        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4565        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4566
4567        List<VersionedPackage> packagesToDelete = null;
4568        final long now = System.currentTimeMillis();
4569
4570        synchronized (mPackages) {
4571            final int[] allUsers = sUserManager.getUserIds();
4572            final int libCount = mSharedLibraries.size();
4573            for (int i = 0; i < libCount; i++) {
4574                final LongSparseArray<SharedLibraryEntry> versionedLib
4575                        = mSharedLibraries.valueAt(i);
4576                if (versionedLib == null) {
4577                    continue;
4578                }
4579                final int versionCount = versionedLib.size();
4580                for (int j = 0; j < versionCount; j++) {
4581                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4582                    // Skip packages that are not static shared libs.
4583                    if (!libInfo.isStatic()) {
4584                        break;
4585                    }
4586                    // Important: We skip static shared libs used for some user since
4587                    // in such a case we need to keep the APK on the device. The check for
4588                    // a lib being used for any user is performed by the uninstall call.
4589                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4590                    // Resolve the package name - we use synthetic package names internally
4591                    final String internalPackageName = resolveInternalPackageNameLPr(
4592                            declaringPackage.getPackageName(),
4593                            declaringPackage.getLongVersionCode());
4594                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4595                    // Skip unused static shared libs cached less than the min period
4596                    // to prevent pruning a lib needed by a subsequently installed package.
4597                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4598                        continue;
4599                    }
4600                    if (packagesToDelete == null) {
4601                        packagesToDelete = new ArrayList<>();
4602                    }
4603                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4604                            declaringPackage.getLongVersionCode()));
4605                }
4606            }
4607        }
4608
4609        if (packagesToDelete != null) {
4610            final int packageCount = packagesToDelete.size();
4611            for (int i = 0; i < packageCount; i++) {
4612                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4613                // Delete the package synchronously (will fail of the lib used for any user).
4614                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4615                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4616                                == PackageManager.DELETE_SUCCEEDED) {
4617                    if (volume.getUsableSpace() >= neededSpace) {
4618                        return true;
4619                    }
4620                }
4621            }
4622        }
4623
4624        return false;
4625    }
4626
4627    /**
4628     * Update given flags based on encryption status of current user.
4629     */
4630    private int updateFlags(int flags, int userId) {
4631        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4632                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4633            // Caller expressed an explicit opinion about what encryption
4634            // aware/unaware components they want to see, so fall through and
4635            // give them what they want
4636        } else {
4637            // Caller expressed no opinion, so match based on user state
4638            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4639                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4640            } else {
4641                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4642            }
4643        }
4644        return flags;
4645    }
4646
4647    private UserManagerInternal getUserManagerInternal() {
4648        if (mUserManagerInternal == null) {
4649            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4650        }
4651        return mUserManagerInternal;
4652    }
4653
4654    private ActivityManagerInternal getActivityManagerInternal() {
4655        if (mActivityManagerInternal == null) {
4656            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4657        }
4658        return mActivityManagerInternal;
4659    }
4660
4661
4662    private DeviceIdleController.LocalService getDeviceIdleController() {
4663        if (mDeviceIdleController == null) {
4664            mDeviceIdleController =
4665                    LocalServices.getService(DeviceIdleController.LocalService.class);
4666        }
4667        return mDeviceIdleController;
4668    }
4669
4670    /**
4671     * Update given flags when being used to request {@link PackageInfo}.
4672     */
4673    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4674        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4675        boolean triaged = true;
4676        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4677                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4678            // Caller is asking for component details, so they'd better be
4679            // asking for specific encryption matching behavior, or be triaged
4680            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4681                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4682                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4683                triaged = false;
4684            }
4685        }
4686        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4687                | PackageManager.MATCH_SYSTEM_ONLY
4688                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4689            triaged = false;
4690        }
4691        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4692            mPermissionManager.enforceCrossUserPermission(
4693                    Binder.getCallingUid(), userId, false, false,
4694                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4695                    + Debug.getCallers(5));
4696        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4697                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4698            // If the caller wants all packages and has a restricted profile associated with it,
4699            // then match all users. This is to make sure that launchers that need to access work
4700            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4701            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4702            flags |= PackageManager.MATCH_ANY_USER;
4703        }
4704        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4705            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4706                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4707        }
4708        return updateFlags(flags, userId);
4709    }
4710
4711    /**
4712     * Update given flags when being used to request {@link ApplicationInfo}.
4713     */
4714    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4715        return updateFlagsForPackage(flags, userId, cookie);
4716    }
4717
4718    /**
4719     * Update given flags when being used to request {@link ComponentInfo}.
4720     */
4721    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4722        if (cookie instanceof Intent) {
4723            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4724                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4725            }
4726        }
4727
4728        boolean triaged = true;
4729        // Caller is asking for component details, so they'd better be
4730        // asking for specific encryption matching behavior, or be triaged
4731        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4732                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4733                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4734            triaged = false;
4735        }
4736        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4737            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4738                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4739        }
4740
4741        return updateFlags(flags, userId);
4742    }
4743
4744    /**
4745     * Update given intent when being used to request {@link ResolveInfo}.
4746     */
4747    private Intent updateIntentForResolve(Intent intent) {
4748        if (intent.getSelector() != null) {
4749            intent = intent.getSelector();
4750        }
4751        if (DEBUG_PREFERRED) {
4752            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4753        }
4754        return intent;
4755    }
4756
4757    /**
4758     * Update given flags when being used to request {@link ResolveInfo}.
4759     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4760     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4761     * flag set. However, this flag is only honoured in three circumstances:
4762     * <ul>
4763     * <li>when called from a system process</li>
4764     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4765     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4766     * action and a {@code android.intent.category.BROWSABLE} category</li>
4767     * </ul>
4768     */
4769    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4770        return updateFlagsForResolve(flags, userId, intent, callingUid,
4771                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4772    }
4773    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4774            boolean wantInstantApps) {
4775        return updateFlagsForResolve(flags, userId, intent, callingUid,
4776                wantInstantApps, false /*onlyExposedExplicitly*/);
4777    }
4778    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4779            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4780        // Safe mode means we shouldn't match any third-party components
4781        if (mSafeMode) {
4782            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4783        }
4784        if (getInstantAppPackageName(callingUid) != null) {
4785            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4786            if (onlyExposedExplicitly) {
4787                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4788            }
4789            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4790            flags |= PackageManager.MATCH_INSTANT;
4791        } else {
4792            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4793            final boolean allowMatchInstant = wantInstantApps
4794                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4795            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4796                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4797            if (!allowMatchInstant) {
4798                flags &= ~PackageManager.MATCH_INSTANT;
4799            }
4800        }
4801        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4802    }
4803
4804    @Override
4805    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4806        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4807    }
4808
4809    /**
4810     * Important: The provided filterCallingUid is used exclusively to filter out activities
4811     * that can be seen based on user state. It's typically the original caller uid prior
4812     * to clearing. Because it can only be provided by trusted code, it's value can be
4813     * trusted and will be used as-is; unlike userId which will be validated by this method.
4814     */
4815    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4816            int filterCallingUid, int userId) {
4817        if (!sUserManager.exists(userId)) return null;
4818        flags = updateFlagsForComponent(flags, userId, component);
4819
4820        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4821            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4822                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4823        }
4824
4825        synchronized (mPackages) {
4826            PackageParser.Activity a = mActivities.mActivities.get(component);
4827
4828            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4829            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4830                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4831                if (ps == null) return null;
4832                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4833                    return null;
4834                }
4835                return PackageParser.generateActivityInfo(
4836                        a, flags, ps.readUserState(userId), userId);
4837            }
4838            if (mResolveComponentName.equals(component)) {
4839                return PackageParser.generateActivityInfo(
4840                        mResolveActivity, flags, new PackageUserState(), userId);
4841            }
4842        }
4843        return null;
4844    }
4845
4846    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4847        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4848            return false;
4849        }
4850        final long token = Binder.clearCallingIdentity();
4851        try {
4852            final int callingUserId = UserHandle.getUserId(callingUid);
4853            if (ActivityManager.getCurrentUser() != callingUserId) {
4854                return false;
4855            }
4856            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4857        } finally {
4858            Binder.restoreCallingIdentity(token);
4859        }
4860    }
4861
4862    @Override
4863    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4864            String resolvedType) {
4865        synchronized (mPackages) {
4866            if (component.equals(mResolveComponentName)) {
4867                // The resolver supports EVERYTHING!
4868                return true;
4869            }
4870            final int callingUid = Binder.getCallingUid();
4871            final int callingUserId = UserHandle.getUserId(callingUid);
4872            PackageParser.Activity a = mActivities.mActivities.get(component);
4873            if (a == null) {
4874                return false;
4875            }
4876            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4877            if (ps == null) {
4878                return false;
4879            }
4880            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4881                return false;
4882            }
4883            for (int i=0; i<a.intents.size(); i++) {
4884                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4885                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4886                    return true;
4887                }
4888            }
4889            return false;
4890        }
4891    }
4892
4893    @Override
4894    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4895        if (!sUserManager.exists(userId)) return null;
4896        final int callingUid = Binder.getCallingUid();
4897        flags = updateFlagsForComponent(flags, userId, component);
4898        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4899                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4900        synchronized (mPackages) {
4901            PackageParser.Activity a = mReceivers.mActivities.get(component);
4902            if (DEBUG_PACKAGE_INFO) Log.v(
4903                TAG, "getReceiverInfo " + component + ": " + a);
4904            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4905                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4906                if (ps == null) return null;
4907                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4908                    return null;
4909                }
4910                return PackageParser.generateActivityInfo(
4911                        a, flags, ps.readUserState(userId), userId);
4912            }
4913        }
4914        return null;
4915    }
4916
4917    @Override
4918    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4919            int flags, int userId) {
4920        if (!sUserManager.exists(userId)) return null;
4921        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4922        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4923            return null;
4924        }
4925
4926        flags = updateFlagsForPackage(flags, userId, null);
4927
4928        final boolean canSeeStaticLibraries =
4929                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4930                        == PERMISSION_GRANTED
4931                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4932                        == PERMISSION_GRANTED
4933                || canRequestPackageInstallsInternal(packageName,
4934                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4935                        false  /* throwIfPermNotDeclared*/)
4936                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4937                        == PERMISSION_GRANTED;
4938
4939        synchronized (mPackages) {
4940            List<SharedLibraryInfo> result = null;
4941
4942            final int libCount = mSharedLibraries.size();
4943            for (int i = 0; i < libCount; i++) {
4944                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4945                if (versionedLib == null) {
4946                    continue;
4947                }
4948
4949                final int versionCount = versionedLib.size();
4950                for (int j = 0; j < versionCount; j++) {
4951                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4952                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4953                        break;
4954                    }
4955                    final long identity = Binder.clearCallingIdentity();
4956                    try {
4957                        PackageInfo packageInfo = getPackageInfoVersioned(
4958                                libInfo.getDeclaringPackage(), flags
4959                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4960                        if (packageInfo == null) {
4961                            continue;
4962                        }
4963                    } finally {
4964                        Binder.restoreCallingIdentity(identity);
4965                    }
4966
4967                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4968                            libInfo.getLongVersion(), libInfo.getType(),
4969                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4970                            flags, userId));
4971
4972                    if (result == null) {
4973                        result = new ArrayList<>();
4974                    }
4975                    result.add(resLibInfo);
4976                }
4977            }
4978
4979            return result != null ? new ParceledListSlice<>(result) : null;
4980        }
4981    }
4982
4983    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4984            SharedLibraryInfo libInfo, int flags, int userId) {
4985        List<VersionedPackage> versionedPackages = null;
4986        final int packageCount = mSettings.mPackages.size();
4987        for (int i = 0; i < packageCount; i++) {
4988            PackageSetting ps = mSettings.mPackages.valueAt(i);
4989
4990            if (ps == null) {
4991                continue;
4992            }
4993
4994            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4995                continue;
4996            }
4997
4998            final String libName = libInfo.getName();
4999            if (libInfo.isStatic()) {
5000                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5001                if (libIdx < 0) {
5002                    continue;
5003                }
5004                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5005                    continue;
5006                }
5007                if (versionedPackages == null) {
5008                    versionedPackages = new ArrayList<>();
5009                }
5010                // If the dependent is a static shared lib, use the public package name
5011                String dependentPackageName = ps.name;
5012                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5013                    dependentPackageName = ps.pkg.manifestPackageName;
5014                }
5015                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5016            } else if (ps.pkg != null) {
5017                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5018                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5019                    if (versionedPackages == null) {
5020                        versionedPackages = new ArrayList<>();
5021                    }
5022                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5023                }
5024            }
5025        }
5026
5027        return versionedPackages;
5028    }
5029
5030    @Override
5031    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5032        if (!sUserManager.exists(userId)) return null;
5033        final int callingUid = Binder.getCallingUid();
5034        flags = updateFlagsForComponent(flags, userId, component);
5035        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5036                false /* requireFullPermission */, false /* checkShell */, "get service info");
5037        synchronized (mPackages) {
5038            PackageParser.Service s = mServices.mServices.get(component);
5039            if (DEBUG_PACKAGE_INFO) Log.v(
5040                TAG, "getServiceInfo " + component + ": " + s);
5041            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5042                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5043                if (ps == null) return null;
5044                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5045                    return null;
5046                }
5047                return PackageParser.generateServiceInfo(
5048                        s, flags, ps.readUserState(userId), userId);
5049            }
5050        }
5051        return null;
5052    }
5053
5054    @Override
5055    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5056        if (!sUserManager.exists(userId)) return null;
5057        final int callingUid = Binder.getCallingUid();
5058        flags = updateFlagsForComponent(flags, userId, component);
5059        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5060                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5061        synchronized (mPackages) {
5062            PackageParser.Provider p = mProviders.mProviders.get(component);
5063            if (DEBUG_PACKAGE_INFO) Log.v(
5064                TAG, "getProviderInfo " + component + ": " + p);
5065            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5066                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5067                if (ps == null) return null;
5068                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5069                    return null;
5070                }
5071                return PackageParser.generateProviderInfo(
5072                        p, flags, ps.readUserState(userId), userId);
5073            }
5074        }
5075        return null;
5076    }
5077
5078    @Override
5079    public String[] getSystemSharedLibraryNames() {
5080        // allow instant applications
5081        synchronized (mPackages) {
5082            Set<String> libs = null;
5083            final int libCount = mSharedLibraries.size();
5084            for (int i = 0; i < libCount; i++) {
5085                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5086                if (versionedLib == null) {
5087                    continue;
5088                }
5089                final int versionCount = versionedLib.size();
5090                for (int j = 0; j < versionCount; j++) {
5091                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5092                    if (!libEntry.info.isStatic()) {
5093                        if (libs == null) {
5094                            libs = new ArraySet<>();
5095                        }
5096                        libs.add(libEntry.info.getName());
5097                        break;
5098                    }
5099                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5100                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5101                            UserHandle.getUserId(Binder.getCallingUid()),
5102                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5103                        if (libs == null) {
5104                            libs = new ArraySet<>();
5105                        }
5106                        libs.add(libEntry.info.getName());
5107                        break;
5108                    }
5109                }
5110            }
5111
5112            if (libs != null) {
5113                String[] libsArray = new String[libs.size()];
5114                libs.toArray(libsArray);
5115                return libsArray;
5116            }
5117
5118            return null;
5119        }
5120    }
5121
5122    @Override
5123    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5124        // allow instant applications
5125        synchronized (mPackages) {
5126            return mServicesSystemSharedLibraryPackageName;
5127        }
5128    }
5129
5130    @Override
5131    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5132        // allow instant applications
5133        synchronized (mPackages) {
5134            return mSharedSystemSharedLibraryPackageName;
5135        }
5136    }
5137
5138    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5139        for (int i = userList.length - 1; i >= 0; --i) {
5140            final int userId = userList[i];
5141            // don't add instant app to the list of updates
5142            if (pkgSetting.getInstantApp(userId)) {
5143                continue;
5144            }
5145            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5146            if (changedPackages == null) {
5147                changedPackages = new SparseArray<>();
5148                mChangedPackages.put(userId, changedPackages);
5149            }
5150            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5151            if (sequenceNumbers == null) {
5152                sequenceNumbers = new HashMap<>();
5153                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5154            }
5155            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5156            if (sequenceNumber != null) {
5157                changedPackages.remove(sequenceNumber);
5158            }
5159            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5160            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5161        }
5162        mChangedPackagesSequenceNumber++;
5163    }
5164
5165    @Override
5166    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5167        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5168            return null;
5169        }
5170        synchronized (mPackages) {
5171            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5172                return null;
5173            }
5174            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5175            if (changedPackages == null) {
5176                return null;
5177            }
5178            final List<String> packageNames =
5179                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5180            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5181                final String packageName = changedPackages.get(i);
5182                if (packageName != null) {
5183                    packageNames.add(packageName);
5184                }
5185            }
5186            return packageNames.isEmpty()
5187                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5188        }
5189    }
5190
5191    @Override
5192    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5193        // allow instant applications
5194        ArrayList<FeatureInfo> res;
5195        synchronized (mAvailableFeatures) {
5196            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5197            res.addAll(mAvailableFeatures.values());
5198        }
5199        final FeatureInfo fi = new FeatureInfo();
5200        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5201                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5202        res.add(fi);
5203
5204        return new ParceledListSlice<>(res);
5205    }
5206
5207    @Override
5208    public boolean hasSystemFeature(String name, int version) {
5209        // allow instant applications
5210        synchronized (mAvailableFeatures) {
5211            final FeatureInfo feat = mAvailableFeatures.get(name);
5212            if (feat == null) {
5213                return false;
5214            } else {
5215                return feat.version >= version;
5216            }
5217        }
5218    }
5219
5220    @Override
5221    public int checkPermission(String permName, String pkgName, int userId) {
5222        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5223    }
5224
5225    @Override
5226    public int checkUidPermission(String permName, int uid) {
5227        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5228    }
5229
5230    @Override
5231    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5232        if (UserHandle.getCallingUserId() != userId) {
5233            mContext.enforceCallingPermission(
5234                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5235                    "isPermissionRevokedByPolicy for user " + userId);
5236        }
5237
5238        if (checkPermission(permission, packageName, userId)
5239                == PackageManager.PERMISSION_GRANTED) {
5240            return false;
5241        }
5242
5243        final int callingUid = Binder.getCallingUid();
5244        if (getInstantAppPackageName(callingUid) != null) {
5245            if (!isCallerSameApp(packageName, callingUid)) {
5246                return false;
5247            }
5248        } else {
5249            if (isInstantApp(packageName, userId)) {
5250                return false;
5251            }
5252        }
5253
5254        final long identity = Binder.clearCallingIdentity();
5255        try {
5256            final int flags = getPermissionFlags(permission, packageName, userId);
5257            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5258        } finally {
5259            Binder.restoreCallingIdentity(identity);
5260        }
5261    }
5262
5263    @Override
5264    public String getPermissionControllerPackageName() {
5265        synchronized (mPackages) {
5266            return mRequiredInstallerPackage;
5267        }
5268    }
5269
5270    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5271        return mPermissionManager.addDynamicPermission(
5272                info, async, getCallingUid(), new PermissionCallback() {
5273                    @Override
5274                    public void onPermissionChanged() {
5275                        if (!async) {
5276                            mSettings.writeLPr();
5277                        } else {
5278                            scheduleWriteSettingsLocked();
5279                        }
5280                    }
5281                });
5282    }
5283
5284    @Override
5285    public boolean addPermission(PermissionInfo info) {
5286        synchronized (mPackages) {
5287            return addDynamicPermission(info, false);
5288        }
5289    }
5290
5291    @Override
5292    public boolean addPermissionAsync(PermissionInfo info) {
5293        synchronized (mPackages) {
5294            return addDynamicPermission(info, true);
5295        }
5296    }
5297
5298    @Override
5299    public void removePermission(String permName) {
5300        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5301    }
5302
5303    @Override
5304    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5305        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5306                getCallingUid(), userId, mPermissionCallback);
5307    }
5308
5309    @Override
5310    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5311        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5312                getCallingUid(), userId, mPermissionCallback);
5313    }
5314
5315    @Override
5316    public void resetRuntimePermissions() {
5317        mContext.enforceCallingOrSelfPermission(
5318                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5319                "revokeRuntimePermission");
5320
5321        int callingUid = Binder.getCallingUid();
5322        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5323            mContext.enforceCallingOrSelfPermission(
5324                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5325                    "resetRuntimePermissions");
5326        }
5327
5328        synchronized (mPackages) {
5329            mPermissionManager.updateAllPermissions(
5330                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5331                    mPermissionCallback);
5332            for (int userId : UserManagerService.getInstance().getUserIds()) {
5333                final int packageCount = mPackages.size();
5334                for (int i = 0; i < packageCount; i++) {
5335                    PackageParser.Package pkg = mPackages.valueAt(i);
5336                    if (!(pkg.mExtras instanceof PackageSetting)) {
5337                        continue;
5338                    }
5339                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5340                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5341                }
5342            }
5343        }
5344    }
5345
5346    @Override
5347    public int getPermissionFlags(String permName, String packageName, int userId) {
5348        return mPermissionManager.getPermissionFlags(
5349                permName, packageName, getCallingUid(), userId);
5350    }
5351
5352    @Override
5353    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5354            int flagValues, int userId) {
5355        mPermissionManager.updatePermissionFlags(
5356                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5357                mPermissionCallback);
5358    }
5359
5360    /**
5361     * Update the permission flags for all packages and runtime permissions of a user in order
5362     * to allow device or profile owner to remove POLICY_FIXED.
5363     */
5364    @Override
5365    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5366        synchronized (mPackages) {
5367            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5368                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5369                    mPermissionCallback);
5370            if (changed) {
5371                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5372            }
5373        }
5374    }
5375
5376    @Override
5377    public boolean shouldShowRequestPermissionRationale(String permissionName,
5378            String packageName, int userId) {
5379        if (UserHandle.getCallingUserId() != userId) {
5380            mContext.enforceCallingPermission(
5381                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5382                    "canShowRequestPermissionRationale for user " + userId);
5383        }
5384
5385        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5386        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5387            return false;
5388        }
5389
5390        if (checkPermission(permissionName, packageName, userId)
5391                == PackageManager.PERMISSION_GRANTED) {
5392            return false;
5393        }
5394
5395        final int flags;
5396
5397        final long identity = Binder.clearCallingIdentity();
5398        try {
5399            flags = getPermissionFlags(permissionName,
5400                    packageName, userId);
5401        } finally {
5402            Binder.restoreCallingIdentity(identity);
5403        }
5404
5405        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5406                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5407                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5408
5409        if ((flags & fixedFlags) != 0) {
5410            return false;
5411        }
5412
5413        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5414    }
5415
5416    @Override
5417    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5418        mContext.enforceCallingOrSelfPermission(
5419                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5420                "addOnPermissionsChangeListener");
5421
5422        synchronized (mPackages) {
5423            mOnPermissionChangeListeners.addListenerLocked(listener);
5424        }
5425    }
5426
5427    @Override
5428    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5429        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5430            throw new SecurityException("Instant applications don't have access to this method");
5431        }
5432        synchronized (mPackages) {
5433            mOnPermissionChangeListeners.removeListenerLocked(listener);
5434        }
5435    }
5436
5437    @Override
5438    public boolean isProtectedBroadcast(String actionName) {
5439        // allow instant applications
5440        synchronized (mProtectedBroadcasts) {
5441            if (mProtectedBroadcasts.contains(actionName)) {
5442                return true;
5443            } else if (actionName != null) {
5444                // TODO: remove these terrible hacks
5445                if (actionName.startsWith("android.net.netmon.lingerExpired")
5446                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5447                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5448                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5449                    return true;
5450                }
5451            }
5452        }
5453        return false;
5454    }
5455
5456    @Override
5457    public int checkSignatures(String pkg1, String pkg2) {
5458        synchronized (mPackages) {
5459            final PackageParser.Package p1 = mPackages.get(pkg1);
5460            final PackageParser.Package p2 = mPackages.get(pkg2);
5461            if (p1 == null || p1.mExtras == null
5462                    || p2 == null || p2.mExtras == null) {
5463                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5464            }
5465            final int callingUid = Binder.getCallingUid();
5466            final int callingUserId = UserHandle.getUserId(callingUid);
5467            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5468            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5469            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5470                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5471                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5472            }
5473            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5474        }
5475    }
5476
5477    @Override
5478    public int checkUidSignatures(int uid1, int uid2) {
5479        final int callingUid = Binder.getCallingUid();
5480        final int callingUserId = UserHandle.getUserId(callingUid);
5481        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5482        // Map to base uids.
5483        uid1 = UserHandle.getAppId(uid1);
5484        uid2 = UserHandle.getAppId(uid2);
5485        // reader
5486        synchronized (mPackages) {
5487            Signature[] s1;
5488            Signature[] s2;
5489            Object obj = mSettings.getUserIdLPr(uid1);
5490            if (obj != null) {
5491                if (obj instanceof SharedUserSetting) {
5492                    if (isCallerInstantApp) {
5493                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5494                    }
5495                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5496                } else if (obj instanceof PackageSetting) {
5497                    final PackageSetting ps = (PackageSetting) obj;
5498                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5499                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5500                    }
5501                    s1 = ps.signatures.mSigningDetails.signatures;
5502                } else {
5503                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5504                }
5505            } else {
5506                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5507            }
5508            obj = mSettings.getUserIdLPr(uid2);
5509            if (obj != null) {
5510                if (obj instanceof SharedUserSetting) {
5511                    if (isCallerInstantApp) {
5512                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5513                    }
5514                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5515                } else if (obj instanceof PackageSetting) {
5516                    final PackageSetting ps = (PackageSetting) obj;
5517                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5518                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5519                    }
5520                    s2 = ps.signatures.mSigningDetails.signatures;
5521                } else {
5522                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5523                }
5524            } else {
5525                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5526            }
5527            return compareSignatures(s1, s2);
5528        }
5529    }
5530
5531    @Override
5532    public boolean hasSigningCertificate(
5533            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5534
5535        synchronized (mPackages) {
5536            final PackageParser.Package p = mPackages.get(packageName);
5537            if (p == null || p.mExtras == null) {
5538                return false;
5539            }
5540            final int callingUid = Binder.getCallingUid();
5541            final int callingUserId = UserHandle.getUserId(callingUid);
5542            final PackageSetting ps = (PackageSetting) p.mExtras;
5543            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5544                return false;
5545            }
5546            switch (type) {
5547                case CERT_INPUT_RAW_X509:
5548                    return p.mSigningDetails.hasCertificate(certificate);
5549                case CERT_INPUT_SHA256:
5550                    return p.mSigningDetails.hasSha256Certificate(certificate);
5551                default:
5552                    return false;
5553            }
5554        }
5555    }
5556
5557    @Override
5558    public boolean hasUidSigningCertificate(
5559            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5560        final int callingUid = Binder.getCallingUid();
5561        final int callingUserId = UserHandle.getUserId(callingUid);
5562        // Map to base uids.
5563        uid = UserHandle.getAppId(uid);
5564        // reader
5565        synchronized (mPackages) {
5566            final PackageParser.SigningDetails signingDetails;
5567            final Object obj = mSettings.getUserIdLPr(uid);
5568            if (obj != null) {
5569                if (obj instanceof SharedUserSetting) {
5570                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5571                    if (isCallerInstantApp) {
5572                        return false;
5573                    }
5574                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5575                } else if (obj instanceof PackageSetting) {
5576                    final PackageSetting ps = (PackageSetting) obj;
5577                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5578                        return false;
5579                    }
5580                    signingDetails = ps.signatures.mSigningDetails;
5581                } else {
5582                    return false;
5583                }
5584            } else {
5585                return false;
5586            }
5587            switch (type) {
5588                case CERT_INPUT_RAW_X509:
5589                    return signingDetails.hasCertificate(certificate);
5590                case CERT_INPUT_SHA256:
5591                    return signingDetails.hasSha256Certificate(certificate);
5592                default:
5593                    return false;
5594            }
5595        }
5596    }
5597
5598    /**
5599     * This method should typically only be used when granting or revoking
5600     * permissions, since the app may immediately restart after this call.
5601     * <p>
5602     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5603     * guard your work against the app being relaunched.
5604     */
5605    private void killUid(int appId, int userId, String reason) {
5606        final long identity = Binder.clearCallingIdentity();
5607        try {
5608            IActivityManager am = ActivityManager.getService();
5609            if (am != null) {
5610                try {
5611                    am.killUid(appId, userId, reason);
5612                } catch (RemoteException e) {
5613                    /* ignore - same process */
5614                }
5615            }
5616        } finally {
5617            Binder.restoreCallingIdentity(identity);
5618        }
5619    }
5620
5621    /**
5622     * If the database version for this type of package (internal storage or
5623     * external storage) is less than the version where package signatures
5624     * were updated, return true.
5625     */
5626    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5627        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5628        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5629    }
5630
5631    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5632        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5633        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5634    }
5635
5636    @Override
5637    public List<String> getAllPackages() {
5638        final int callingUid = Binder.getCallingUid();
5639        final int callingUserId = UserHandle.getUserId(callingUid);
5640        synchronized (mPackages) {
5641            if (canViewInstantApps(callingUid, callingUserId)) {
5642                return new ArrayList<String>(mPackages.keySet());
5643            }
5644            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5645            final List<String> result = new ArrayList<>();
5646            if (instantAppPkgName != null) {
5647                // caller is an instant application; filter unexposed applications
5648                for (PackageParser.Package pkg : mPackages.values()) {
5649                    if (!pkg.visibleToInstantApps) {
5650                        continue;
5651                    }
5652                    result.add(pkg.packageName);
5653                }
5654            } else {
5655                // caller is a normal application; filter instant applications
5656                for (PackageParser.Package pkg : mPackages.values()) {
5657                    final PackageSetting ps =
5658                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5659                    if (ps != null
5660                            && ps.getInstantApp(callingUserId)
5661                            && !mInstantAppRegistry.isInstantAccessGranted(
5662                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5663                        continue;
5664                    }
5665                    result.add(pkg.packageName);
5666                }
5667            }
5668            return result;
5669        }
5670    }
5671
5672    @Override
5673    public String[] getPackagesForUid(int uid) {
5674        final int callingUid = Binder.getCallingUid();
5675        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5676        final int userId = UserHandle.getUserId(uid);
5677        uid = UserHandle.getAppId(uid);
5678        // reader
5679        synchronized (mPackages) {
5680            Object obj = mSettings.getUserIdLPr(uid);
5681            if (obj instanceof SharedUserSetting) {
5682                if (isCallerInstantApp) {
5683                    return null;
5684                }
5685                final SharedUserSetting sus = (SharedUserSetting) obj;
5686                final int N = sus.packages.size();
5687                String[] res = new String[N];
5688                final Iterator<PackageSetting> it = sus.packages.iterator();
5689                int i = 0;
5690                while (it.hasNext()) {
5691                    PackageSetting ps = it.next();
5692                    if (ps.getInstalled(userId)) {
5693                        res[i++] = ps.name;
5694                    } else {
5695                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5696                    }
5697                }
5698                return res;
5699            } else if (obj instanceof PackageSetting) {
5700                final PackageSetting ps = (PackageSetting) obj;
5701                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5702                    return new String[]{ps.name};
5703                }
5704            }
5705        }
5706        return null;
5707    }
5708
5709    @Override
5710    public String getNameForUid(int uid) {
5711        final int callingUid = Binder.getCallingUid();
5712        if (getInstantAppPackageName(callingUid) != null) {
5713            return null;
5714        }
5715        synchronized (mPackages) {
5716            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5717            if (obj instanceof SharedUserSetting) {
5718                final SharedUserSetting sus = (SharedUserSetting) obj;
5719                return sus.name + ":" + sus.userId;
5720            } else if (obj instanceof PackageSetting) {
5721                final PackageSetting ps = (PackageSetting) obj;
5722                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5723                    return null;
5724                }
5725                return ps.name;
5726            }
5727            return null;
5728        }
5729    }
5730
5731    @Override
5732    public String[] getNamesForUids(int[] uids) {
5733        if (uids == null || uids.length == 0) {
5734            return null;
5735        }
5736        final int callingUid = Binder.getCallingUid();
5737        if (getInstantAppPackageName(callingUid) != null) {
5738            return null;
5739        }
5740        final String[] names = new String[uids.length];
5741        synchronized (mPackages) {
5742            for (int i = uids.length - 1; i >= 0; i--) {
5743                final int uid = uids[i];
5744                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5745                if (obj instanceof SharedUserSetting) {
5746                    final SharedUserSetting sus = (SharedUserSetting) obj;
5747                    names[i] = "shared:" + sus.name;
5748                } else if (obj instanceof PackageSetting) {
5749                    final PackageSetting ps = (PackageSetting) obj;
5750                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5751                        names[i] = null;
5752                    } else {
5753                        names[i] = ps.name;
5754                    }
5755                } else {
5756                    names[i] = null;
5757                }
5758            }
5759        }
5760        return names;
5761    }
5762
5763    @Override
5764    public int getUidForSharedUser(String sharedUserName) {
5765        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5766            return -1;
5767        }
5768        if (sharedUserName == null) {
5769            return -1;
5770        }
5771        // reader
5772        synchronized (mPackages) {
5773            SharedUserSetting suid;
5774            try {
5775                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5776                if (suid != null) {
5777                    return suid.userId;
5778                }
5779            } catch (PackageManagerException ignore) {
5780                // can't happen, but, still need to catch it
5781            }
5782            return -1;
5783        }
5784    }
5785
5786    @Override
5787    public int getFlagsForUid(int uid) {
5788        final int callingUid = Binder.getCallingUid();
5789        if (getInstantAppPackageName(callingUid) != null) {
5790            return 0;
5791        }
5792        synchronized (mPackages) {
5793            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5794            if (obj instanceof SharedUserSetting) {
5795                final SharedUserSetting sus = (SharedUserSetting) obj;
5796                return sus.pkgFlags;
5797            } else if (obj instanceof PackageSetting) {
5798                final PackageSetting ps = (PackageSetting) obj;
5799                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5800                    return 0;
5801                }
5802                return ps.pkgFlags;
5803            }
5804        }
5805        return 0;
5806    }
5807
5808    @Override
5809    public int getPrivateFlagsForUid(int uid) {
5810        final int callingUid = Binder.getCallingUid();
5811        if (getInstantAppPackageName(callingUid) != null) {
5812            return 0;
5813        }
5814        synchronized (mPackages) {
5815            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5816            if (obj instanceof SharedUserSetting) {
5817                final SharedUserSetting sus = (SharedUserSetting) obj;
5818                return sus.pkgPrivateFlags;
5819            } else if (obj instanceof PackageSetting) {
5820                final PackageSetting ps = (PackageSetting) obj;
5821                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5822                    return 0;
5823                }
5824                return ps.pkgPrivateFlags;
5825            }
5826        }
5827        return 0;
5828    }
5829
5830    @Override
5831    public boolean isUidPrivileged(int uid) {
5832        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5833            return false;
5834        }
5835        uid = UserHandle.getAppId(uid);
5836        // reader
5837        synchronized (mPackages) {
5838            Object obj = mSettings.getUserIdLPr(uid);
5839            if (obj instanceof SharedUserSetting) {
5840                final SharedUserSetting sus = (SharedUserSetting) obj;
5841                final Iterator<PackageSetting> it = sus.packages.iterator();
5842                while (it.hasNext()) {
5843                    if (it.next().isPrivileged()) {
5844                        return true;
5845                    }
5846                }
5847            } else if (obj instanceof PackageSetting) {
5848                final PackageSetting ps = (PackageSetting) obj;
5849                return ps.isPrivileged();
5850            }
5851        }
5852        return false;
5853    }
5854
5855    @Override
5856    public String[] getAppOpPermissionPackages(String permName) {
5857        return mPermissionManager.getAppOpPermissionPackages(permName);
5858    }
5859
5860    @Override
5861    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5862            int flags, int userId) {
5863        return resolveIntentInternal(
5864                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5865    }
5866
5867    /**
5868     * Normally instant apps can only be resolved when they're visible to the caller.
5869     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5870     * since we need to allow the system to start any installed application.
5871     */
5872    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5873            int flags, int userId, boolean resolveForStart) {
5874        try {
5875            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5876
5877            if (!sUserManager.exists(userId)) return null;
5878            final int callingUid = Binder.getCallingUid();
5879            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5880            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5881                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5882
5883            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5884            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5885                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5886            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5887
5888            final ResolveInfo bestChoice =
5889                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5890            return bestChoice;
5891        } finally {
5892            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5893        }
5894    }
5895
5896    @Override
5897    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5898        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5899            throw new SecurityException(
5900                    "findPersistentPreferredActivity can only be run by the system");
5901        }
5902        if (!sUserManager.exists(userId)) {
5903            return null;
5904        }
5905        final int callingUid = Binder.getCallingUid();
5906        intent = updateIntentForResolve(intent);
5907        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5908        final int flags = updateFlagsForResolve(
5909                0, userId, intent, callingUid, false /*includeInstantApps*/);
5910        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5911                userId);
5912        synchronized (mPackages) {
5913            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5914                    userId);
5915        }
5916    }
5917
5918    @Override
5919    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5920            IntentFilter filter, int match, ComponentName activity) {
5921        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5922            return;
5923        }
5924        final int userId = UserHandle.getCallingUserId();
5925        if (DEBUG_PREFERRED) {
5926            Log.v(TAG, "setLastChosenActivity intent=" + intent
5927                + " resolvedType=" + resolvedType
5928                + " flags=" + flags
5929                + " filter=" + filter
5930                + " match=" + match
5931                + " activity=" + activity);
5932            filter.dump(new PrintStreamPrinter(System.out), "    ");
5933        }
5934        intent.setComponent(null);
5935        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5936                userId);
5937        // Find any earlier preferred or last chosen entries and nuke them
5938        findPreferredActivity(intent, resolvedType,
5939                flags, query, 0, false, true, false, userId);
5940        // Add the new activity as the last chosen for this filter
5941        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5942                "Setting last chosen");
5943    }
5944
5945    @Override
5946    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5947        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5948            return null;
5949        }
5950        final int userId = UserHandle.getCallingUserId();
5951        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5952        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5953                userId);
5954        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5955                false, false, false, userId);
5956    }
5957
5958    /**
5959     * Returns whether or not instant apps have been disabled remotely.
5960     */
5961    private boolean isEphemeralDisabled() {
5962        return mEphemeralAppsDisabled;
5963    }
5964
5965    private boolean isInstantAppAllowed(
5966            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5967            boolean skipPackageCheck) {
5968        if (mInstantAppResolverConnection == null) {
5969            return false;
5970        }
5971        if (mInstantAppInstallerActivity == null) {
5972            return false;
5973        }
5974        if (intent.getComponent() != null) {
5975            return false;
5976        }
5977        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5978            return false;
5979        }
5980        if (!skipPackageCheck && intent.getPackage() != null) {
5981            return false;
5982        }
5983        if (!intent.isBrowsableWebIntent()) {
5984            // for non web intents, we should not resolve externally if an app already exists to
5985            // handle it or if the caller didn't explicitly request it.
5986            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5987                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5988                return false;
5989            }
5990        } else if (intent.getData() == null) {
5991            return false;
5992        }
5993        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5994        // Or if there's already an ephemeral app installed that handles the action
5995        synchronized (mPackages) {
5996            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5997            for (int n = 0; n < count; n++) {
5998                final ResolveInfo info = resolvedActivities.get(n);
5999                final String packageName = info.activityInfo.packageName;
6000                final PackageSetting ps = mSettings.mPackages.get(packageName);
6001                if (ps != null) {
6002                    // only check domain verification status if the app is not a browser
6003                    if (!info.handleAllWebDataURI) {
6004                        // Try to get the status from User settings first
6005                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6006                        final int status = (int) (packedStatus >> 32);
6007                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6008                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6009                            if (DEBUG_EPHEMERAL) {
6010                                Slog.v(TAG, "DENY instant app;"
6011                                    + " pkg: " + packageName + ", status: " + status);
6012                            }
6013                            return false;
6014                        }
6015                    }
6016                    if (ps.getInstantApp(userId)) {
6017                        if (DEBUG_EPHEMERAL) {
6018                            Slog.v(TAG, "DENY instant app installed;"
6019                                    + " pkg: " + packageName);
6020                        }
6021                        return false;
6022                    }
6023                }
6024            }
6025        }
6026        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6027        return true;
6028    }
6029
6030    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6031            Intent origIntent, String resolvedType, String callingPackage,
6032            Bundle verificationBundle, int userId) {
6033        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6034                new InstantAppRequest(responseObj, origIntent, resolvedType,
6035                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6036        mHandler.sendMessage(msg);
6037    }
6038
6039    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6040            int flags, List<ResolveInfo> query, int userId) {
6041        if (query != null) {
6042            final int N = query.size();
6043            if (N == 1) {
6044                return query.get(0);
6045            } else if (N > 1) {
6046                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6047                // If there is more than one activity with the same priority,
6048                // then let the user decide between them.
6049                ResolveInfo r0 = query.get(0);
6050                ResolveInfo r1 = query.get(1);
6051                if (DEBUG_INTENT_MATCHING || debug) {
6052                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6053                            + r1.activityInfo.name + "=" + r1.priority);
6054                }
6055                // If the first activity has a higher priority, or a different
6056                // default, then it is always desirable to pick it.
6057                if (r0.priority != r1.priority
6058                        || r0.preferredOrder != r1.preferredOrder
6059                        || r0.isDefault != r1.isDefault) {
6060                    return query.get(0);
6061                }
6062                // If we have saved a preference for a preferred activity for
6063                // this Intent, use that.
6064                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6065                        flags, query, r0.priority, true, false, debug, userId);
6066                if (ri != null) {
6067                    return ri;
6068                }
6069                // If we have an ephemeral app, use it
6070                for (int i = 0; i < N; i++) {
6071                    ri = query.get(i);
6072                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6073                        final String packageName = ri.activityInfo.packageName;
6074                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6075                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6076                        final int status = (int)(packedStatus >> 32);
6077                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6078                            return ri;
6079                        }
6080                    }
6081                }
6082                ri = new ResolveInfo(mResolveInfo);
6083                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6084                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6085                // If all of the options come from the same package, show the application's
6086                // label and icon instead of the generic resolver's.
6087                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6088                // and then throw away the ResolveInfo itself, meaning that the caller loses
6089                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6090                // a fallback for this case; we only set the target package's resources on
6091                // the ResolveInfo, not the ActivityInfo.
6092                final String intentPackage = intent.getPackage();
6093                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6094                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6095                    ri.resolvePackageName = intentPackage;
6096                    if (userNeedsBadging(userId)) {
6097                        ri.noResourceId = true;
6098                    } else {
6099                        ri.icon = appi.icon;
6100                    }
6101                    ri.iconResourceId = appi.icon;
6102                    ri.labelRes = appi.labelRes;
6103                }
6104                ri.activityInfo.applicationInfo = new ApplicationInfo(
6105                        ri.activityInfo.applicationInfo);
6106                if (userId != 0) {
6107                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6108                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6109                }
6110                // Make sure that the resolver is displayable in car mode
6111                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6112                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6113                return ri;
6114            }
6115        }
6116        return null;
6117    }
6118
6119    /**
6120     * Return true if the given list is not empty and all of its contents have
6121     * an activityInfo with the given package name.
6122     */
6123    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6124        if (ArrayUtils.isEmpty(list)) {
6125            return false;
6126        }
6127        for (int i = 0, N = list.size(); i < N; i++) {
6128            final ResolveInfo ri = list.get(i);
6129            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6130            if (ai == null || !packageName.equals(ai.packageName)) {
6131                return false;
6132            }
6133        }
6134        return true;
6135    }
6136
6137    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6138            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6139        final int N = query.size();
6140        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6141                .get(userId);
6142        // Get the list of persistent preferred activities that handle the intent
6143        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6144        List<PersistentPreferredActivity> pprefs = ppir != null
6145                ? ppir.queryIntent(intent, resolvedType,
6146                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6147                        userId)
6148                : null;
6149        if (pprefs != null && pprefs.size() > 0) {
6150            final int M = pprefs.size();
6151            for (int i=0; i<M; i++) {
6152                final PersistentPreferredActivity ppa = pprefs.get(i);
6153                if (DEBUG_PREFERRED || debug) {
6154                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6155                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6156                            + "\n  component=" + ppa.mComponent);
6157                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6158                }
6159                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6160                        flags | MATCH_DISABLED_COMPONENTS, userId);
6161                if (DEBUG_PREFERRED || debug) {
6162                    Slog.v(TAG, "Found persistent preferred activity:");
6163                    if (ai != null) {
6164                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6165                    } else {
6166                        Slog.v(TAG, "  null");
6167                    }
6168                }
6169                if (ai == null) {
6170                    // This previously registered persistent preferred activity
6171                    // component is no longer known. Ignore it and do NOT remove it.
6172                    continue;
6173                }
6174                for (int j=0; j<N; j++) {
6175                    final ResolveInfo ri = query.get(j);
6176                    if (!ri.activityInfo.applicationInfo.packageName
6177                            .equals(ai.applicationInfo.packageName)) {
6178                        continue;
6179                    }
6180                    if (!ri.activityInfo.name.equals(ai.name)) {
6181                        continue;
6182                    }
6183                    //  Found a persistent preference that can handle the intent.
6184                    if (DEBUG_PREFERRED || debug) {
6185                        Slog.v(TAG, "Returning persistent preferred activity: " +
6186                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6187                    }
6188                    return ri;
6189                }
6190            }
6191        }
6192        return null;
6193    }
6194
6195    // TODO: handle preferred activities missing while user has amnesia
6196    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6197            List<ResolveInfo> query, int priority, boolean always,
6198            boolean removeMatches, boolean debug, int userId) {
6199        if (!sUserManager.exists(userId)) return null;
6200        final int callingUid = Binder.getCallingUid();
6201        flags = updateFlagsForResolve(
6202                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6203        intent = updateIntentForResolve(intent);
6204        // writer
6205        synchronized (mPackages) {
6206            // Try to find a matching persistent preferred activity.
6207            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6208                    debug, userId);
6209
6210            // If a persistent preferred activity matched, use it.
6211            if (pri != null) {
6212                return pri;
6213            }
6214
6215            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6216            // Get the list of preferred activities that handle the intent
6217            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6218            List<PreferredActivity> prefs = pir != null
6219                    ? pir.queryIntent(intent, resolvedType,
6220                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6221                            userId)
6222                    : null;
6223            if (prefs != null && prefs.size() > 0) {
6224                boolean changed = false;
6225                try {
6226                    // First figure out how good the original match set is.
6227                    // We will only allow preferred activities that came
6228                    // from the same match quality.
6229                    int match = 0;
6230
6231                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6232
6233                    final int N = query.size();
6234                    for (int j=0; j<N; j++) {
6235                        final ResolveInfo ri = query.get(j);
6236                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6237                                + ": 0x" + Integer.toHexString(match));
6238                        if (ri.match > match) {
6239                            match = ri.match;
6240                        }
6241                    }
6242
6243                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6244                            + Integer.toHexString(match));
6245
6246                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6247                    final int M = prefs.size();
6248                    for (int i=0; i<M; i++) {
6249                        final PreferredActivity pa = prefs.get(i);
6250                        if (DEBUG_PREFERRED || debug) {
6251                            Slog.v(TAG, "Checking PreferredActivity ds="
6252                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6253                                    + "\n  component=" + pa.mPref.mComponent);
6254                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6255                        }
6256                        if (pa.mPref.mMatch != match) {
6257                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6258                                    + Integer.toHexString(pa.mPref.mMatch));
6259                            continue;
6260                        }
6261                        // If it's not an "always" type preferred activity and that's what we're
6262                        // looking for, skip it.
6263                        if (always && !pa.mPref.mAlways) {
6264                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6265                            continue;
6266                        }
6267                        final ActivityInfo ai = getActivityInfo(
6268                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6269                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6270                                userId);
6271                        if (DEBUG_PREFERRED || debug) {
6272                            Slog.v(TAG, "Found preferred activity:");
6273                            if (ai != null) {
6274                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6275                            } else {
6276                                Slog.v(TAG, "  null");
6277                            }
6278                        }
6279                        if (ai == null) {
6280                            // This previously registered preferred activity
6281                            // component is no longer known.  Most likely an update
6282                            // to the app was installed and in the new version this
6283                            // component no longer exists.  Clean it up by removing
6284                            // it from the preferred activities list, and skip it.
6285                            Slog.w(TAG, "Removing dangling preferred activity: "
6286                                    + pa.mPref.mComponent);
6287                            pir.removeFilter(pa);
6288                            changed = true;
6289                            continue;
6290                        }
6291                        for (int j=0; j<N; j++) {
6292                            final ResolveInfo ri = query.get(j);
6293                            if (!ri.activityInfo.applicationInfo.packageName
6294                                    .equals(ai.applicationInfo.packageName)) {
6295                                continue;
6296                            }
6297                            if (!ri.activityInfo.name.equals(ai.name)) {
6298                                continue;
6299                            }
6300
6301                            if (removeMatches) {
6302                                pir.removeFilter(pa);
6303                                changed = true;
6304                                if (DEBUG_PREFERRED) {
6305                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6306                                }
6307                                break;
6308                            }
6309
6310                            // Okay we found a previously set preferred or last chosen app.
6311                            // If the result set is different from when this
6312                            // was created, and is not a subset of the preferred set, we need to
6313                            // clear it and re-ask the user their preference, if we're looking for
6314                            // an "always" type entry.
6315                            if (always && !pa.mPref.sameSet(query)) {
6316                                if (pa.mPref.isSuperset(query)) {
6317                                    // some components of the set are no longer present in
6318                                    // the query, but the preferred activity can still be reused
6319                                    if (DEBUG_PREFERRED) {
6320                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6321                                                + " still valid as only non-preferred components"
6322                                                + " were removed for " + intent + " type "
6323                                                + resolvedType);
6324                                    }
6325                                    // remove obsolete components and re-add the up-to-date filter
6326                                    PreferredActivity freshPa = new PreferredActivity(pa,
6327                                            pa.mPref.mMatch,
6328                                            pa.mPref.discardObsoleteComponents(query),
6329                                            pa.mPref.mComponent,
6330                                            pa.mPref.mAlways);
6331                                    pir.removeFilter(pa);
6332                                    pir.addFilter(freshPa);
6333                                    changed = true;
6334                                } else {
6335                                    Slog.i(TAG,
6336                                            "Result set changed, dropping preferred activity for "
6337                                                    + intent + " type " + resolvedType);
6338                                    if (DEBUG_PREFERRED) {
6339                                        Slog.v(TAG, "Removing preferred activity since set changed "
6340                                                + pa.mPref.mComponent);
6341                                    }
6342                                    pir.removeFilter(pa);
6343                                    // Re-add the filter as a "last chosen" entry (!always)
6344                                    PreferredActivity lastChosen = new PreferredActivity(
6345                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6346                                    pir.addFilter(lastChosen);
6347                                    changed = true;
6348                                    return null;
6349                                }
6350                            }
6351
6352                            // Yay! Either the set matched or we're looking for the last chosen
6353                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6354                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6355                            return ri;
6356                        }
6357                    }
6358                } finally {
6359                    if (changed) {
6360                        if (DEBUG_PREFERRED) {
6361                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6362                        }
6363                        scheduleWritePackageRestrictionsLocked(userId);
6364                    }
6365                }
6366            }
6367        }
6368        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6369        return null;
6370    }
6371
6372    /*
6373     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6374     */
6375    @Override
6376    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6377            int targetUserId) {
6378        mContext.enforceCallingOrSelfPermission(
6379                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6380        List<CrossProfileIntentFilter> matches =
6381                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6382        if (matches != null) {
6383            int size = matches.size();
6384            for (int i = 0; i < size; i++) {
6385                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6386            }
6387        }
6388        if (intent.hasWebURI()) {
6389            // cross-profile app linking works only towards the parent.
6390            final int callingUid = Binder.getCallingUid();
6391            final UserInfo parent = getProfileParent(sourceUserId);
6392            synchronized(mPackages) {
6393                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6394                        false /*includeInstantApps*/);
6395                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6396                        intent, resolvedType, flags, sourceUserId, parent.id);
6397                return xpDomainInfo != null;
6398            }
6399        }
6400        return false;
6401    }
6402
6403    private UserInfo getProfileParent(int userId) {
6404        final long identity = Binder.clearCallingIdentity();
6405        try {
6406            return sUserManager.getProfileParent(userId);
6407        } finally {
6408            Binder.restoreCallingIdentity(identity);
6409        }
6410    }
6411
6412    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6413            String resolvedType, int userId) {
6414        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6415        if (resolver != null) {
6416            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6417        }
6418        return null;
6419    }
6420
6421    @Override
6422    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6423            String resolvedType, int flags, int userId) {
6424        try {
6425            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6426
6427            return new ParceledListSlice<>(
6428                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6429        } finally {
6430            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6431        }
6432    }
6433
6434    /**
6435     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6436     * instant, returns {@code null}.
6437     */
6438    private String getInstantAppPackageName(int callingUid) {
6439        synchronized (mPackages) {
6440            // If the caller is an isolated app use the owner's uid for the lookup.
6441            if (Process.isIsolated(callingUid)) {
6442                callingUid = mIsolatedOwners.get(callingUid);
6443            }
6444            final int appId = UserHandle.getAppId(callingUid);
6445            final Object obj = mSettings.getUserIdLPr(appId);
6446            if (obj instanceof PackageSetting) {
6447                final PackageSetting ps = (PackageSetting) obj;
6448                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6449                return isInstantApp ? ps.pkg.packageName : null;
6450            }
6451        }
6452        return null;
6453    }
6454
6455    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6456            String resolvedType, int flags, int userId) {
6457        return queryIntentActivitiesInternal(
6458                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6459                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6460    }
6461
6462    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6463            String resolvedType, int flags, int filterCallingUid, int userId,
6464            boolean resolveForStart, boolean allowDynamicSplits) {
6465        if (!sUserManager.exists(userId)) return Collections.emptyList();
6466        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6467        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6468                false /* requireFullPermission */, false /* checkShell */,
6469                "query intent activities");
6470        final String pkgName = intent.getPackage();
6471        ComponentName comp = intent.getComponent();
6472        if (comp == null) {
6473            if (intent.getSelector() != null) {
6474                intent = intent.getSelector();
6475                comp = intent.getComponent();
6476            }
6477        }
6478
6479        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6480                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6481        if (comp != null) {
6482            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6483            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6484            if (ai != null) {
6485                // When specifying an explicit component, we prevent the activity from being
6486                // used when either 1) the calling package is normal and the activity is within
6487                // an ephemeral application or 2) the calling package is ephemeral and the
6488                // activity is not visible to ephemeral applications.
6489                final boolean matchInstantApp =
6490                        (flags & PackageManager.MATCH_INSTANT) != 0;
6491                final boolean matchVisibleToInstantAppOnly =
6492                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6493                final boolean matchExplicitlyVisibleOnly =
6494                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6495                final boolean isCallerInstantApp =
6496                        instantAppPkgName != null;
6497                final boolean isTargetSameInstantApp =
6498                        comp.getPackageName().equals(instantAppPkgName);
6499                final boolean isTargetInstantApp =
6500                        (ai.applicationInfo.privateFlags
6501                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6502                final boolean isTargetVisibleToInstantApp =
6503                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6504                final boolean isTargetExplicitlyVisibleToInstantApp =
6505                        isTargetVisibleToInstantApp
6506                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6507                final boolean isTargetHiddenFromInstantApp =
6508                        !isTargetVisibleToInstantApp
6509                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6510                final boolean blockResolution =
6511                        !isTargetSameInstantApp
6512                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6513                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6514                                        && isTargetHiddenFromInstantApp));
6515                if (!blockResolution) {
6516                    final ResolveInfo ri = new ResolveInfo();
6517                    ri.activityInfo = ai;
6518                    list.add(ri);
6519                }
6520            }
6521            return applyPostResolutionFilter(
6522                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6523        }
6524
6525        // reader
6526        boolean sortResult = false;
6527        boolean addEphemeral = false;
6528        List<ResolveInfo> result;
6529        final boolean ephemeralDisabled = isEphemeralDisabled();
6530        synchronized (mPackages) {
6531            if (pkgName == null) {
6532                List<CrossProfileIntentFilter> matchingFilters =
6533                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6534                // Check for results that need to skip the current profile.
6535                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6536                        resolvedType, flags, userId);
6537                if (xpResolveInfo != null) {
6538                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6539                    xpResult.add(xpResolveInfo);
6540                    return applyPostResolutionFilter(
6541                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6542                            allowDynamicSplits, filterCallingUid, userId);
6543                }
6544
6545                // Check for results in the current profile.
6546                result = filterIfNotSystemUser(mActivities.queryIntent(
6547                        intent, resolvedType, flags, userId), userId);
6548                addEphemeral = !ephemeralDisabled
6549                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6550                // Check for cross profile results.
6551                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6552                xpResolveInfo = queryCrossProfileIntents(
6553                        matchingFilters, intent, resolvedType, flags, userId,
6554                        hasNonNegativePriorityResult);
6555                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6556                    boolean isVisibleToUser = filterIfNotSystemUser(
6557                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6558                    if (isVisibleToUser) {
6559                        result.add(xpResolveInfo);
6560                        sortResult = true;
6561                    }
6562                }
6563                if (intent.hasWebURI()) {
6564                    CrossProfileDomainInfo xpDomainInfo = null;
6565                    final UserInfo parent = getProfileParent(userId);
6566                    if (parent != null) {
6567                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6568                                flags, userId, parent.id);
6569                    }
6570                    if (xpDomainInfo != null) {
6571                        if (xpResolveInfo != null) {
6572                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6573                            // in the result.
6574                            result.remove(xpResolveInfo);
6575                        }
6576                        if (result.size() == 0 && !addEphemeral) {
6577                            // No result in current profile, but found candidate in parent user.
6578                            // And we are not going to add emphemeral app, so we can return the
6579                            // result straight away.
6580                            result.add(xpDomainInfo.resolveInfo);
6581                            return applyPostResolutionFilter(result, instantAppPkgName,
6582                                    allowDynamicSplits, filterCallingUid, userId);
6583                        }
6584                    } else if (result.size() <= 1 && !addEphemeral) {
6585                        // No result in parent user and <= 1 result in current profile, and we
6586                        // are not going to add emphemeral app, so we can return the result without
6587                        // further processing.
6588                        return applyPostResolutionFilter(result, instantAppPkgName,
6589                                allowDynamicSplits, filterCallingUid, userId);
6590                    }
6591                    // We have more than one candidate (combining results from current and parent
6592                    // profile), so we need filtering and sorting.
6593                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6594                            intent, flags, result, xpDomainInfo, userId);
6595                    sortResult = true;
6596                }
6597            } else {
6598                final PackageParser.Package pkg = mPackages.get(pkgName);
6599                result = null;
6600                if (pkg != null) {
6601                    result = filterIfNotSystemUser(
6602                            mActivities.queryIntentForPackage(
6603                                    intent, resolvedType, flags, pkg.activities, userId),
6604                            userId);
6605                }
6606                if (result == null || result.size() == 0) {
6607                    // the caller wants to resolve for a particular package; however, there
6608                    // were no installed results, so, try to find an ephemeral result
6609                    addEphemeral = !ephemeralDisabled
6610                            && isInstantAppAllowed(
6611                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6612                    if (result == null) {
6613                        result = new ArrayList<>();
6614                    }
6615                }
6616            }
6617        }
6618        if (addEphemeral) {
6619            result = maybeAddInstantAppInstaller(
6620                    result, intent, resolvedType, flags, userId, resolveForStart);
6621        }
6622        if (sortResult) {
6623            Collections.sort(result, mResolvePrioritySorter);
6624        }
6625        return applyPostResolutionFilter(
6626                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6627    }
6628
6629    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6630            String resolvedType, int flags, int userId, boolean resolveForStart) {
6631        // first, check to see if we've got an instant app already installed
6632        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6633        ResolveInfo localInstantApp = null;
6634        boolean blockResolution = false;
6635        if (!alreadyResolvedLocally) {
6636            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6637                    flags
6638                        | PackageManager.GET_RESOLVED_FILTER
6639                        | PackageManager.MATCH_INSTANT
6640                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6641                    userId);
6642            for (int i = instantApps.size() - 1; i >= 0; --i) {
6643                final ResolveInfo info = instantApps.get(i);
6644                final String packageName = info.activityInfo.packageName;
6645                final PackageSetting ps = mSettings.mPackages.get(packageName);
6646                if (ps.getInstantApp(userId)) {
6647                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6648                    final int status = (int)(packedStatus >> 32);
6649                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6650                        // there's a local instant application installed, but, the user has
6651                        // chosen to never use it; skip resolution and don't acknowledge
6652                        // an instant application is even available
6653                        if (DEBUG_EPHEMERAL) {
6654                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6655                        }
6656                        blockResolution = true;
6657                        break;
6658                    } else {
6659                        // we have a locally installed instant application; skip resolution
6660                        // but acknowledge there's an instant application available
6661                        if (DEBUG_EPHEMERAL) {
6662                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6663                        }
6664                        localInstantApp = info;
6665                        break;
6666                    }
6667                }
6668            }
6669        }
6670        // no app installed, let's see if one's available
6671        AuxiliaryResolveInfo auxiliaryResponse = null;
6672        if (!blockResolution) {
6673            if (localInstantApp == null) {
6674                // we don't have an instant app locally, resolve externally
6675                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6676                final InstantAppRequest requestObject = new InstantAppRequest(
6677                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6678                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6679                        resolveForStart);
6680                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6681                        mInstantAppResolverConnection, requestObject);
6682                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6683            } else {
6684                // we have an instant application locally, but, we can't admit that since
6685                // callers shouldn't be able to determine prior browsing. create a dummy
6686                // auxiliary response so the downstream code behaves as if there's an
6687                // instant application available externally. when it comes time to start
6688                // the instant application, we'll do the right thing.
6689                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6690                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6691                                        ai.packageName, ai.versionCode, null /* splitName */);
6692            }
6693        }
6694        if (intent.isBrowsableWebIntent() && auxiliaryResponse == null) {
6695            return result;
6696        }
6697        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6698        if (ps == null) {
6699            return result;
6700        }
6701        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6702        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6703                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6704        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6705                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6706        // add a non-generic filter
6707        ephemeralInstaller.filter = new IntentFilter();
6708        if (intent.getAction() != null) {
6709            ephemeralInstaller.filter.addAction(intent.getAction());
6710        }
6711        if (intent.getData() != null && intent.getData().getPath() != null) {
6712            ephemeralInstaller.filter.addDataPath(
6713                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6714        }
6715        ephemeralInstaller.isInstantAppAvailable = true;
6716        // make sure this resolver is the default
6717        ephemeralInstaller.isDefault = true;
6718        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6719        if (DEBUG_EPHEMERAL) {
6720            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6721        }
6722
6723        result.add(ephemeralInstaller);
6724        return result;
6725    }
6726
6727    private static class CrossProfileDomainInfo {
6728        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6729        ResolveInfo resolveInfo;
6730        /* Best domain verification status of the activities found in the other profile */
6731        int bestDomainVerificationStatus;
6732    }
6733
6734    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6735            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6736        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6737                sourceUserId)) {
6738            return null;
6739        }
6740        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6741                resolvedType, flags, parentUserId);
6742
6743        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6744            return null;
6745        }
6746        CrossProfileDomainInfo result = null;
6747        int size = resultTargetUser.size();
6748        for (int i = 0; i < size; i++) {
6749            ResolveInfo riTargetUser = resultTargetUser.get(i);
6750            // Intent filter verification is only for filters that specify a host. So don't return
6751            // those that handle all web uris.
6752            if (riTargetUser.handleAllWebDataURI) {
6753                continue;
6754            }
6755            String packageName = riTargetUser.activityInfo.packageName;
6756            PackageSetting ps = mSettings.mPackages.get(packageName);
6757            if (ps == null) {
6758                continue;
6759            }
6760            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6761            int status = (int)(verificationState >> 32);
6762            if (result == null) {
6763                result = new CrossProfileDomainInfo();
6764                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6765                        sourceUserId, parentUserId);
6766                result.bestDomainVerificationStatus = status;
6767            } else {
6768                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6769                        result.bestDomainVerificationStatus);
6770            }
6771        }
6772        // Don't consider matches with status NEVER across profiles.
6773        if (result != null && result.bestDomainVerificationStatus
6774                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6775            return null;
6776        }
6777        return result;
6778    }
6779
6780    /**
6781     * Verification statuses are ordered from the worse to the best, except for
6782     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6783     */
6784    private int bestDomainVerificationStatus(int status1, int status2) {
6785        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6786            return status2;
6787        }
6788        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6789            return status1;
6790        }
6791        return (int) MathUtils.max(status1, status2);
6792    }
6793
6794    private boolean isUserEnabled(int userId) {
6795        long callingId = Binder.clearCallingIdentity();
6796        try {
6797            UserInfo userInfo = sUserManager.getUserInfo(userId);
6798            return userInfo != null && userInfo.isEnabled();
6799        } finally {
6800            Binder.restoreCallingIdentity(callingId);
6801        }
6802    }
6803
6804    /**
6805     * Filter out activities with systemUserOnly flag set, when current user is not System.
6806     *
6807     * @return filtered list
6808     */
6809    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6810        if (userId == UserHandle.USER_SYSTEM) {
6811            return resolveInfos;
6812        }
6813        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6814            ResolveInfo info = resolveInfos.get(i);
6815            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6816                resolveInfos.remove(i);
6817            }
6818        }
6819        return resolveInfos;
6820    }
6821
6822    /**
6823     * Filters out ephemeral activities.
6824     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6825     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6826     *
6827     * @param resolveInfos The pre-filtered list of resolved activities
6828     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6829     *          is performed.
6830     * @return A filtered list of resolved activities.
6831     */
6832    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6833            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6834        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6835            final ResolveInfo info = resolveInfos.get(i);
6836            // allow activities that are defined in the provided package
6837            if (allowDynamicSplits
6838                    && info.activityInfo != null
6839                    && info.activityInfo.splitName != null
6840                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6841                            info.activityInfo.splitName)) {
6842                if (mInstantAppInstallerActivity == null) {
6843                    if (DEBUG_INSTALL) {
6844                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6845                    }
6846                    resolveInfos.remove(i);
6847                    continue;
6848                }
6849                // requested activity is defined in a split that hasn't been installed yet.
6850                // add the installer to the resolve list
6851                if (DEBUG_INSTALL) {
6852                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6853                }
6854                final ResolveInfo installerInfo = new ResolveInfo(
6855                        mInstantAppInstallerInfo);
6856                final ComponentName installFailureActivity = findInstallFailureActivity(
6857                        info.activityInfo.packageName,  filterCallingUid, userId);
6858                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6859                        installFailureActivity,
6860                        info.activityInfo.packageName,
6861                        info.activityInfo.applicationInfo.versionCode,
6862                        info.activityInfo.splitName);
6863                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6864                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6865                // add a non-generic filter
6866                installerInfo.filter = new IntentFilter();
6867
6868                // This resolve info may appear in the chooser UI, so let us make it
6869                // look as the one it replaces as far as the user is concerned which
6870                // requires loading the correct label and icon for the resolve info.
6871                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6872                installerInfo.labelRes = info.resolveLabelResId();
6873                installerInfo.icon = info.resolveIconResId();
6874
6875                // propagate priority/preferred order/default
6876                installerInfo.priority = info.priority;
6877                installerInfo.preferredOrder = info.preferredOrder;
6878                installerInfo.isDefault = info.isDefault;
6879                installerInfo.isInstantAppAvailable = true;
6880                resolveInfos.set(i, installerInfo);
6881                continue;
6882            }
6883            // caller is a full app, don't need to apply any other filtering
6884            if (ephemeralPkgName == null) {
6885                continue;
6886            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6887                // caller is same app; don't need to apply any other filtering
6888                continue;
6889            }
6890            // allow activities that have been explicitly exposed to ephemeral apps
6891            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6892            if (!isEphemeralApp
6893                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6894                continue;
6895            }
6896            resolveInfos.remove(i);
6897        }
6898        return resolveInfos;
6899    }
6900
6901    /**
6902     * Returns the activity component that can handle install failures.
6903     * <p>By default, the instant application installer handles failures. However, an
6904     * application may want to handle failures on its own. Applications do this by
6905     * creating an activity with an intent filter that handles the action
6906     * {@link Intent#ACTION_INSTALL_FAILURE}.
6907     */
6908    private @Nullable ComponentName findInstallFailureActivity(
6909            String packageName, int filterCallingUid, int userId) {
6910        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6911        failureActivityIntent.setPackage(packageName);
6912        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6913        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6914                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6915                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6916        final int NR = result.size();
6917        if (NR > 0) {
6918            for (int i = 0; i < NR; i++) {
6919                final ResolveInfo info = result.get(i);
6920                if (info.activityInfo.splitName != null) {
6921                    continue;
6922                }
6923                return new ComponentName(packageName, info.activityInfo.name);
6924            }
6925        }
6926        return null;
6927    }
6928
6929    /**
6930     * @param resolveInfos list of resolve infos in descending priority order
6931     * @return if the list contains a resolve info with non-negative priority
6932     */
6933    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6934        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6935    }
6936
6937    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6938            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6939            int userId) {
6940        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6941
6942        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6943            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6944                    candidates.size());
6945        }
6946
6947        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6948        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6949        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6950        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6951        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6952        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6953
6954        synchronized (mPackages) {
6955            final int count = candidates.size();
6956            // First, try to use linked apps. Partition the candidates into four lists:
6957            // one for the final results, one for the "do not use ever", one for "undefined status"
6958            // and finally one for "browser app type".
6959            for (int n=0; n<count; n++) {
6960                ResolveInfo info = candidates.get(n);
6961                String packageName = info.activityInfo.packageName;
6962                PackageSetting ps = mSettings.mPackages.get(packageName);
6963                if (ps != null) {
6964                    // Add to the special match all list (Browser use case)
6965                    if (info.handleAllWebDataURI) {
6966                        matchAllList.add(info);
6967                        continue;
6968                    }
6969                    // Try to get the status from User settings first
6970                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6971                    int status = (int)(packedStatus >> 32);
6972                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6973                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6974                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6975                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6976                                    + " : linkgen=" + linkGeneration);
6977                        }
6978                        // Use link-enabled generation as preferredOrder, i.e.
6979                        // prefer newly-enabled over earlier-enabled.
6980                        info.preferredOrder = linkGeneration;
6981                        alwaysList.add(info);
6982                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6983                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6984                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6985                        }
6986                        neverList.add(info);
6987                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6988                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6989                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6990                        }
6991                        alwaysAskList.add(info);
6992                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6993                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6994                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6995                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6996                        }
6997                        undefinedList.add(info);
6998                    }
6999                }
7000            }
7001
7002            // We'll want to include browser possibilities in a few cases
7003            boolean includeBrowser = false;
7004
7005            // First try to add the "always" resolution(s) for the current user, if any
7006            if (alwaysList.size() > 0) {
7007                result.addAll(alwaysList);
7008            } else {
7009                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7010                result.addAll(undefinedList);
7011                // Maybe add one for the other profile.
7012                if (xpDomainInfo != null && (
7013                        xpDomainInfo.bestDomainVerificationStatus
7014                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7015                    result.add(xpDomainInfo.resolveInfo);
7016                }
7017                includeBrowser = true;
7018            }
7019
7020            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7021            // If there were 'always' entries their preferred order has been set, so we also
7022            // back that off to make the alternatives equivalent
7023            if (alwaysAskList.size() > 0) {
7024                for (ResolveInfo i : result) {
7025                    i.preferredOrder = 0;
7026                }
7027                result.addAll(alwaysAskList);
7028                includeBrowser = true;
7029            }
7030
7031            if (includeBrowser) {
7032                // Also add browsers (all of them or only the default one)
7033                if (DEBUG_DOMAIN_VERIFICATION) {
7034                    Slog.v(TAG, "   ...including browsers in candidate set");
7035                }
7036                if ((matchFlags & MATCH_ALL) != 0) {
7037                    result.addAll(matchAllList);
7038                } else {
7039                    // Browser/generic handling case.  If there's a default browser, go straight
7040                    // to that (but only if there is no other higher-priority match).
7041                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7042                    int maxMatchPrio = 0;
7043                    ResolveInfo defaultBrowserMatch = null;
7044                    final int numCandidates = matchAllList.size();
7045                    for (int n = 0; n < numCandidates; n++) {
7046                        ResolveInfo info = matchAllList.get(n);
7047                        // track the highest overall match priority...
7048                        if (info.priority > maxMatchPrio) {
7049                            maxMatchPrio = info.priority;
7050                        }
7051                        // ...and the highest-priority default browser match
7052                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7053                            if (defaultBrowserMatch == null
7054                                    || (defaultBrowserMatch.priority < info.priority)) {
7055                                if (debug) {
7056                                    Slog.v(TAG, "Considering default browser match " + info);
7057                                }
7058                                defaultBrowserMatch = info;
7059                            }
7060                        }
7061                    }
7062                    if (defaultBrowserMatch != null
7063                            && defaultBrowserMatch.priority >= maxMatchPrio
7064                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7065                    {
7066                        if (debug) {
7067                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7068                        }
7069                        result.add(defaultBrowserMatch);
7070                    } else {
7071                        result.addAll(matchAllList);
7072                    }
7073                }
7074
7075                // If there is nothing selected, add all candidates and remove the ones that the user
7076                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7077                if (result.size() == 0) {
7078                    result.addAll(candidates);
7079                    result.removeAll(neverList);
7080                }
7081            }
7082        }
7083        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7084            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7085                    result.size());
7086            for (ResolveInfo info : result) {
7087                Slog.v(TAG, "  + " + info.activityInfo);
7088            }
7089        }
7090        return result;
7091    }
7092
7093    // Returns a packed value as a long:
7094    //
7095    // high 'int'-sized word: link status: undefined/ask/never/always.
7096    // low 'int'-sized word: relative priority among 'always' results.
7097    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7098        long result = ps.getDomainVerificationStatusForUser(userId);
7099        // if none available, get the master status
7100        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7101            if (ps.getIntentFilterVerificationInfo() != null) {
7102                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7103            }
7104        }
7105        return result;
7106    }
7107
7108    private ResolveInfo querySkipCurrentProfileIntents(
7109            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7110            int flags, int sourceUserId) {
7111        if (matchingFilters != null) {
7112            int size = matchingFilters.size();
7113            for (int i = 0; i < size; i ++) {
7114                CrossProfileIntentFilter filter = matchingFilters.get(i);
7115                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7116                    // Checking if there are activities in the target user that can handle the
7117                    // intent.
7118                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7119                            resolvedType, flags, sourceUserId);
7120                    if (resolveInfo != null) {
7121                        return resolveInfo;
7122                    }
7123                }
7124            }
7125        }
7126        return null;
7127    }
7128
7129    // Return matching ResolveInfo in target user if any.
7130    private ResolveInfo queryCrossProfileIntents(
7131            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7132            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7133        if (matchingFilters != null) {
7134            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7135            // match the same intent. For performance reasons, it is better not to
7136            // run queryIntent twice for the same userId
7137            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7138            int size = matchingFilters.size();
7139            for (int i = 0; i < size; i++) {
7140                CrossProfileIntentFilter filter = matchingFilters.get(i);
7141                int targetUserId = filter.getTargetUserId();
7142                boolean skipCurrentProfile =
7143                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7144                boolean skipCurrentProfileIfNoMatchFound =
7145                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7146                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7147                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7148                    // Checking if there are activities in the target user that can handle the
7149                    // intent.
7150                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7151                            resolvedType, flags, sourceUserId);
7152                    if (resolveInfo != null) return resolveInfo;
7153                    alreadyTriedUserIds.put(targetUserId, true);
7154                }
7155            }
7156        }
7157        return null;
7158    }
7159
7160    /**
7161     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7162     * will forward the intent to the filter's target user.
7163     * Otherwise, returns null.
7164     */
7165    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7166            String resolvedType, int flags, int sourceUserId) {
7167        int targetUserId = filter.getTargetUserId();
7168        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7169                resolvedType, flags, targetUserId);
7170        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7171            // If all the matches in the target profile are suspended, return null.
7172            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7173                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7174                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7175                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7176                            targetUserId);
7177                }
7178            }
7179        }
7180        return null;
7181    }
7182
7183    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7184            int sourceUserId, int targetUserId) {
7185        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7186        long ident = Binder.clearCallingIdentity();
7187        boolean targetIsProfile;
7188        try {
7189            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7190        } finally {
7191            Binder.restoreCallingIdentity(ident);
7192        }
7193        String className;
7194        if (targetIsProfile) {
7195            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7196        } else {
7197            className = FORWARD_INTENT_TO_PARENT;
7198        }
7199        ComponentName forwardingActivityComponentName = new ComponentName(
7200                mAndroidApplication.packageName, className);
7201        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7202                sourceUserId);
7203        if (!targetIsProfile) {
7204            forwardingActivityInfo.showUserIcon = targetUserId;
7205            forwardingResolveInfo.noResourceId = true;
7206        }
7207        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7208        forwardingResolveInfo.priority = 0;
7209        forwardingResolveInfo.preferredOrder = 0;
7210        forwardingResolveInfo.match = 0;
7211        forwardingResolveInfo.isDefault = true;
7212        forwardingResolveInfo.filter = filter;
7213        forwardingResolveInfo.targetUserId = targetUserId;
7214        return forwardingResolveInfo;
7215    }
7216
7217    @Override
7218    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7219            Intent[] specifics, String[] specificTypes, Intent intent,
7220            String resolvedType, int flags, int userId) {
7221        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7222                specificTypes, intent, resolvedType, flags, userId));
7223    }
7224
7225    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7226            Intent[] specifics, String[] specificTypes, Intent intent,
7227            String resolvedType, int flags, int userId) {
7228        if (!sUserManager.exists(userId)) return Collections.emptyList();
7229        final int callingUid = Binder.getCallingUid();
7230        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7231                false /*includeInstantApps*/);
7232        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7233                false /*requireFullPermission*/, false /*checkShell*/,
7234                "query intent activity options");
7235        final String resultsAction = intent.getAction();
7236
7237        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7238                | PackageManager.GET_RESOLVED_FILTER, userId);
7239
7240        if (DEBUG_INTENT_MATCHING) {
7241            Log.v(TAG, "Query " + intent + ": " + results);
7242        }
7243
7244        int specificsPos = 0;
7245        int N;
7246
7247        // todo: note that the algorithm used here is O(N^2).  This
7248        // isn't a problem in our current environment, but if we start running
7249        // into situations where we have more than 5 or 10 matches then this
7250        // should probably be changed to something smarter...
7251
7252        // First we go through and resolve each of the specific items
7253        // that were supplied, taking care of removing any corresponding
7254        // duplicate items in the generic resolve list.
7255        if (specifics != null) {
7256            for (int i=0; i<specifics.length; i++) {
7257                final Intent sintent = specifics[i];
7258                if (sintent == null) {
7259                    continue;
7260                }
7261
7262                if (DEBUG_INTENT_MATCHING) {
7263                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7264                }
7265
7266                String action = sintent.getAction();
7267                if (resultsAction != null && resultsAction.equals(action)) {
7268                    // If this action was explicitly requested, then don't
7269                    // remove things that have it.
7270                    action = null;
7271                }
7272
7273                ResolveInfo ri = null;
7274                ActivityInfo ai = null;
7275
7276                ComponentName comp = sintent.getComponent();
7277                if (comp == null) {
7278                    ri = resolveIntent(
7279                        sintent,
7280                        specificTypes != null ? specificTypes[i] : null,
7281                            flags, userId);
7282                    if (ri == null) {
7283                        continue;
7284                    }
7285                    if (ri == mResolveInfo) {
7286                        // ACK!  Must do something better with this.
7287                    }
7288                    ai = ri.activityInfo;
7289                    comp = new ComponentName(ai.applicationInfo.packageName,
7290                            ai.name);
7291                } else {
7292                    ai = getActivityInfo(comp, flags, userId);
7293                    if (ai == null) {
7294                        continue;
7295                    }
7296                }
7297
7298                // Look for any generic query activities that are duplicates
7299                // of this specific one, and remove them from the results.
7300                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7301                N = results.size();
7302                int j;
7303                for (j=specificsPos; j<N; j++) {
7304                    ResolveInfo sri = results.get(j);
7305                    if ((sri.activityInfo.name.equals(comp.getClassName())
7306                            && sri.activityInfo.applicationInfo.packageName.equals(
7307                                    comp.getPackageName()))
7308                        || (action != null && sri.filter.matchAction(action))) {
7309                        results.remove(j);
7310                        if (DEBUG_INTENT_MATCHING) Log.v(
7311                            TAG, "Removing duplicate item from " + j
7312                            + " due to specific " + specificsPos);
7313                        if (ri == null) {
7314                            ri = sri;
7315                        }
7316                        j--;
7317                        N--;
7318                    }
7319                }
7320
7321                // Add this specific item to its proper place.
7322                if (ri == null) {
7323                    ri = new ResolveInfo();
7324                    ri.activityInfo = ai;
7325                }
7326                results.add(specificsPos, ri);
7327                ri.specificIndex = i;
7328                specificsPos++;
7329            }
7330        }
7331
7332        // Now we go through the remaining generic results and remove any
7333        // duplicate actions that are found here.
7334        N = results.size();
7335        for (int i=specificsPos; i<N-1; i++) {
7336            final ResolveInfo rii = results.get(i);
7337            if (rii.filter == null) {
7338                continue;
7339            }
7340
7341            // Iterate over all of the actions of this result's intent
7342            // filter...  typically this should be just one.
7343            final Iterator<String> it = rii.filter.actionsIterator();
7344            if (it == null) {
7345                continue;
7346            }
7347            while (it.hasNext()) {
7348                final String action = it.next();
7349                if (resultsAction != null && resultsAction.equals(action)) {
7350                    // If this action was explicitly requested, then don't
7351                    // remove things that have it.
7352                    continue;
7353                }
7354                for (int j=i+1; j<N; j++) {
7355                    final ResolveInfo rij = results.get(j);
7356                    if (rij.filter != null && rij.filter.hasAction(action)) {
7357                        results.remove(j);
7358                        if (DEBUG_INTENT_MATCHING) Log.v(
7359                            TAG, "Removing duplicate item from " + j
7360                            + " due to action " + action + " at " + i);
7361                        j--;
7362                        N--;
7363                    }
7364                }
7365            }
7366
7367            // If the caller didn't request filter information, drop it now
7368            // so we don't have to marshall/unmarshall it.
7369            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7370                rii.filter = null;
7371            }
7372        }
7373
7374        // Filter out the caller activity if so requested.
7375        if (caller != null) {
7376            N = results.size();
7377            for (int i=0; i<N; i++) {
7378                ActivityInfo ainfo = results.get(i).activityInfo;
7379                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7380                        && caller.getClassName().equals(ainfo.name)) {
7381                    results.remove(i);
7382                    break;
7383                }
7384            }
7385        }
7386
7387        // If the caller didn't request filter information,
7388        // drop them now so we don't have to
7389        // marshall/unmarshall it.
7390        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7391            N = results.size();
7392            for (int i=0; i<N; i++) {
7393                results.get(i).filter = null;
7394            }
7395        }
7396
7397        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7398        return results;
7399    }
7400
7401    @Override
7402    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7403            String resolvedType, int flags, int userId) {
7404        return new ParceledListSlice<>(
7405                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7406                        false /*allowDynamicSplits*/));
7407    }
7408
7409    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7410            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7411        if (!sUserManager.exists(userId)) return Collections.emptyList();
7412        final int callingUid = Binder.getCallingUid();
7413        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7414                false /*requireFullPermission*/, false /*checkShell*/,
7415                "query intent receivers");
7416        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7417        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7418                false /*includeInstantApps*/);
7419        ComponentName comp = intent.getComponent();
7420        if (comp == null) {
7421            if (intent.getSelector() != null) {
7422                intent = intent.getSelector();
7423                comp = intent.getComponent();
7424            }
7425        }
7426        if (comp != null) {
7427            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7428            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7429            if (ai != null) {
7430                // When specifying an explicit component, we prevent the activity from being
7431                // used when either 1) the calling package is normal and the activity is within
7432                // an instant application or 2) the calling package is ephemeral and the
7433                // activity is not visible to instant applications.
7434                final boolean matchInstantApp =
7435                        (flags & PackageManager.MATCH_INSTANT) != 0;
7436                final boolean matchVisibleToInstantAppOnly =
7437                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7438                final boolean matchExplicitlyVisibleOnly =
7439                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7440                final boolean isCallerInstantApp =
7441                        instantAppPkgName != null;
7442                final boolean isTargetSameInstantApp =
7443                        comp.getPackageName().equals(instantAppPkgName);
7444                final boolean isTargetInstantApp =
7445                        (ai.applicationInfo.privateFlags
7446                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7447                final boolean isTargetVisibleToInstantApp =
7448                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7449                final boolean isTargetExplicitlyVisibleToInstantApp =
7450                        isTargetVisibleToInstantApp
7451                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7452                final boolean isTargetHiddenFromInstantApp =
7453                        !isTargetVisibleToInstantApp
7454                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7455                final boolean blockResolution =
7456                        !isTargetSameInstantApp
7457                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7458                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7459                                        && isTargetHiddenFromInstantApp));
7460                if (!blockResolution) {
7461                    ResolveInfo ri = new ResolveInfo();
7462                    ri.activityInfo = ai;
7463                    list.add(ri);
7464                }
7465            }
7466            return applyPostResolutionFilter(
7467                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7468        }
7469
7470        // reader
7471        synchronized (mPackages) {
7472            String pkgName = intent.getPackage();
7473            if (pkgName == null) {
7474                final List<ResolveInfo> result =
7475                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7476                return applyPostResolutionFilter(
7477                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7478            }
7479            final PackageParser.Package pkg = mPackages.get(pkgName);
7480            if (pkg != null) {
7481                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7482                        intent, resolvedType, flags, pkg.receivers, userId);
7483                return applyPostResolutionFilter(
7484                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7485            }
7486            return Collections.emptyList();
7487        }
7488    }
7489
7490    @Override
7491    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7492        final int callingUid = Binder.getCallingUid();
7493        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7494    }
7495
7496    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7497            int userId, int callingUid) {
7498        if (!sUserManager.exists(userId)) return null;
7499        flags = updateFlagsForResolve(
7500                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7501        List<ResolveInfo> query = queryIntentServicesInternal(
7502                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7503        if (query != null) {
7504            if (query.size() >= 1) {
7505                // If there is more than one service with the same priority,
7506                // just arbitrarily pick the first one.
7507                return query.get(0);
7508            }
7509        }
7510        return null;
7511    }
7512
7513    @Override
7514    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7515            String resolvedType, int flags, int userId) {
7516        final int callingUid = Binder.getCallingUid();
7517        return new ParceledListSlice<>(queryIntentServicesInternal(
7518                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7519    }
7520
7521    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7522            String resolvedType, int flags, int userId, int callingUid,
7523            boolean includeInstantApps) {
7524        if (!sUserManager.exists(userId)) return Collections.emptyList();
7525        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7526                false /*requireFullPermission*/, false /*checkShell*/,
7527                "query intent receivers");
7528        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7529        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7530        ComponentName comp = intent.getComponent();
7531        if (comp == null) {
7532            if (intent.getSelector() != null) {
7533                intent = intent.getSelector();
7534                comp = intent.getComponent();
7535            }
7536        }
7537        if (comp != null) {
7538            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7539            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7540            if (si != null) {
7541                // When specifying an explicit component, we prevent the service from being
7542                // used when either 1) the service is in an instant application and the
7543                // caller is not the same instant application or 2) the calling package is
7544                // ephemeral and the activity is not visible to ephemeral applications.
7545                final boolean matchInstantApp =
7546                        (flags & PackageManager.MATCH_INSTANT) != 0;
7547                final boolean matchVisibleToInstantAppOnly =
7548                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7549                final boolean isCallerInstantApp =
7550                        instantAppPkgName != null;
7551                final boolean isTargetSameInstantApp =
7552                        comp.getPackageName().equals(instantAppPkgName);
7553                final boolean isTargetInstantApp =
7554                        (si.applicationInfo.privateFlags
7555                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7556                final boolean isTargetHiddenFromInstantApp =
7557                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7558                final boolean blockResolution =
7559                        !isTargetSameInstantApp
7560                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7561                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7562                                        && isTargetHiddenFromInstantApp));
7563                if (!blockResolution) {
7564                    final ResolveInfo ri = new ResolveInfo();
7565                    ri.serviceInfo = si;
7566                    list.add(ri);
7567                }
7568            }
7569            return list;
7570        }
7571
7572        // reader
7573        synchronized (mPackages) {
7574            String pkgName = intent.getPackage();
7575            if (pkgName == null) {
7576                return applyPostServiceResolutionFilter(
7577                        mServices.queryIntent(intent, resolvedType, flags, userId),
7578                        instantAppPkgName);
7579            }
7580            final PackageParser.Package pkg = mPackages.get(pkgName);
7581            if (pkg != null) {
7582                return applyPostServiceResolutionFilter(
7583                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7584                                userId),
7585                        instantAppPkgName);
7586            }
7587            return Collections.emptyList();
7588        }
7589    }
7590
7591    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7592            String instantAppPkgName) {
7593        if (instantAppPkgName == null) {
7594            return resolveInfos;
7595        }
7596        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7597            final ResolveInfo info = resolveInfos.get(i);
7598            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7599            // allow services that are defined in the provided package
7600            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7601                if (info.serviceInfo.splitName != null
7602                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7603                                info.serviceInfo.splitName)) {
7604                    // requested service is defined in a split that hasn't been installed yet.
7605                    // add the installer to the resolve list
7606                    if (DEBUG_EPHEMERAL) {
7607                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7608                    }
7609                    final ResolveInfo installerInfo = new ResolveInfo(
7610                            mInstantAppInstallerInfo);
7611                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7612                            null /* installFailureActivity */,
7613                            info.serviceInfo.packageName,
7614                            info.serviceInfo.applicationInfo.versionCode,
7615                            info.serviceInfo.splitName);
7616                    // make sure this resolver is the default
7617                    installerInfo.isDefault = true;
7618                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7619                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7620                    // add a non-generic filter
7621                    installerInfo.filter = new IntentFilter();
7622                    // load resources from the correct package
7623                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7624                    resolveInfos.set(i, installerInfo);
7625                }
7626                continue;
7627            }
7628            // allow services that have been explicitly exposed to ephemeral apps
7629            if (!isEphemeralApp
7630                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7631                continue;
7632            }
7633            resolveInfos.remove(i);
7634        }
7635        return resolveInfos;
7636    }
7637
7638    @Override
7639    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7640            String resolvedType, int flags, int userId) {
7641        return new ParceledListSlice<>(
7642                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7643    }
7644
7645    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7646            Intent intent, String resolvedType, int flags, int userId) {
7647        if (!sUserManager.exists(userId)) return Collections.emptyList();
7648        final int callingUid = Binder.getCallingUid();
7649        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7650        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7651                false /*includeInstantApps*/);
7652        ComponentName comp = intent.getComponent();
7653        if (comp == null) {
7654            if (intent.getSelector() != null) {
7655                intent = intent.getSelector();
7656                comp = intent.getComponent();
7657            }
7658        }
7659        if (comp != null) {
7660            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7661            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7662            if (pi != null) {
7663                // When specifying an explicit component, we prevent the provider from being
7664                // used when either 1) the provider is in an instant application and the
7665                // caller is not the same instant application or 2) the calling package is an
7666                // instant application and the provider is not visible to instant applications.
7667                final boolean matchInstantApp =
7668                        (flags & PackageManager.MATCH_INSTANT) != 0;
7669                final boolean matchVisibleToInstantAppOnly =
7670                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7671                final boolean isCallerInstantApp =
7672                        instantAppPkgName != null;
7673                final boolean isTargetSameInstantApp =
7674                        comp.getPackageName().equals(instantAppPkgName);
7675                final boolean isTargetInstantApp =
7676                        (pi.applicationInfo.privateFlags
7677                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7678                final boolean isTargetHiddenFromInstantApp =
7679                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7680                final boolean blockResolution =
7681                        !isTargetSameInstantApp
7682                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7683                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7684                                        && isTargetHiddenFromInstantApp));
7685                if (!blockResolution) {
7686                    final ResolveInfo ri = new ResolveInfo();
7687                    ri.providerInfo = pi;
7688                    list.add(ri);
7689                }
7690            }
7691            return list;
7692        }
7693
7694        // reader
7695        synchronized (mPackages) {
7696            String pkgName = intent.getPackage();
7697            if (pkgName == null) {
7698                return applyPostContentProviderResolutionFilter(
7699                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7700                        instantAppPkgName);
7701            }
7702            final PackageParser.Package pkg = mPackages.get(pkgName);
7703            if (pkg != null) {
7704                return applyPostContentProviderResolutionFilter(
7705                        mProviders.queryIntentForPackage(
7706                        intent, resolvedType, flags, pkg.providers, userId),
7707                        instantAppPkgName);
7708            }
7709            return Collections.emptyList();
7710        }
7711    }
7712
7713    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7714            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7715        if (instantAppPkgName == null) {
7716            return resolveInfos;
7717        }
7718        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7719            final ResolveInfo info = resolveInfos.get(i);
7720            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7721            // allow providers that are defined in the provided package
7722            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7723                if (info.providerInfo.splitName != null
7724                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7725                                info.providerInfo.splitName)) {
7726                    // requested provider is defined in a split that hasn't been installed yet.
7727                    // add the installer to the resolve list
7728                    if (DEBUG_EPHEMERAL) {
7729                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7730                    }
7731                    final ResolveInfo installerInfo = new ResolveInfo(
7732                            mInstantAppInstallerInfo);
7733                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7734                            null /*failureActivity*/,
7735                            info.providerInfo.packageName,
7736                            info.providerInfo.applicationInfo.versionCode,
7737                            info.providerInfo.splitName);
7738                    // make sure this resolver is the default
7739                    installerInfo.isDefault = true;
7740                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7741                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7742                    // add a non-generic filter
7743                    installerInfo.filter = new IntentFilter();
7744                    // load resources from the correct package
7745                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7746                    resolveInfos.set(i, installerInfo);
7747                }
7748                continue;
7749            }
7750            // allow providers that have been explicitly exposed to instant applications
7751            if (!isEphemeralApp
7752                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7753                continue;
7754            }
7755            resolveInfos.remove(i);
7756        }
7757        return resolveInfos;
7758    }
7759
7760    @Override
7761    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7762        final int callingUid = Binder.getCallingUid();
7763        if (getInstantAppPackageName(callingUid) != null) {
7764            return ParceledListSlice.emptyList();
7765        }
7766        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7767        flags = updateFlagsForPackage(flags, userId, null);
7768        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7769        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7770                true /* requireFullPermission */, false /* checkShell */,
7771                "get installed packages");
7772
7773        // writer
7774        synchronized (mPackages) {
7775            ArrayList<PackageInfo> list;
7776            if (listUninstalled) {
7777                list = new ArrayList<>(mSettings.mPackages.size());
7778                for (PackageSetting ps : mSettings.mPackages.values()) {
7779                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7780                        continue;
7781                    }
7782                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7783                        continue;
7784                    }
7785                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7786                    if (pi != null) {
7787                        list.add(pi);
7788                    }
7789                }
7790            } else {
7791                list = new ArrayList<>(mPackages.size());
7792                for (PackageParser.Package p : mPackages.values()) {
7793                    final PackageSetting ps = (PackageSetting) p.mExtras;
7794                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7795                        continue;
7796                    }
7797                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7798                        continue;
7799                    }
7800                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7801                            p.mExtras, flags, userId);
7802                    if (pi != null) {
7803                        list.add(pi);
7804                    }
7805                }
7806            }
7807
7808            return new ParceledListSlice<>(list);
7809        }
7810    }
7811
7812    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7813            String[] permissions, boolean[] tmp, int flags, int userId) {
7814        int numMatch = 0;
7815        final PermissionsState permissionsState = ps.getPermissionsState();
7816        for (int i=0; i<permissions.length; i++) {
7817            final String permission = permissions[i];
7818            if (permissionsState.hasPermission(permission, userId)) {
7819                tmp[i] = true;
7820                numMatch++;
7821            } else {
7822                tmp[i] = false;
7823            }
7824        }
7825        if (numMatch == 0) {
7826            return;
7827        }
7828        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7829
7830        // The above might return null in cases of uninstalled apps or install-state
7831        // skew across users/profiles.
7832        if (pi != null) {
7833            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7834                if (numMatch == permissions.length) {
7835                    pi.requestedPermissions = permissions;
7836                } else {
7837                    pi.requestedPermissions = new String[numMatch];
7838                    numMatch = 0;
7839                    for (int i=0; i<permissions.length; i++) {
7840                        if (tmp[i]) {
7841                            pi.requestedPermissions[numMatch] = permissions[i];
7842                            numMatch++;
7843                        }
7844                    }
7845                }
7846            }
7847            list.add(pi);
7848        }
7849    }
7850
7851    @Override
7852    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7853            String[] permissions, int flags, int userId) {
7854        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7855        flags = updateFlagsForPackage(flags, userId, permissions);
7856        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7857                true /* requireFullPermission */, false /* checkShell */,
7858                "get packages holding permissions");
7859        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7860
7861        // writer
7862        synchronized (mPackages) {
7863            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7864            boolean[] tmpBools = new boolean[permissions.length];
7865            if (listUninstalled) {
7866                for (PackageSetting ps : mSettings.mPackages.values()) {
7867                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7868                            userId);
7869                }
7870            } else {
7871                for (PackageParser.Package pkg : mPackages.values()) {
7872                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7873                    if (ps != null) {
7874                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7875                                userId);
7876                    }
7877                }
7878            }
7879
7880            return new ParceledListSlice<PackageInfo>(list);
7881        }
7882    }
7883
7884    @Override
7885    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7886        final int callingUid = Binder.getCallingUid();
7887        if (getInstantAppPackageName(callingUid) != null) {
7888            return ParceledListSlice.emptyList();
7889        }
7890        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7891        flags = updateFlagsForApplication(flags, userId, null);
7892        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7893
7894        // writer
7895        synchronized (mPackages) {
7896            ArrayList<ApplicationInfo> list;
7897            if (listUninstalled) {
7898                list = new ArrayList<>(mSettings.mPackages.size());
7899                for (PackageSetting ps : mSettings.mPackages.values()) {
7900                    ApplicationInfo ai;
7901                    int effectiveFlags = flags;
7902                    if (ps.isSystem()) {
7903                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7904                    }
7905                    if (ps.pkg != null) {
7906                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7907                            continue;
7908                        }
7909                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7910                            continue;
7911                        }
7912                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7913                                ps.readUserState(userId), userId);
7914                        if (ai != null) {
7915                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7916                        }
7917                    } else {
7918                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7919                        // and already converts to externally visible package name
7920                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7921                                callingUid, effectiveFlags, userId);
7922                    }
7923                    if (ai != null) {
7924                        list.add(ai);
7925                    }
7926                }
7927            } else {
7928                list = new ArrayList<>(mPackages.size());
7929                for (PackageParser.Package p : mPackages.values()) {
7930                    if (p.mExtras != null) {
7931                        PackageSetting ps = (PackageSetting) p.mExtras;
7932                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7933                            continue;
7934                        }
7935                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7936                            continue;
7937                        }
7938                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7939                                ps.readUserState(userId), userId);
7940                        if (ai != null) {
7941                            ai.packageName = resolveExternalPackageNameLPr(p);
7942                            list.add(ai);
7943                        }
7944                    }
7945                }
7946            }
7947
7948            return new ParceledListSlice<>(list);
7949        }
7950    }
7951
7952    @Override
7953    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7954        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7955            return null;
7956        }
7957        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7958            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7959                    "getEphemeralApplications");
7960        }
7961        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7962                true /* requireFullPermission */, false /* checkShell */,
7963                "getEphemeralApplications");
7964        synchronized (mPackages) {
7965            List<InstantAppInfo> instantApps = mInstantAppRegistry
7966                    .getInstantAppsLPr(userId);
7967            if (instantApps != null) {
7968                return new ParceledListSlice<>(instantApps);
7969            }
7970        }
7971        return null;
7972    }
7973
7974    @Override
7975    public boolean isInstantApp(String packageName, int userId) {
7976        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7977                true /* requireFullPermission */, false /* checkShell */,
7978                "isInstantApp");
7979        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7980            return false;
7981        }
7982
7983        synchronized (mPackages) {
7984            int callingUid = Binder.getCallingUid();
7985            if (Process.isIsolated(callingUid)) {
7986                callingUid = mIsolatedOwners.get(callingUid);
7987            }
7988            final PackageSetting ps = mSettings.mPackages.get(packageName);
7989            PackageParser.Package pkg = mPackages.get(packageName);
7990            final boolean returnAllowed =
7991                    ps != null
7992                    && (isCallerSameApp(packageName, callingUid)
7993                            || canViewInstantApps(callingUid, userId)
7994                            || mInstantAppRegistry.isInstantAccessGranted(
7995                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7996            if (returnAllowed) {
7997                return ps.getInstantApp(userId);
7998            }
7999        }
8000        return false;
8001    }
8002
8003    @Override
8004    public byte[] getInstantAppCookie(String packageName, int userId) {
8005        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8006            return null;
8007        }
8008
8009        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8010                true /* requireFullPermission */, false /* checkShell */,
8011                "getInstantAppCookie");
8012        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8013            return null;
8014        }
8015        synchronized (mPackages) {
8016            return mInstantAppRegistry.getInstantAppCookieLPw(
8017                    packageName, userId);
8018        }
8019    }
8020
8021    @Override
8022    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8023        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8024            return true;
8025        }
8026
8027        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8028                true /* requireFullPermission */, true /* checkShell */,
8029                "setInstantAppCookie");
8030        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8031            return false;
8032        }
8033        synchronized (mPackages) {
8034            return mInstantAppRegistry.setInstantAppCookieLPw(
8035                    packageName, cookie, userId);
8036        }
8037    }
8038
8039    @Override
8040    public Bitmap getInstantAppIcon(String packageName, int userId) {
8041        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8042            return null;
8043        }
8044
8045        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8046            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8047                    "getInstantAppIcon");
8048        }
8049        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8050                true /* requireFullPermission */, false /* checkShell */,
8051                "getInstantAppIcon");
8052
8053        synchronized (mPackages) {
8054            return mInstantAppRegistry.getInstantAppIconLPw(
8055                    packageName, userId);
8056        }
8057    }
8058
8059    private boolean isCallerSameApp(String packageName, int uid) {
8060        PackageParser.Package pkg = mPackages.get(packageName);
8061        return pkg != null
8062                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8063    }
8064
8065    @Override
8066    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8067        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8068            return ParceledListSlice.emptyList();
8069        }
8070        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8071    }
8072
8073    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8074        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8075
8076        // reader
8077        synchronized (mPackages) {
8078            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8079            final int userId = UserHandle.getCallingUserId();
8080            while (i.hasNext()) {
8081                final PackageParser.Package p = i.next();
8082                if (p.applicationInfo == null) continue;
8083
8084                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8085                        && !p.applicationInfo.isDirectBootAware();
8086                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8087                        && p.applicationInfo.isDirectBootAware();
8088
8089                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8090                        && (!mSafeMode || isSystemApp(p))
8091                        && (matchesUnaware || matchesAware)) {
8092                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8093                    if (ps != null) {
8094                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8095                                ps.readUserState(userId), userId);
8096                        if (ai != null) {
8097                            finalList.add(ai);
8098                        }
8099                    }
8100                }
8101            }
8102        }
8103
8104        return finalList;
8105    }
8106
8107    @Override
8108    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8109        return resolveContentProviderInternal(name, flags, userId);
8110    }
8111
8112    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8113        if (!sUserManager.exists(userId)) return null;
8114        flags = updateFlagsForComponent(flags, userId, name);
8115        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8116        // reader
8117        synchronized (mPackages) {
8118            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8119            PackageSetting ps = provider != null
8120                    ? mSettings.mPackages.get(provider.owner.packageName)
8121                    : null;
8122            if (ps != null) {
8123                final boolean isInstantApp = ps.getInstantApp(userId);
8124                // normal application; filter out instant application provider
8125                if (instantAppPkgName == null && isInstantApp) {
8126                    return null;
8127                }
8128                // instant application; filter out other instant applications
8129                if (instantAppPkgName != null
8130                        && isInstantApp
8131                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8132                    return null;
8133                }
8134                // instant application; filter out non-exposed provider
8135                if (instantAppPkgName != null
8136                        && !isInstantApp
8137                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8138                    return null;
8139                }
8140                // provider not enabled
8141                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8142                    return null;
8143                }
8144                return PackageParser.generateProviderInfo(
8145                        provider, flags, ps.readUserState(userId), userId);
8146            }
8147            return null;
8148        }
8149    }
8150
8151    /**
8152     * @deprecated
8153     */
8154    @Deprecated
8155    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8156        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8157            return;
8158        }
8159        // reader
8160        synchronized (mPackages) {
8161            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8162                    .entrySet().iterator();
8163            final int userId = UserHandle.getCallingUserId();
8164            while (i.hasNext()) {
8165                Map.Entry<String, PackageParser.Provider> entry = i.next();
8166                PackageParser.Provider p = entry.getValue();
8167                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8168
8169                if (ps != null && p.syncable
8170                        && (!mSafeMode || (p.info.applicationInfo.flags
8171                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8172                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8173                            ps.readUserState(userId), userId);
8174                    if (info != null) {
8175                        outNames.add(entry.getKey());
8176                        outInfo.add(info);
8177                    }
8178                }
8179            }
8180        }
8181    }
8182
8183    @Override
8184    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8185            int uid, int flags, String metaDataKey) {
8186        final int callingUid = Binder.getCallingUid();
8187        final int userId = processName != null ? UserHandle.getUserId(uid)
8188                : UserHandle.getCallingUserId();
8189        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8190        flags = updateFlagsForComponent(flags, userId, processName);
8191        ArrayList<ProviderInfo> finalList = null;
8192        // reader
8193        synchronized (mPackages) {
8194            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8195            while (i.hasNext()) {
8196                final PackageParser.Provider p = i.next();
8197                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8198                if (ps != null && p.info.authority != null
8199                        && (processName == null
8200                                || (p.info.processName.equals(processName)
8201                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8202                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8203
8204                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8205                    // parameter.
8206                    if (metaDataKey != null
8207                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8208                        continue;
8209                    }
8210                    final ComponentName component =
8211                            new ComponentName(p.info.packageName, p.info.name);
8212                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8213                        continue;
8214                    }
8215                    if (finalList == null) {
8216                        finalList = new ArrayList<ProviderInfo>(3);
8217                    }
8218                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8219                            ps.readUserState(userId), userId);
8220                    if (info != null) {
8221                        finalList.add(info);
8222                    }
8223                }
8224            }
8225        }
8226
8227        if (finalList != null) {
8228            Collections.sort(finalList, mProviderInitOrderSorter);
8229            return new ParceledListSlice<ProviderInfo>(finalList);
8230        }
8231
8232        return ParceledListSlice.emptyList();
8233    }
8234
8235    @Override
8236    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8237        // reader
8238        synchronized (mPackages) {
8239            final int callingUid = Binder.getCallingUid();
8240            final int callingUserId = UserHandle.getUserId(callingUid);
8241            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8242            if (ps == null) return null;
8243            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8244                return null;
8245            }
8246            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8247            return PackageParser.generateInstrumentationInfo(i, flags);
8248        }
8249    }
8250
8251    @Override
8252    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8253            String targetPackage, int flags) {
8254        final int callingUid = Binder.getCallingUid();
8255        final int callingUserId = UserHandle.getUserId(callingUid);
8256        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8257        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8258            return ParceledListSlice.emptyList();
8259        }
8260        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8261    }
8262
8263    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8264            int flags) {
8265        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8266
8267        // reader
8268        synchronized (mPackages) {
8269            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8270            while (i.hasNext()) {
8271                final PackageParser.Instrumentation p = i.next();
8272                if (targetPackage == null
8273                        || targetPackage.equals(p.info.targetPackage)) {
8274                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8275                            flags);
8276                    if (ii != null) {
8277                        finalList.add(ii);
8278                    }
8279                }
8280            }
8281        }
8282
8283        return finalList;
8284    }
8285
8286    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8287        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8288        try {
8289            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8290        } finally {
8291            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8292        }
8293    }
8294
8295    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8296        final File[] files = scanDir.listFiles();
8297        if (ArrayUtils.isEmpty(files)) {
8298            Log.d(TAG, "No files in app dir " + scanDir);
8299            return;
8300        }
8301
8302        if (DEBUG_PACKAGE_SCANNING) {
8303            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8304                    + " flags=0x" + Integer.toHexString(parseFlags));
8305        }
8306        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8307                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8308                mParallelPackageParserCallback)) {
8309            // Submit files for parsing in parallel
8310            int fileCount = 0;
8311            for (File file : files) {
8312                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8313                        && !PackageInstallerService.isStageName(file.getName());
8314                if (!isPackage) {
8315                    // Ignore entries which are not packages
8316                    continue;
8317                }
8318                parallelPackageParser.submit(file, parseFlags);
8319                fileCount++;
8320            }
8321
8322            // Process results one by one
8323            for (; fileCount > 0; fileCount--) {
8324                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8325                Throwable throwable = parseResult.throwable;
8326                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8327
8328                if (throwable == null) {
8329                    // TODO(toddke): move lower in the scan chain
8330                    // Static shared libraries have synthetic package names
8331                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8332                        renameStaticSharedLibraryPackage(parseResult.pkg);
8333                    }
8334                    try {
8335                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8336                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8337                                    currentTime, null);
8338                        }
8339                    } catch (PackageManagerException e) {
8340                        errorCode = e.error;
8341                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8342                    }
8343                } else if (throwable instanceof PackageParser.PackageParserException) {
8344                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8345                            throwable;
8346                    errorCode = e.error;
8347                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8348                } else {
8349                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8350                            + parseResult.scanFile, throwable);
8351                }
8352
8353                // Delete invalid userdata apps
8354                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8355                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8356                    logCriticalInfo(Log.WARN,
8357                            "Deleting invalid package at " + parseResult.scanFile);
8358                    removeCodePathLI(parseResult.scanFile);
8359                }
8360            }
8361        }
8362    }
8363
8364    public static void reportSettingsProblem(int priority, String msg) {
8365        logCriticalInfo(priority, msg);
8366    }
8367
8368    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8369            boolean forceCollect) throws PackageManagerException {
8370        // When upgrading from pre-N MR1, verify the package time stamp using the package
8371        // directory and not the APK file.
8372        final long lastModifiedTime = mIsPreNMR1Upgrade
8373                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8374        // Note that currently skipVerify skips verification on both base and splits for simplicity.
8375        final boolean skipVerify = forceCollect && canSkipFullPackageVerification(pkg);
8376        if (ps != null && !forceCollect
8377                && ps.codePathString.equals(pkg.codePath)
8378                && ps.timeStamp == lastModifiedTime
8379                && !isCompatSignatureUpdateNeeded(pkg)
8380                && !isRecoverSignatureUpdateNeeded(pkg)) {
8381            if (ps.signatures.mSigningDetails.signatures != null
8382                    && ps.signatures.mSigningDetails.signatures.length != 0
8383                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8384                            != SignatureSchemeVersion.UNKNOWN) {
8385                // Optimization: reuse the existing cached signing data
8386                // if the package appears to be unchanged.
8387                pkg.mSigningDetails =
8388                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8389                return;
8390            }
8391
8392            Slog.w(TAG, "PackageSetting for " + ps.name
8393                    + " is missing signatures.  Collecting certs again to recover them.");
8394        } else {
8395            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8396                    (forceCollect ? " (forced)" : ""));
8397        }
8398
8399        try {
8400            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8401            PackageParser.collectCertificates(pkg, skipVerify);
8402        } catch (PackageParserException e) {
8403            throw PackageManagerException.from(e);
8404        } finally {
8405            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8406        }
8407    }
8408
8409    /**
8410     *  Traces a package scan.
8411     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8412     */
8413    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8414            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8416        try {
8417            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8418        } finally {
8419            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8420        }
8421    }
8422
8423    /**
8424     *  Scans a package and returns the newly parsed package.
8425     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8426     */
8427    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8428            long currentTime, UserHandle user) throws PackageManagerException {
8429        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8430        PackageParser pp = new PackageParser();
8431        pp.setSeparateProcesses(mSeparateProcesses);
8432        pp.setOnlyCoreApps(mOnlyCore);
8433        pp.setDisplayMetrics(mMetrics);
8434        pp.setCallback(mPackageParserCallback);
8435
8436        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8437        final PackageParser.Package pkg;
8438        try {
8439            pkg = pp.parsePackage(scanFile, parseFlags);
8440        } catch (PackageParserException e) {
8441            throw PackageManagerException.from(e);
8442        } finally {
8443            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8444        }
8445
8446        // Static shared libraries have synthetic package names
8447        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8448            renameStaticSharedLibraryPackage(pkg);
8449        }
8450
8451        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8452    }
8453
8454    /**
8455     *  Scans a package and returns the newly parsed package.
8456     *  @throws PackageManagerException on a parse error.
8457     */
8458    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8459            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8460            @Nullable UserHandle user)
8461                    throws PackageManagerException {
8462        // If the package has children and this is the first dive in the function
8463        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8464        // packages (parent and children) would be successfully scanned before the
8465        // actual scan since scanning mutates internal state and we want to atomically
8466        // install the package and its children.
8467        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8468            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8469                scanFlags |= SCAN_CHECK_ONLY;
8470            }
8471        } else {
8472            scanFlags &= ~SCAN_CHECK_ONLY;
8473        }
8474
8475        // Scan the parent
8476        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8477                scanFlags, currentTime, user);
8478
8479        // Scan the children
8480        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8481        for (int i = 0; i < childCount; i++) {
8482            PackageParser.Package childPackage = pkg.childPackages.get(i);
8483            addForInitLI(childPackage, parseFlags, scanFlags,
8484                    currentTime, user);
8485        }
8486
8487
8488        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8489            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8490        }
8491
8492        return scannedPkg;
8493    }
8494
8495    /**
8496     * Returns if full apk verification can be skipped for the whole package, including the splits.
8497     */
8498    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8499        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8500            return false;
8501        }
8502        // TODO: Allow base and splits to be verified individually.
8503        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8504            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8505                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8506                    return false;
8507                }
8508            }
8509        }
8510        return true;
8511    }
8512
8513    /**
8514     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8515     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8516     * match one in a trusted source, and should be done separately.
8517     */
8518    private boolean canSkipFullApkVerification(String apkPath) {
8519        byte[] rootHashObserved = null;
8520        try {
8521            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8522            if (rootHashObserved == null) {
8523                return false;  // APK does not contain Merkle tree root hash.
8524            }
8525            synchronized (mInstallLock) {
8526                // Returns whether the observed root hash matches what kernel has.
8527                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8528                return true;
8529            }
8530        } catch (InstallerException | IOException | DigestException |
8531                NoSuchAlgorithmException e) {
8532            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8533        }
8534        return false;
8535    }
8536
8537    // Temporary to catch potential issues with refactoring
8538    private static boolean REFACTOR_DEBUG = true;
8539    /**
8540     * Adds a new package to the internal data structures during platform initialization.
8541     * <p>After adding, the package is known to the system and available for querying.
8542     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8543     * etc...], additional checks are performed. Basic verification [such as ensuring
8544     * matching signatures, checking version codes, etc...] occurs if the package is
8545     * identical to a previously known package. If the package fails a signature check,
8546     * the version installed on /data will be removed. If the version of the new package
8547     * is less than or equal than the version on /data, it will be ignored.
8548     * <p>Regardless of the package location, the results are applied to the internal
8549     * structures and the package is made available to the rest of the system.
8550     * <p>NOTE: The return value should be removed. It's the passed in package object.
8551     */
8552    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8553            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8554            @Nullable UserHandle user)
8555                    throws PackageManagerException {
8556        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8557        final String renamedPkgName;
8558        final PackageSetting disabledPkgSetting;
8559        final boolean isSystemPkgUpdated;
8560        final boolean pkgAlreadyExists;
8561        PackageSetting pkgSetting;
8562
8563        // NOTE: installPackageLI() has the same code to setup the package's
8564        // application info. This probably should be done lower in the call
8565        // stack [such as scanPackageOnly()]. However, we verify the application
8566        // info prior to that [in scanPackageNew()] and thus have to setup
8567        // the application info early.
8568        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8569        pkg.setApplicationInfoCodePath(pkg.codePath);
8570        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8571        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8572        pkg.setApplicationInfoResourcePath(pkg.codePath);
8573        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8574        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8575
8576        synchronized (mPackages) {
8577            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8578            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8579if (REFACTOR_DEBUG) {
8580Slog.e("TODD",
8581        "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName));
8582}
8583            if (realPkgName != null) {
8584                ensurePackageRenamed(pkg, renamedPkgName);
8585            }
8586            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8587            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8588            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8589            pkgAlreadyExists = pkgSetting != null;
8590            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8591            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8592            isSystemPkgUpdated = disabledPkgSetting != null;
8593
8594            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8595                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8596            }
8597if (REFACTOR_DEBUG) {
8598Slog.e("TODD",
8599        "SSP? " + scanSystemPartition
8600        + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"")
8601        + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():""));
8602}
8603
8604            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8605                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8606                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8607                    : null;
8608            if (DEBUG_PACKAGE_SCANNING
8609                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8610                    && sharedUserSetting != null) {
8611                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8612                        + " (uid=" + sharedUserSetting.userId + "):"
8613                        + " packages=" + sharedUserSetting.packages);
8614if (REFACTOR_DEBUG) {
8615Slog.e("TODD",
8616        "Shared UserID " + pkg.mSharedUserId
8617        + " (uid=" + sharedUserSetting.userId + "):"
8618        + " packages=" + sharedUserSetting.packages);
8619}
8620            }
8621
8622            if (scanSystemPartition) {
8623                // Potentially prune child packages. If the application on the /system
8624                // partition has been updated via OTA, but, is still disabled by a
8625                // version on /data, cycle through all of its children packages and
8626                // remove children that are no longer defined.
8627                if (isSystemPkgUpdated) {
8628if (REFACTOR_DEBUG) {
8629Slog.e("TODD",
8630        "Disable child packages");
8631}
8632                    final int scannedChildCount = (pkg.childPackages != null)
8633                            ? pkg.childPackages.size() : 0;
8634                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8635                            ? disabledPkgSetting.childPackageNames.size() : 0;
8636                    for (int i = 0; i < disabledChildCount; i++) {
8637                        String disabledChildPackageName =
8638                                disabledPkgSetting.childPackageNames.get(i);
8639                        boolean disabledPackageAvailable = false;
8640                        for (int j = 0; j < scannedChildCount; j++) {
8641                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8642                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8643if (REFACTOR_DEBUG) {
8644Slog.e("TODD",
8645        "Ignore " + disabledChildPackageName);
8646}
8647                                disabledPackageAvailable = true;
8648                                break;
8649                            }
8650                        }
8651                        if (!disabledPackageAvailable) {
8652if (REFACTOR_DEBUG) {
8653Slog.e("TODD",
8654        "Disable " + disabledChildPackageName);
8655}
8656                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8657                        }
8658                    }
8659                    // we're updating the disabled package, so, scan it as the package setting
8660                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8661                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8662                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8663                            (pkg == mPlatformPackage), user);
8664if (REFACTOR_DEBUG) {
8665Slog.e("TODD",
8666        "Scan disabled system package");
8667Slog.e("TODD",
8668        "Pre: " + request.pkgSetting.dumpState_temp());
8669}
8670final ScanResult result =
8671                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8672if (REFACTOR_DEBUG) {
8673Slog.e("TODD",
8674        "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan"));
8675}
8676                }
8677            }
8678        }
8679
8680        final boolean newPkgChangedPaths =
8681                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8682if (REFACTOR_DEBUG) {
8683Slog.e("TODD",
8684        "paths changed? " + newPkgChangedPaths
8685        + "; old: " + pkg.codePath
8686        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString));
8687}
8688        final boolean newPkgVersionGreater =
8689                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8690if (REFACTOR_DEBUG) {
8691Slog.e("TODD",
8692        "version greater? " + newPkgVersionGreater
8693        + "; old: " + pkg.getLongVersionCode()
8694        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode));
8695}
8696        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8697                && newPkgChangedPaths && newPkgVersionGreater;
8698if (REFACTOR_DEBUG) {
8699    Slog.e("TODD",
8700            "system better? " + isSystemPkgBetter);
8701}
8702        if (isSystemPkgBetter) {
8703            // The version of the application on /system is greater than the version on
8704            // /data. Switch back to the application on /system.
8705            // It's safe to assume the application on /system will correctly scan. If not,
8706            // there won't be a working copy of the application.
8707            synchronized (mPackages) {
8708                // just remove the loaded entries from package lists
8709                mPackages.remove(pkgSetting.name);
8710            }
8711
8712            logCriticalInfo(Log.WARN,
8713                    "System package updated;"
8714                    + " name: " + pkgSetting.name
8715                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8716                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8717if (REFACTOR_DEBUG) {
8718Slog.e("TODD",
8719        "System package changed;"
8720        + " name: " + pkgSetting.name
8721        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8722        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8723}
8724
8725            final InstallArgs args = createInstallArgsForExisting(
8726                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8727                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8728            args.cleanUpResourcesLI();
8729            synchronized (mPackages) {
8730                mSettings.enableSystemPackageLPw(pkgSetting.name);
8731            }
8732        }
8733
8734        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8735if (REFACTOR_DEBUG) {
8736Slog.e("TODD",
8737        "THROW exception; system pkg version not good enough");
8738}
8739            // The version of the application on the /system partition is less than or
8740            // equal to the version on the /data partition. Throw an exception and use
8741            // the application already installed on the /data partition.
8742            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8743                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8744                    + " better than this " + pkg.getLongVersionCode());
8745        }
8746
8747        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8748        // force re-collecting certificate. Full apk verification will happen unless apk verity is
8749        // set up for the file. In that case, only small part of the apk is verified upfront.
8750        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8751                disabledPkgSetting);
8752        collectCertificatesLI(pkgSetting, pkg, forceCollect);
8753
8754        boolean shouldHideSystemApp = false;
8755        // A new application appeared on /system, but, we already have a copy of
8756        // the application installed on /data.
8757        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8758                && !pkgSetting.isSystem()) {
8759
8760            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8761                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8762                logCriticalInfo(Log.WARN,
8763                        "System package signature mismatch;"
8764                        + " name: " + pkgSetting.name);
8765if (REFACTOR_DEBUG) {
8766Slog.e("TODD",
8767        "System package signature mismatch;"
8768        + " name: " + pkgSetting.name);
8769}
8770                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8771                        "scanPackageInternalLI")) {
8772                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8773                }
8774                pkgSetting = null;
8775            } else if (newPkgVersionGreater) {
8776                // The application on /system is newer than the application on /data.
8777                // Simply remove the application on /data [keeping application data]
8778                // and replace it with the version on /system.
8779                logCriticalInfo(Log.WARN,
8780                        "System package enabled;"
8781                        + " name: " + pkgSetting.name
8782                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8783                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8784if (REFACTOR_DEBUG) {
8785Slog.e("TODD",
8786        "System package enabled;"
8787        + " name: " + pkgSetting.name
8788        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8789        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8790}
8791                InstallArgs args = createInstallArgsForExisting(
8792                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8793                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8794                synchronized (mInstallLock) {
8795                    args.cleanUpResourcesLI();
8796                }
8797            } else {
8798                // The application on /system is older than the application on /data. Hide
8799                // the application on /system and the version on /data will be scanned later
8800                // and re-added like an update.
8801                shouldHideSystemApp = true;
8802                logCriticalInfo(Log.INFO,
8803                        "System package disabled;"
8804                        + " name: " + pkgSetting.name
8805                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8806                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8807if (REFACTOR_DEBUG) {
8808Slog.e("TODD",
8809        "System package disabled;"
8810        + " name: " + pkgSetting.name
8811        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8812        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8813}
8814            }
8815        }
8816
8817if (REFACTOR_DEBUG) {
8818Slog.e("TODD",
8819        "Scan package");
8820Slog.e("TODD",
8821        "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8822}
8823        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8824                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8825if (REFACTOR_DEBUG) {
8826pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8827Slog.e("TODD",
8828        "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8829}
8830
8831        if (shouldHideSystemApp) {
8832if (REFACTOR_DEBUG) {
8833Slog.e("TODD",
8834        "Disable package: " + pkg.packageName);
8835}
8836            synchronized (mPackages) {
8837                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8838            }
8839        }
8840        return scannedPkg;
8841    }
8842
8843    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8844        // Derive the new package synthetic package name
8845        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8846                + pkg.staticSharedLibVersion);
8847    }
8848
8849    private static String fixProcessName(String defProcessName,
8850            String processName) {
8851        if (processName == null) {
8852            return defProcessName;
8853        }
8854        return processName;
8855    }
8856
8857    /**
8858     * Enforces that only the system UID or root's UID can call a method exposed
8859     * via Binder.
8860     *
8861     * @param message used as message if SecurityException is thrown
8862     * @throws SecurityException if the caller is not system or root
8863     */
8864    private static final void enforceSystemOrRoot(String message) {
8865        final int uid = Binder.getCallingUid();
8866        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8867            throw new SecurityException(message);
8868        }
8869    }
8870
8871    @Override
8872    public void performFstrimIfNeeded() {
8873        enforceSystemOrRoot("Only the system can request fstrim");
8874
8875        // Before everything else, see whether we need to fstrim.
8876        try {
8877            IStorageManager sm = PackageHelper.getStorageManager();
8878            if (sm != null) {
8879                boolean doTrim = false;
8880                final long interval = android.provider.Settings.Global.getLong(
8881                        mContext.getContentResolver(),
8882                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8883                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8884                if (interval > 0) {
8885                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8886                    if (timeSinceLast > interval) {
8887                        doTrim = true;
8888                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8889                                + "; running immediately");
8890                    }
8891                }
8892                if (doTrim) {
8893                    final boolean dexOptDialogShown;
8894                    synchronized (mPackages) {
8895                        dexOptDialogShown = mDexOptDialogShown;
8896                    }
8897                    if (!isFirstBoot() && dexOptDialogShown) {
8898                        try {
8899                            ActivityManager.getService().showBootMessage(
8900                                    mContext.getResources().getString(
8901                                            R.string.android_upgrading_fstrim), true);
8902                        } catch (RemoteException e) {
8903                        }
8904                    }
8905                    sm.runMaintenance();
8906                }
8907            } else {
8908                Slog.e(TAG, "storageManager service unavailable!");
8909            }
8910        } catch (RemoteException e) {
8911            // Can't happen; StorageManagerService is local
8912        }
8913    }
8914
8915    @Override
8916    public void updatePackagesIfNeeded() {
8917        enforceSystemOrRoot("Only the system can request package update");
8918
8919        // We need to re-extract after an OTA.
8920        boolean causeUpgrade = isUpgrade();
8921
8922        // First boot or factory reset.
8923        // Note: we also handle devices that are upgrading to N right now as if it is their
8924        //       first boot, as they do not have profile data.
8925        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8926
8927        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8928        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8929
8930        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8931            return;
8932        }
8933
8934        List<PackageParser.Package> pkgs;
8935        synchronized (mPackages) {
8936            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8937        }
8938
8939        final long startTime = System.nanoTime();
8940        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8941                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8942                    false /* bootComplete */);
8943
8944        final int elapsedTimeSeconds =
8945                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8946
8947        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8948        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8949        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8950        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8951        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8952    }
8953
8954    /*
8955     * Return the prebuilt profile path given a package base code path.
8956     */
8957    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8958        return pkg.baseCodePath + ".prof";
8959    }
8960
8961    /**
8962     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8963     * containing statistics about the invocation. The array consists of three elements,
8964     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8965     * and {@code numberOfPackagesFailed}.
8966     */
8967    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8968            final String compilerFilter, boolean bootComplete) {
8969
8970        int numberOfPackagesVisited = 0;
8971        int numberOfPackagesOptimized = 0;
8972        int numberOfPackagesSkipped = 0;
8973        int numberOfPackagesFailed = 0;
8974        final int numberOfPackagesToDexopt = pkgs.size();
8975
8976        for (PackageParser.Package pkg : pkgs) {
8977            numberOfPackagesVisited++;
8978
8979            boolean useProfileForDexopt = false;
8980
8981            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8982                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8983                // that are already compiled.
8984                File profileFile = new File(getPrebuildProfilePath(pkg));
8985                // Copy profile if it exists.
8986                if (profileFile.exists()) {
8987                    try {
8988                        // We could also do this lazily before calling dexopt in
8989                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8990                        // is that we don't have a good way to say "do this only once".
8991                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8992                                pkg.applicationInfo.uid, pkg.packageName,
8993                                ArtManager.getProfileName(null))) {
8994                            Log.e(TAG, "Installer failed to copy system profile!");
8995                        } else {
8996                            // Disabled as this causes speed-profile compilation during first boot
8997                            // even if things are already compiled.
8998                            // useProfileForDexopt = true;
8999                        }
9000                    } catch (Exception e) {
9001                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9002                                e);
9003                    }
9004                } else {
9005                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9006                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9007                    // minimize the number off apps being speed-profile compiled during first boot.
9008                    // The other paths will not change the filter.
9009                    if (disabledPs != null && disabledPs.pkg.isStub) {
9010                        // The package is the stub one, remove the stub suffix to get the normal
9011                        // package and APK names.
9012                        String systemProfilePath =
9013                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9014                        profileFile = new File(systemProfilePath);
9015                        // If we have a profile for a compressed APK, copy it to the reference
9016                        // location.
9017                        // Note that copying the profile here will cause it to override the
9018                        // reference profile every OTA even though the existing reference profile
9019                        // may have more data. We can't copy during decompression since the
9020                        // directories are not set up at that point.
9021                        if (profileFile.exists()) {
9022                            try {
9023                                // We could also do this lazily before calling dexopt in
9024                                // PackageDexOptimizer to prevent this happening on first boot. The
9025                                // issue is that we don't have a good way to say "do this only
9026                                // once".
9027                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9028                                        pkg.applicationInfo.uid, pkg.packageName,
9029                                        ArtManager.getProfileName(null))) {
9030                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9031                                } else {
9032                                    useProfileForDexopt = true;
9033                                }
9034                            } catch (Exception e) {
9035                                Log.e(TAG, "Failed to copy profile " +
9036                                        profileFile.getAbsolutePath() + " ", e);
9037                            }
9038                        }
9039                    }
9040                }
9041            }
9042
9043            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9044                if (DEBUG_DEXOPT) {
9045                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9046                }
9047                numberOfPackagesSkipped++;
9048                continue;
9049            }
9050
9051            if (DEBUG_DEXOPT) {
9052                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9053                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9054            }
9055
9056            if (showDialog) {
9057                try {
9058                    ActivityManager.getService().showBootMessage(
9059                            mContext.getResources().getString(R.string.android_upgrading_apk,
9060                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9061                } catch (RemoteException e) {
9062                }
9063                synchronized (mPackages) {
9064                    mDexOptDialogShown = true;
9065                }
9066            }
9067
9068            String pkgCompilerFilter = compilerFilter;
9069            if (useProfileForDexopt) {
9070                // Use background dexopt mode to try and use the profile. Note that this does not
9071                // guarantee usage of the profile.
9072                pkgCompilerFilter =
9073                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9074                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9075            }
9076
9077            // checkProfiles is false to avoid merging profiles during boot which
9078            // might interfere with background compilation (b/28612421).
9079            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9080            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9081            // trade-off worth doing to save boot time work.
9082            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9083            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9084                    pkg.packageName,
9085                    pkgCompilerFilter,
9086                    dexoptFlags));
9087
9088            switch (primaryDexOptStaus) {
9089                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9090                    numberOfPackagesOptimized++;
9091                    break;
9092                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9093                    numberOfPackagesSkipped++;
9094                    break;
9095                case PackageDexOptimizer.DEX_OPT_FAILED:
9096                    numberOfPackagesFailed++;
9097                    break;
9098                default:
9099                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9100                    break;
9101            }
9102        }
9103
9104        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9105                numberOfPackagesFailed };
9106    }
9107
9108    @Override
9109    public void notifyPackageUse(String packageName, int reason) {
9110        synchronized (mPackages) {
9111            final int callingUid = Binder.getCallingUid();
9112            final int callingUserId = UserHandle.getUserId(callingUid);
9113            if (getInstantAppPackageName(callingUid) != null) {
9114                if (!isCallerSameApp(packageName, callingUid)) {
9115                    return;
9116                }
9117            } else {
9118                if (isInstantApp(packageName, callingUserId)) {
9119                    return;
9120                }
9121            }
9122            notifyPackageUseLocked(packageName, reason);
9123        }
9124    }
9125
9126    private void notifyPackageUseLocked(String packageName, int reason) {
9127        final PackageParser.Package p = mPackages.get(packageName);
9128        if (p == null) {
9129            return;
9130        }
9131        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9132    }
9133
9134    @Override
9135    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9136            List<String> classPaths, String loaderIsa) {
9137        int userId = UserHandle.getCallingUserId();
9138        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9139        if (ai == null) {
9140            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9141                + loadingPackageName + ", user=" + userId);
9142            return;
9143        }
9144        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9145    }
9146
9147    @Override
9148    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9149            IDexModuleRegisterCallback callback) {
9150        int userId = UserHandle.getCallingUserId();
9151        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9152        DexManager.RegisterDexModuleResult result;
9153        if (ai == null) {
9154            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9155                     " calling user. package=" + packageName + ", user=" + userId);
9156            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9157        } else {
9158            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9159        }
9160
9161        if (callback != null) {
9162            mHandler.post(() -> {
9163                try {
9164                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9165                } catch (RemoteException e) {
9166                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9167                }
9168            });
9169        }
9170    }
9171
9172    /**
9173     * Ask the package manager to perform a dex-opt with the given compiler filter.
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 performDexOptMode(String packageName,
9180            boolean checkProfiles, String targetCompilerFilter, boolean force,
9181            boolean bootComplete, String splitName) {
9182        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9183                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9184                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9185        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9186                splitName, flags));
9187    }
9188
9189    /**
9190     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9191     * secondary dex files belonging to the given package.
9192     *
9193     * Note: exposed only for the shell command to allow moving packages explicitly to a
9194     *       definite state.
9195     */
9196    @Override
9197    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9198            boolean force) {
9199        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9200                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9201                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9202                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9203        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9204    }
9205
9206    /*package*/ boolean performDexOpt(DexoptOptions options) {
9207        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9208            return false;
9209        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9210            return false;
9211        }
9212
9213        if (options.isDexoptOnlySecondaryDex()) {
9214            return mDexManager.dexoptSecondaryDex(options);
9215        } else {
9216            int dexoptStatus = performDexOptWithStatus(options);
9217            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9218        }
9219    }
9220
9221    /**
9222     * Perform dexopt on the given package and return one of following result:
9223     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9224     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9225     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9226     */
9227    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9228        return performDexOptTraced(options);
9229    }
9230
9231    private int performDexOptTraced(DexoptOptions options) {
9232        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9233        try {
9234            return performDexOptInternal(options);
9235        } finally {
9236            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9237        }
9238    }
9239
9240    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9241    // if the package can now be considered up to date for the given filter.
9242    private int performDexOptInternal(DexoptOptions options) {
9243        PackageParser.Package p;
9244        synchronized (mPackages) {
9245            p = mPackages.get(options.getPackageName());
9246            if (p == null) {
9247                // Package could not be found. Report failure.
9248                return PackageDexOptimizer.DEX_OPT_FAILED;
9249            }
9250            mPackageUsage.maybeWriteAsync(mPackages);
9251            mCompilerStats.maybeWriteAsync();
9252        }
9253        long callingId = Binder.clearCallingIdentity();
9254        try {
9255            synchronized (mInstallLock) {
9256                return performDexOptInternalWithDependenciesLI(p, options);
9257            }
9258        } finally {
9259            Binder.restoreCallingIdentity(callingId);
9260        }
9261    }
9262
9263    public ArraySet<String> getOptimizablePackages() {
9264        ArraySet<String> pkgs = new ArraySet<String>();
9265        synchronized (mPackages) {
9266            for (PackageParser.Package p : mPackages.values()) {
9267                if (PackageDexOptimizer.canOptimizePackage(p)) {
9268                    pkgs.add(p.packageName);
9269                }
9270            }
9271        }
9272        return pkgs;
9273    }
9274
9275    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9276            DexoptOptions options) {
9277        // Select the dex optimizer based on the force parameter.
9278        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9279        //       allocate an object here.
9280        PackageDexOptimizer pdo = options.isForce()
9281                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9282                : mPackageDexOptimizer;
9283
9284        // Dexopt all dependencies first. Note: we ignore the return value and march on
9285        // on errors.
9286        // Note that we are going to call performDexOpt on those libraries as many times as
9287        // they are referenced in packages. When we do a batch of performDexOpt (for example
9288        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9289        // and the first package that uses the library will dexopt it. The
9290        // others will see that the compiled code for the library is up to date.
9291        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9292        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9293        if (!deps.isEmpty()) {
9294            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9295                    options.getCompilerFilter(), options.getSplitName(),
9296                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9297            for (PackageParser.Package depPackage : deps) {
9298                // TODO: Analyze and investigate if we (should) profile libraries.
9299                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9300                        getOrCreateCompilerPackageStats(depPackage),
9301                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9302            }
9303        }
9304        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9305                getOrCreateCompilerPackageStats(p),
9306                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9307    }
9308
9309    /**
9310     * Reconcile the information we have about the secondary dex files belonging to
9311     * {@code packagName} and the actual dex files. For all dex files that were
9312     * deleted, update the internal records and delete the generated oat files.
9313     */
9314    @Override
9315    public void reconcileSecondaryDexFiles(String packageName) {
9316        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9317            return;
9318        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9319            return;
9320        }
9321        mDexManager.reconcileSecondaryDexFiles(packageName);
9322    }
9323
9324    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9325    // a reference there.
9326    /*package*/ DexManager getDexManager() {
9327        return mDexManager;
9328    }
9329
9330    /**
9331     * Execute the background dexopt job immediately.
9332     */
9333    @Override
9334    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9335        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9336            return false;
9337        }
9338        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9339    }
9340
9341    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9342        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9343                || p.usesStaticLibraries != null) {
9344            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9345            Set<String> collectedNames = new HashSet<>();
9346            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9347
9348            retValue.remove(p);
9349
9350            return retValue;
9351        } else {
9352            return Collections.emptyList();
9353        }
9354    }
9355
9356    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9357            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9358        if (!collectedNames.contains(p.packageName)) {
9359            collectedNames.add(p.packageName);
9360            collected.add(p);
9361
9362            if (p.usesLibraries != null) {
9363                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9364                        null, collected, collectedNames);
9365            }
9366            if (p.usesOptionalLibraries != null) {
9367                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9368                        null, collected, collectedNames);
9369            }
9370            if (p.usesStaticLibraries != null) {
9371                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9372                        p.usesStaticLibrariesVersions, collected, collectedNames);
9373            }
9374        }
9375    }
9376
9377    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9378            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9379        final int libNameCount = libs.size();
9380        for (int i = 0; i < libNameCount; i++) {
9381            String libName = libs.get(i);
9382            long version = (versions != null && versions.length == libNameCount)
9383                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9384            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9385            if (libPkg != null) {
9386                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9387            }
9388        }
9389    }
9390
9391    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9392        synchronized (mPackages) {
9393            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9394            if (libEntry != null) {
9395                return mPackages.get(libEntry.apk);
9396            }
9397            return null;
9398        }
9399    }
9400
9401    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9402        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9403        if (versionedLib == null) {
9404            return null;
9405        }
9406        return versionedLib.get(version);
9407    }
9408
9409    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9410        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9411                pkg.staticSharedLibName);
9412        if (versionedLib == null) {
9413            return null;
9414        }
9415        long previousLibVersion = -1;
9416        final int versionCount = versionedLib.size();
9417        for (int i = 0; i < versionCount; i++) {
9418            final long libVersion = versionedLib.keyAt(i);
9419            if (libVersion < pkg.staticSharedLibVersion) {
9420                previousLibVersion = Math.max(previousLibVersion, libVersion);
9421            }
9422        }
9423        if (previousLibVersion >= 0) {
9424            return versionedLib.get(previousLibVersion);
9425        }
9426        return null;
9427    }
9428
9429    public void shutdown() {
9430        mPackageUsage.writeNow(mPackages);
9431        mCompilerStats.writeNow();
9432        mDexManager.writePackageDexUsageNow();
9433    }
9434
9435    @Override
9436    public void dumpProfiles(String packageName) {
9437        PackageParser.Package pkg;
9438        synchronized (mPackages) {
9439            pkg = mPackages.get(packageName);
9440            if (pkg == null) {
9441                throw new IllegalArgumentException("Unknown package: " + packageName);
9442            }
9443        }
9444        /* Only the shell, root, or the app user should be able to dump profiles. */
9445        int callingUid = Binder.getCallingUid();
9446        if (callingUid != Process.SHELL_UID &&
9447            callingUid != Process.ROOT_UID &&
9448            callingUid != pkg.applicationInfo.uid) {
9449            throw new SecurityException("dumpProfiles");
9450        }
9451
9452        synchronized (mInstallLock) {
9453            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9454            mArtManagerService.dumpProfiles(pkg);
9455            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9456        }
9457    }
9458
9459    @Override
9460    public void forceDexOpt(String packageName) {
9461        enforceSystemOrRoot("forceDexOpt");
9462
9463        PackageParser.Package pkg;
9464        synchronized (mPackages) {
9465            pkg = mPackages.get(packageName);
9466            if (pkg == null) {
9467                throw new IllegalArgumentException("Unknown package: " + packageName);
9468            }
9469        }
9470
9471        synchronized (mInstallLock) {
9472            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9473
9474            // Whoever is calling forceDexOpt wants a compiled package.
9475            // Don't use profiles since that may cause compilation to be skipped.
9476            final int res = performDexOptInternalWithDependenciesLI(
9477                    pkg,
9478                    new DexoptOptions(packageName,
9479                            getDefaultCompilerFilter(),
9480                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9481
9482            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9483            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9484                throw new IllegalStateException("Failed to dexopt: " + res);
9485            }
9486        }
9487    }
9488
9489    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9490        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9491            Slog.w(TAG, "Unable to update from " + oldPkg.name
9492                    + " to " + newPkg.packageName
9493                    + ": old package not in system partition");
9494            return false;
9495        } else if (mPackages.get(oldPkg.name) != null) {
9496            Slog.w(TAG, "Unable to update from " + oldPkg.name
9497                    + " to " + newPkg.packageName
9498                    + ": old package still exists");
9499            return false;
9500        }
9501        return true;
9502    }
9503
9504    void removeCodePathLI(File codePath) {
9505        if (codePath.isDirectory()) {
9506            try {
9507                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9508            } catch (InstallerException e) {
9509                Slog.w(TAG, "Failed to remove code path", e);
9510            }
9511        } else {
9512            codePath.delete();
9513        }
9514    }
9515
9516    private int[] resolveUserIds(int userId) {
9517        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9518    }
9519
9520    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9521        if (pkg == null) {
9522            Slog.wtf(TAG, "Package was null!", new Throwable());
9523            return;
9524        }
9525        clearAppDataLeafLIF(pkg, userId, flags);
9526        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9527        for (int i = 0; i < childCount; i++) {
9528            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9529        }
9530
9531        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9532    }
9533
9534    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9535        final PackageSetting ps;
9536        synchronized (mPackages) {
9537            ps = mSettings.mPackages.get(pkg.packageName);
9538        }
9539        for (int realUserId : resolveUserIds(userId)) {
9540            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9541            try {
9542                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9543                        ceDataInode);
9544            } catch (InstallerException e) {
9545                Slog.w(TAG, String.valueOf(e));
9546            }
9547        }
9548    }
9549
9550    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9551        if (pkg == null) {
9552            Slog.wtf(TAG, "Package was null!", new Throwable());
9553            return;
9554        }
9555        destroyAppDataLeafLIF(pkg, userId, flags);
9556        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9557        for (int i = 0; i < childCount; i++) {
9558            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9559        }
9560    }
9561
9562    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9563        final PackageSetting ps;
9564        synchronized (mPackages) {
9565            ps = mSettings.mPackages.get(pkg.packageName);
9566        }
9567        for (int realUserId : resolveUserIds(userId)) {
9568            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9569            try {
9570                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9571                        ceDataInode);
9572            } catch (InstallerException e) {
9573                Slog.w(TAG, String.valueOf(e));
9574            }
9575            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9576        }
9577    }
9578
9579    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9580        if (pkg == null) {
9581            Slog.wtf(TAG, "Package was null!", new Throwable());
9582            return;
9583        }
9584        destroyAppProfilesLeafLIF(pkg);
9585        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9586        for (int i = 0; i < childCount; i++) {
9587            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9588        }
9589    }
9590
9591    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9592        try {
9593            mInstaller.destroyAppProfiles(pkg.packageName);
9594        } catch (InstallerException e) {
9595            Slog.w(TAG, String.valueOf(e));
9596        }
9597    }
9598
9599    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9600        if (pkg == null) {
9601            Slog.wtf(TAG, "Package was null!", new Throwable());
9602            return;
9603        }
9604        mArtManagerService.clearAppProfiles(pkg);
9605        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9606        for (int i = 0; i < childCount; i++) {
9607            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9608        }
9609    }
9610
9611    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9612            long lastUpdateTime) {
9613        // Set parent install/update time
9614        PackageSetting ps = (PackageSetting) pkg.mExtras;
9615        if (ps != null) {
9616            ps.firstInstallTime = firstInstallTime;
9617            ps.lastUpdateTime = lastUpdateTime;
9618        }
9619        // Set children install/update time
9620        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9621        for (int i = 0; i < childCount; i++) {
9622            PackageParser.Package childPkg = pkg.childPackages.get(i);
9623            ps = (PackageSetting) childPkg.mExtras;
9624            if (ps != null) {
9625                ps.firstInstallTime = firstInstallTime;
9626                ps.lastUpdateTime = lastUpdateTime;
9627            }
9628        }
9629    }
9630
9631    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9632            SharedLibraryEntry file,
9633            PackageParser.Package changingLib) {
9634        if (file.path != null) {
9635            usesLibraryFiles.add(file.path);
9636            return;
9637        }
9638        PackageParser.Package p = mPackages.get(file.apk);
9639        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9640            // If we are doing this while in the middle of updating a library apk,
9641            // then we need to make sure to use that new apk for determining the
9642            // dependencies here.  (We haven't yet finished committing the new apk
9643            // to the package manager state.)
9644            if (p == null || p.packageName.equals(changingLib.packageName)) {
9645                p = changingLib;
9646            }
9647        }
9648        if (p != null) {
9649            usesLibraryFiles.addAll(p.getAllCodePaths());
9650            if (p.usesLibraryFiles != null) {
9651                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9652            }
9653        }
9654    }
9655
9656    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9657            PackageParser.Package changingLib) throws PackageManagerException {
9658        if (pkg == null) {
9659            return;
9660        }
9661        // The collection used here must maintain the order of addition (so
9662        // that libraries are searched in the correct order) and must have no
9663        // duplicates.
9664        Set<String> usesLibraryFiles = null;
9665        if (pkg.usesLibraries != null) {
9666            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9667                    null, null, pkg.packageName, changingLib, true,
9668                    pkg.applicationInfo.targetSdkVersion, null);
9669        }
9670        if (pkg.usesStaticLibraries != null) {
9671            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9672                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9673                    pkg.packageName, changingLib, true,
9674                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9675        }
9676        if (pkg.usesOptionalLibraries != null) {
9677            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9678                    null, null, pkg.packageName, changingLib, false,
9679                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9680        }
9681        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9682            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9683        } else {
9684            pkg.usesLibraryFiles = null;
9685        }
9686    }
9687
9688    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9689            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9690            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9691            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9692            throws PackageManagerException {
9693        final int libCount = requestedLibraries.size();
9694        for (int i = 0; i < libCount; i++) {
9695            final String libName = requestedLibraries.get(i);
9696            final long libVersion = requiredVersions != null ? requiredVersions[i]
9697                    : SharedLibraryInfo.VERSION_UNDEFINED;
9698            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9699            if (libEntry == null) {
9700                if (required) {
9701                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9702                            "Package " + packageName + " requires unavailable shared library "
9703                                    + libName + "; failing!");
9704                } else if (DEBUG_SHARED_LIBRARIES) {
9705                    Slog.i(TAG, "Package " + packageName
9706                            + " desires unavailable shared library "
9707                            + libName + "; ignoring!");
9708                }
9709            } else {
9710                if (requiredVersions != null && requiredCertDigests != null) {
9711                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9712                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9713                            "Package " + packageName + " requires unavailable static shared"
9714                                    + " library " + libName + " version "
9715                                    + libEntry.info.getLongVersion() + "; failing!");
9716                    }
9717
9718                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9719                    if (libPkg == null) {
9720                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9721                                "Package " + packageName + " requires unavailable static shared"
9722                                        + " library; failing!");
9723                    }
9724
9725                    final String[] expectedCertDigests = requiredCertDigests[i];
9726
9727
9728                    if (expectedCertDigests.length > 1) {
9729
9730                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9731                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9732                                ? PackageUtils.computeSignaturesSha256Digests(
9733                                libPkg.mSigningDetails.signatures)
9734                                : PackageUtils.computeSignaturesSha256Digests(
9735                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9736
9737                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9738                        // target O we don't parse the "additional-certificate" tags similarly
9739                        // how we only consider all certs only for apps targeting O (see above).
9740                        // Therefore, the size check is safe to make.
9741                        if (expectedCertDigests.length != libCertDigests.length) {
9742                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9743                                    "Package " + packageName + " requires differently signed" +
9744                                            " static shared library; failing!");
9745                        }
9746
9747                        // Use a predictable order as signature order may vary
9748                        Arrays.sort(libCertDigests);
9749                        Arrays.sort(expectedCertDigests);
9750
9751                        final int certCount = libCertDigests.length;
9752                        for (int j = 0; j < certCount; j++) {
9753                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9754                                throw new PackageManagerException(
9755                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9756                                        "Package " + packageName + " requires differently signed" +
9757                                                " static shared library; failing!");
9758                            }
9759                        }
9760                    } else {
9761
9762                        // lib signing cert could have rotated beyond the one expected, check to see
9763                        // if the new one has been blessed by the old
9764                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9765                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9766                            throw new PackageManagerException(
9767                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9768                                    "Package " + packageName + " requires differently signed" +
9769                                            " static shared library; failing!");
9770                        }
9771                    }
9772                }
9773
9774                if (outUsedLibraries == null) {
9775                    // Use LinkedHashSet to preserve the order of files added to
9776                    // usesLibraryFiles while eliminating duplicates.
9777                    outUsedLibraries = new LinkedHashSet<>();
9778                }
9779                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9780            }
9781        }
9782        return outUsedLibraries;
9783    }
9784
9785    private static boolean hasString(List<String> list, List<String> which) {
9786        if (list == null) {
9787            return false;
9788        }
9789        for (int i=list.size()-1; i>=0; i--) {
9790            for (int j=which.size()-1; j>=0; j--) {
9791                if (which.get(j).equals(list.get(i))) {
9792                    return true;
9793                }
9794            }
9795        }
9796        return false;
9797    }
9798
9799    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9800            PackageParser.Package changingPkg) {
9801        ArrayList<PackageParser.Package> res = null;
9802        for (PackageParser.Package pkg : mPackages.values()) {
9803            if (changingPkg != null
9804                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9805                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9806                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9807                            changingPkg.staticSharedLibName)) {
9808                return null;
9809            }
9810            if (res == null) {
9811                res = new ArrayList<>();
9812            }
9813            res.add(pkg);
9814            try {
9815                updateSharedLibrariesLPr(pkg, changingPkg);
9816            } catch (PackageManagerException e) {
9817                // If a system app update or an app and a required lib missing we
9818                // delete the package and for updated system apps keep the data as
9819                // it is better for the user to reinstall than to be in an limbo
9820                // state. Also libs disappearing under an app should never happen
9821                // - just in case.
9822                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9823                    final int flags = pkg.isUpdatedSystemApp()
9824                            ? PackageManager.DELETE_KEEP_DATA : 0;
9825                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9826                            flags , null, true, null);
9827                }
9828                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9829            }
9830        }
9831        return res;
9832    }
9833
9834    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9835            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9836            @Nullable UserHandle user) throws PackageManagerException {
9837        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9838        // If the package has children and this is the first dive in the function
9839        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9840        // whether all packages (parent and children) would be successfully scanned
9841        // before the actual scan since scanning mutates internal state and we want
9842        // to atomically install the package and its children.
9843        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9844            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9845                scanFlags |= SCAN_CHECK_ONLY;
9846            }
9847        } else {
9848            scanFlags &= ~SCAN_CHECK_ONLY;
9849        }
9850
9851        final PackageParser.Package scannedPkg;
9852        try {
9853            // Scan the parent
9854            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9855            // Scan the children
9856            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9857            for (int i = 0; i < childCount; i++) {
9858                PackageParser.Package childPkg = pkg.childPackages.get(i);
9859                scanPackageNewLI(childPkg, parseFlags,
9860                        scanFlags, currentTime, user);
9861            }
9862        } finally {
9863            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9864        }
9865
9866        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9867            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9868        }
9869
9870        return scannedPkg;
9871    }
9872
9873    /** The result of a package scan. */
9874    private static class ScanResult {
9875        /** Whether or not the package scan was successful */
9876        public final boolean success;
9877        /**
9878         * The final package settings. This may be the same object passed in
9879         * the {@link ScanRequest}, but, with modified values.
9880         */
9881        @Nullable public final PackageSetting pkgSetting;
9882        /** ABI code paths that have changed in the package scan */
9883        @Nullable public final List<String> changedAbiCodePath;
9884        public ScanResult(
9885                boolean success,
9886                @Nullable PackageSetting pkgSetting,
9887                @Nullable List<String> changedAbiCodePath) {
9888            this.success = success;
9889            this.pkgSetting = pkgSetting;
9890            this.changedAbiCodePath = changedAbiCodePath;
9891        }
9892    }
9893
9894    /** A package to be scanned */
9895    private static class ScanRequest {
9896        /** The parsed package */
9897        @NonNull public final PackageParser.Package pkg;
9898        /** Shared user settings, if the package has a shared user */
9899        @Nullable public final SharedUserSetting sharedUserSetting;
9900        /**
9901         * Package settings of the currently installed version.
9902         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9903         * during scan.
9904         */
9905        @Nullable public final PackageSetting pkgSetting;
9906        /** A copy of the settings for the currently installed version */
9907        @Nullable public final PackageSetting oldPkgSetting;
9908        /** Package settings for the disabled version on the /system partition */
9909        @Nullable public final PackageSetting disabledPkgSetting;
9910        /** Package settings for the installed version under its original package name */
9911        @Nullable public final PackageSetting originalPkgSetting;
9912        /** The real package name of a renamed application */
9913        @Nullable public final String realPkgName;
9914        public final @ParseFlags int parseFlags;
9915        public final @ScanFlags int scanFlags;
9916        /** The user for which the package is being scanned */
9917        @Nullable public final UserHandle user;
9918        /** Whether or not the platform package is being scanned */
9919        public final boolean isPlatformPackage;
9920        public ScanRequest(
9921                @NonNull PackageParser.Package pkg,
9922                @Nullable SharedUserSetting sharedUserSetting,
9923                @Nullable PackageSetting pkgSetting,
9924                @Nullable PackageSetting disabledPkgSetting,
9925                @Nullable PackageSetting originalPkgSetting,
9926                @Nullable String realPkgName,
9927                @ParseFlags int parseFlags,
9928                @ScanFlags int scanFlags,
9929                boolean isPlatformPackage,
9930                @Nullable UserHandle user) {
9931            this.pkg = pkg;
9932            this.pkgSetting = pkgSetting;
9933            this.sharedUserSetting = sharedUserSetting;
9934            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9935            this.disabledPkgSetting = disabledPkgSetting;
9936            this.originalPkgSetting = originalPkgSetting;
9937            this.realPkgName = realPkgName;
9938            this.parseFlags = parseFlags;
9939            this.scanFlags = scanFlags;
9940            this.isPlatformPackage = isPlatformPackage;
9941            this.user = user;
9942        }
9943    }
9944
9945    /**
9946     * Returns the actual scan flags depending upon the state of the other settings.
9947     * <p>Updated system applications will not have the following flags set
9948     * by default and need to be adjusted after the fact:
9949     * <ul>
9950     * <li>{@link #SCAN_AS_SYSTEM}</li>
9951     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9952     * <li>{@link #SCAN_AS_OEM}</li>
9953     * <li>{@link #SCAN_AS_VENDOR}</li>
9954     * <li>{@link #SCAN_AS_PRODUCT}</li>
9955     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9956     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9957     * </ul>
9958     */
9959    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9960            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9961            PackageParser.Package pkg) {
9962        if (disabledPkgSetting != null) {
9963            // updated system application, must at least have SCAN_AS_SYSTEM
9964            scanFlags |= SCAN_AS_SYSTEM;
9965            if ((disabledPkgSetting.pkgPrivateFlags
9966                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9967                scanFlags |= SCAN_AS_PRIVILEGED;
9968            }
9969            if ((disabledPkgSetting.pkgPrivateFlags
9970                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9971                scanFlags |= SCAN_AS_OEM;
9972            }
9973            if ((disabledPkgSetting.pkgPrivateFlags
9974                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9975                scanFlags |= SCAN_AS_VENDOR;
9976            }
9977            if ((disabledPkgSetting.pkgPrivateFlags
9978                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9979                scanFlags |= SCAN_AS_PRODUCT;
9980            }
9981        }
9982        if (pkgSetting != null) {
9983            final int userId = ((user == null) ? 0 : user.getIdentifier());
9984            if (pkgSetting.getInstantApp(userId)) {
9985                scanFlags |= SCAN_AS_INSTANT_APP;
9986            }
9987            if (pkgSetting.getVirtulalPreload(userId)) {
9988                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9989            }
9990        }
9991
9992        // Scan as privileged apps that share a user with a priv-app.
9993        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9994                && (pkg.mSharedUserId != null)) {
9995            SharedUserSetting sharedUserSetting = null;
9996            try {
9997                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9998            } catch (PackageManagerException ignore) {}
9999            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10000                // Exempt SharedUsers signed with the platform key.
10001                // TODO(b/72378145) Fix this exemption. Force signature apps
10002                // to whitelist their privileged permissions just like other
10003                // priv-apps.
10004                synchronized (mPackages) {
10005                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10006                    if (!pkg.packageName.equals("android")
10007                            && (compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
10008                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10009                        scanFlags |= SCAN_AS_PRIVILEGED;
10010                    }
10011                }
10012            }
10013        }
10014
10015        return scanFlags;
10016    }
10017
10018    @GuardedBy("mInstallLock")
10019    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10020            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10021            @Nullable UserHandle user) throws PackageManagerException {
10022
10023        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10024        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10025        if (realPkgName != null) {
10026            ensurePackageRenamed(pkg, renamedPkgName);
10027        }
10028        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10029        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10030        final PackageSetting disabledPkgSetting =
10031                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10032
10033        if (mTransferedPackages.contains(pkg.packageName)) {
10034            Slog.w(TAG, "Package " + pkg.packageName
10035                    + " was transferred to another, but its .apk remains");
10036        }
10037
10038        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10039        synchronized (mPackages) {
10040            applyPolicy(pkg, parseFlags, scanFlags);
10041            assertPackageIsValid(pkg, parseFlags, scanFlags);
10042
10043            SharedUserSetting sharedUserSetting = null;
10044            if (pkg.mSharedUserId != null) {
10045                // SIDE EFFECTS; may potentially allocate a new shared user
10046                sharedUserSetting = mSettings.getSharedUserLPw(
10047                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10048                if (DEBUG_PACKAGE_SCANNING) {
10049                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10050                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10051                                + " (uid=" + sharedUserSetting.userId + "):"
10052                                + " packages=" + sharedUserSetting.packages);
10053                }
10054            }
10055
10056            boolean scanSucceeded = false;
10057            try {
10058                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10059                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10060                        (pkg == mPlatformPackage), user);
10061                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10062                if (result.success) {
10063                    commitScanResultsLocked(request, result);
10064                }
10065                scanSucceeded = true;
10066            } finally {
10067                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10068                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10069                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10070                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10071                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10072                  }
10073            }
10074        }
10075        return pkg;
10076    }
10077
10078    /**
10079     * Commits the package scan and modifies system state.
10080     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10081     * of committing the package, leaving the system in an inconsistent state.
10082     * This needs to be fixed so, once we get to this point, no errors are
10083     * possible and the system is not left in an inconsistent state.
10084     */
10085    @GuardedBy("mPackages")
10086    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10087            throws PackageManagerException {
10088        final PackageParser.Package pkg = request.pkg;
10089        final @ParseFlags int parseFlags = request.parseFlags;
10090        final @ScanFlags int scanFlags = request.scanFlags;
10091        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10092        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10093        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10094        final UserHandle user = request.user;
10095        final String realPkgName = request.realPkgName;
10096        final PackageSetting pkgSetting = result.pkgSetting;
10097        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10098        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10099
10100        if (newPkgSettingCreated) {
10101            if (originalPkgSetting != null) {
10102                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10103            }
10104            // THROWS: when we can't allocate a user id. add call to check if there's
10105            // enough space to ensure we won't throw; otherwise, don't modify state
10106            mSettings.addUserToSettingLPw(pkgSetting);
10107
10108            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10109                mTransferedPackages.add(originalPkgSetting.name);
10110            }
10111        }
10112        // TODO(toddke): Consider a method specifically for modifying the Package object
10113        // post scan; or, moving this stuff out of the Package object since it has nothing
10114        // to do with the package on disk.
10115        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10116        // for creating the application ID. If we did this earlier, we would be saving the
10117        // correct ID.
10118        pkg.applicationInfo.uid = pkgSetting.appId;
10119
10120        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10121
10122        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10123            mTransferedPackages.add(pkg.packageName);
10124        }
10125
10126        // THROWS: when requested libraries that can't be found. it only changes
10127        // the state of the passed in pkg object, so, move to the top of the method
10128        // and allow it to abort
10129        if ((scanFlags & SCAN_BOOTING) == 0
10130                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10131            // Check all shared libraries and map to their actual file path.
10132            // We only do this here for apps not on a system dir, because those
10133            // are the only ones that can fail an install due to this.  We
10134            // will take care of the system apps by updating all of their
10135            // library paths after the scan is done. Also during the initial
10136            // scan don't update any libs as we do this wholesale after all
10137            // apps are scanned to avoid dependency based scanning.
10138            updateSharedLibrariesLPr(pkg, null);
10139        }
10140
10141        // All versions of a static shared library are referenced with the same
10142        // package name. Internally, we use a synthetic package name to allow
10143        // multiple versions of the same shared library to be installed. So,
10144        // we need to generate the synthetic package name of the latest shared
10145        // library in order to compare signatures.
10146        PackageSetting signatureCheckPs = pkgSetting;
10147        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10148            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10149            if (libraryEntry != null) {
10150                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10151            }
10152        }
10153
10154        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10155        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10156            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10157                // We just determined the app is signed correctly, so bring
10158                // over the latest parsed certs.
10159                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10160            } else {
10161                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10162                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10163                            "Package " + pkg.packageName + " upgrade keys do not match the "
10164                                    + "previously installed version");
10165                } else {
10166                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10167                    String msg = "System package " + pkg.packageName
10168                            + " signature changed; retaining data.";
10169                    reportSettingsProblem(Log.WARN, msg);
10170                }
10171            }
10172        } else {
10173            try {
10174                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10175                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10176                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10177                        pkg.mSigningDetails, compareCompat, compareRecover);
10178                // The new KeySets will be re-added later in the scanning process.
10179                if (compatMatch) {
10180                    synchronized (mPackages) {
10181                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10182                    }
10183                }
10184                // We just determined the app is signed correctly, so bring
10185                // over the latest parsed certs.
10186                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10187
10188
10189                // if this is is a sharedUser, check to see if the new package is signed by a newer
10190                // signing certificate than the existing one, and if so, copy over the new details
10191                if (signatureCheckPs.sharedUser != null
10192                        && pkg.mSigningDetails.hasAncestor(
10193                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10194                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10195                }
10196            } catch (PackageManagerException e) {
10197                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10198                    throw e;
10199                }
10200                // The signature has changed, but this package is in the system
10201                // image...  let's recover!
10202                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10203                // However...  if this package is part of a shared user, but it
10204                // doesn't match the signature of the shared user, let's fail.
10205                // What this means is that you can't change the signatures
10206                // associated with an overall shared user, which doesn't seem all
10207                // that unreasonable.
10208                if (signatureCheckPs.sharedUser != null) {
10209                    if (compareSignatures(
10210                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10211                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10212                        throw new PackageManagerException(
10213                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10214                                "Signature mismatch for shared user: "
10215                                        + pkgSetting.sharedUser);
10216                    }
10217                }
10218                // File a report about this.
10219                String msg = "System package " + pkg.packageName
10220                        + " signature changed; retaining data.";
10221                reportSettingsProblem(Log.WARN, msg);
10222            } catch (IllegalArgumentException e) {
10223
10224                // should never happen: certs matched when checking, but not when comparing
10225                // old to new for sharedUser
10226                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10227                        "Signing certificates comparison made on incomparable signing details"
10228                        + " but somehow passed verifySignatures!");
10229            }
10230        }
10231
10232        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10233            // This package wants to adopt ownership of permissions from
10234            // another package.
10235            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10236                final String origName = pkg.mAdoptPermissions.get(i);
10237                final PackageSetting orig = mSettings.getPackageLPr(origName);
10238                if (orig != null) {
10239                    if (verifyPackageUpdateLPr(orig, pkg)) {
10240                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10241                                + pkg.packageName);
10242                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10243                    }
10244                }
10245            }
10246        }
10247
10248        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10249            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10250                final String codePathString = changedAbiCodePath.get(i);
10251                try {
10252                    mInstaller.rmdex(codePathString,
10253                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10254                } catch (InstallerException ignored) {
10255                }
10256            }
10257        }
10258
10259        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10260            if (oldPkgSetting != null) {
10261                synchronized (mPackages) {
10262                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10263                }
10264            }
10265        } else {
10266            final int userId = user == null ? 0 : user.getIdentifier();
10267            // Modify state for the given package setting
10268            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10269                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10270            if (pkgSetting.getInstantApp(userId)) {
10271                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10272            }
10273        }
10274    }
10275
10276    /**
10277     * Returns the "real" name of the package.
10278     * <p>This may differ from the package's actual name if the application has already
10279     * been installed under one of this package's original names.
10280     */
10281    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10282            @Nullable String renamedPkgName) {
10283        if (isPackageRenamed(pkg, renamedPkgName)) {
10284            return pkg.mRealPackage;
10285        }
10286        return null;
10287    }
10288
10289    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10290    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10291            @Nullable String renamedPkgName) {
10292        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10293    }
10294
10295    /**
10296     * Returns the original package setting.
10297     * <p>A package can migrate its name during an update. In this scenario, a package
10298     * designates a set of names that it considers as one of its original names.
10299     * <p>An original package must be signed identically and it must have the same
10300     * shared user [if any].
10301     */
10302    @GuardedBy("mPackages")
10303    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10304            @Nullable String renamedPkgName) {
10305        if (!isPackageRenamed(pkg, renamedPkgName)) {
10306            return null;
10307        }
10308        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10309            final PackageSetting originalPs =
10310                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10311            if (originalPs != null) {
10312                // the package is already installed under its original name...
10313                // but, should we use it?
10314                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10315                    // the new package is incompatible with the original
10316                    continue;
10317                } else if (originalPs.sharedUser != null) {
10318                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10319                        // the shared user id is incompatible with the original
10320                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10321                                + " to " + pkg.packageName + ": old uid "
10322                                + originalPs.sharedUser.name
10323                                + " differs from " + pkg.mSharedUserId);
10324                        continue;
10325                    }
10326                    // TODO: Add case when shared user id is added [b/28144775]
10327                } else {
10328                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10329                            + pkg.packageName + " to old name " + originalPs.name);
10330                }
10331                return originalPs;
10332            }
10333        }
10334        return null;
10335    }
10336
10337    /**
10338     * Renames the package if it was installed under a different name.
10339     * <p>When we've already installed the package under an original name, update
10340     * the new package so we can continue to have the old name.
10341     */
10342    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10343            @NonNull String renamedPackageName) {
10344        if (pkg.mOriginalPackages == null
10345                || !pkg.mOriginalPackages.contains(renamedPackageName)
10346                || pkg.packageName.equals(renamedPackageName)) {
10347            return;
10348        }
10349        pkg.setPackageName(renamedPackageName);
10350    }
10351
10352    /**
10353     * Just scans the package without any side effects.
10354     * <p>Not entirely true at the moment. There is still one side effect -- this
10355     * method potentially modifies a live {@link PackageSetting} object representing
10356     * the package being scanned. This will be resolved in the future.
10357     *
10358     * @param request Information about the package to be scanned
10359     * @param isUnderFactoryTest Whether or not the device is under factory test
10360     * @param currentTime The current time, in millis
10361     * @return The results of the scan
10362     */
10363    @GuardedBy("mInstallLock")
10364    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10365            boolean isUnderFactoryTest, long currentTime)
10366                    throws PackageManagerException {
10367        final PackageParser.Package pkg = request.pkg;
10368        PackageSetting pkgSetting = request.pkgSetting;
10369        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10370        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10371        final @ParseFlags int parseFlags = request.parseFlags;
10372        final @ScanFlags int scanFlags = request.scanFlags;
10373        final String realPkgName = request.realPkgName;
10374        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10375        final UserHandle user = request.user;
10376        final boolean isPlatformPackage = request.isPlatformPackage;
10377
10378        List<String> changedAbiCodePath = null;
10379
10380        if (DEBUG_PACKAGE_SCANNING) {
10381            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10382                Log.d(TAG, "Scanning package " + pkg.packageName);
10383        }
10384
10385        if (Build.IS_DEBUGGABLE &&
10386                pkg.isPrivileged() &&
10387                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10388            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10389        }
10390
10391        // Initialize package source and resource directories
10392        final File scanFile = new File(pkg.codePath);
10393        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10394        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10395
10396        // We keep references to the derived CPU Abis from settings in oder to reuse
10397        // them in the case where we're not upgrading or booting for the first time.
10398        String primaryCpuAbiFromSettings = null;
10399        String secondaryCpuAbiFromSettings = null;
10400        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10401
10402        if (!needToDeriveAbi) {
10403            if (pkgSetting != null) {
10404                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10405                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10406            } else {
10407                // Re-scanning a system package after uninstalling updates; need to derive ABI
10408                needToDeriveAbi = true;
10409            }
10410        }
10411
10412        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10413            PackageManagerService.reportSettingsProblem(Log.WARN,
10414                    "Package " + pkg.packageName + " shared user changed from "
10415                            + (pkgSetting.sharedUser != null
10416                            ? pkgSetting.sharedUser.name : "<nothing>")
10417                            + " to "
10418                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10419                            + "; replacing with new");
10420            pkgSetting = null;
10421        }
10422
10423        String[] usesStaticLibraries = null;
10424        if (pkg.usesStaticLibraries != null) {
10425            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10426            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10427        }
10428        final boolean createNewPackage = (pkgSetting == null);
10429        if (createNewPackage) {
10430            final String parentPackageName = (pkg.parentPackage != null)
10431                    ? pkg.parentPackage.packageName : null;
10432            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10433            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10434            // REMOVE SharedUserSetting from method; update in a separate call
10435            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10436                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10437                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10438                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10439                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10440                    user, true /*allowInstall*/, instantApp, virtualPreload,
10441                    parentPackageName, pkg.getChildPackageNames(),
10442                    UserManagerService.getInstance(), usesStaticLibraries,
10443                    pkg.usesStaticLibrariesVersions);
10444        } else {
10445            // REMOVE SharedUserSetting from method; update in a separate call.
10446            //
10447            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10448            // secondaryCpuAbi are not known at this point so we always update them
10449            // to null here, only to reset them at a later point.
10450            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10451                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10452                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10453                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10454                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10455                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10456        }
10457        if (createNewPackage && originalPkgSetting != null) {
10458            // This is the initial transition from the original package, so,
10459            // fix up the new package's name now. We must do this after looking
10460            // up the package under its new name, so getPackageLP takes care of
10461            // fiddling things correctly.
10462            pkg.setPackageName(originalPkgSetting.name);
10463
10464            // File a report about this.
10465            String msg = "New package " + pkgSetting.realName
10466                    + " renamed to replace old package " + pkgSetting.name;
10467            reportSettingsProblem(Log.WARN, msg);
10468        }
10469
10470        if (disabledPkgSetting != null) {
10471            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10472        }
10473
10474        SELinuxMMAC.assignSeInfoValue(pkg);
10475
10476        pkg.mExtras = pkgSetting;
10477        pkg.applicationInfo.processName = fixProcessName(
10478                pkg.applicationInfo.packageName,
10479                pkg.applicationInfo.processName);
10480
10481        if (!isPlatformPackage) {
10482            // Get all of our default paths setup
10483            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10484        }
10485
10486        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10487
10488        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10489            if (needToDeriveAbi) {
10490                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10491                final boolean extractNativeLibs = !pkg.isLibrary();
10492                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10493                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10494
10495                // Some system apps still use directory structure for native libraries
10496                // in which case we might end up not detecting abi solely based on apk
10497                // structure. Try to detect abi based on directory structure.
10498                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10499                        pkg.applicationInfo.primaryCpuAbi == null) {
10500                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10501                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10502                }
10503            } else {
10504                // This is not a first boot or an upgrade, don't bother deriving the
10505                // ABI during the scan. Instead, trust the value that was stored in the
10506                // package setting.
10507                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10508                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10509
10510                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10511
10512                if (DEBUG_ABI_SELECTION) {
10513                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10514                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10515                            pkg.applicationInfo.secondaryCpuAbi);
10516                }
10517            }
10518        } else {
10519            if ((scanFlags & SCAN_MOVE) != 0) {
10520                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10521                // but we already have this packages package info in the PackageSetting. We just
10522                // use that and derive the native library path based on the new codepath.
10523                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10524                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10525            }
10526
10527            // Set native library paths again. For moves, the path will be updated based on the
10528            // ABIs we've determined above. For non-moves, the path will be updated based on the
10529            // ABIs we determined during compilation, but the path will depend on the final
10530            // package path (after the rename away from the stage path).
10531            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10532        }
10533
10534        // This is a special case for the "system" package, where the ABI is
10535        // dictated by the zygote configuration (and init.rc). We should keep track
10536        // of this ABI so that we can deal with "normal" applications that run under
10537        // the same UID correctly.
10538        if (isPlatformPackage) {
10539            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10540                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10541        }
10542
10543        // If there's a mismatch between the abi-override in the package setting
10544        // and the abiOverride specified for the install. Warn about this because we
10545        // would've already compiled the app without taking the package setting into
10546        // account.
10547        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10548            if (cpuAbiOverride == null && pkg.packageName != null) {
10549                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10550                        " for package " + pkg.packageName);
10551            }
10552        }
10553
10554        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10555        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10556        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10557
10558        // Copy the derived override back to the parsed package, so that we can
10559        // update the package settings accordingly.
10560        pkg.cpuAbiOverride = cpuAbiOverride;
10561
10562        if (DEBUG_ABI_SELECTION) {
10563            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10564                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10565                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10566        }
10567
10568        // Push the derived path down into PackageSettings so we know what to
10569        // clean up at uninstall time.
10570        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10571
10572        if (DEBUG_ABI_SELECTION) {
10573            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10574                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10575                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10576        }
10577
10578        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10579            // We don't do this here during boot because we can do it all
10580            // at once after scanning all existing packages.
10581            //
10582            // We also do this *before* we perform dexopt on this package, so that
10583            // we can avoid redundant dexopts, and also to make sure we've got the
10584            // code and package path correct.
10585            changedAbiCodePath =
10586                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10587        }
10588
10589        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10590                android.Manifest.permission.FACTORY_TEST)) {
10591            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10592        }
10593
10594        if (isSystemApp(pkg)) {
10595            pkgSetting.isOrphaned = true;
10596        }
10597
10598        // Take care of first install / last update times.
10599        final long scanFileTime = getLastModifiedTime(pkg);
10600        if (currentTime != 0) {
10601            if (pkgSetting.firstInstallTime == 0) {
10602                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10603            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10604                pkgSetting.lastUpdateTime = currentTime;
10605            }
10606        } else if (pkgSetting.firstInstallTime == 0) {
10607            // We need *something*.  Take time time stamp of the file.
10608            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10609        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10610            if (scanFileTime != pkgSetting.timeStamp) {
10611                // A package on the system image has changed; consider this
10612                // to be an update.
10613                pkgSetting.lastUpdateTime = scanFileTime;
10614            }
10615        }
10616        pkgSetting.setTimeStamp(scanFileTime);
10617
10618        pkgSetting.pkg = pkg;
10619        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10620        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10621            pkgSetting.versionCode = pkg.getLongVersionCode();
10622        }
10623        // Update volume if needed
10624        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10625        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10626            Slog.i(PackageManagerService.TAG,
10627                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10628                    + " package " + pkg.packageName
10629                    + " volume from " + pkgSetting.volumeUuid
10630                    + " to " + volumeUuid);
10631            pkgSetting.volumeUuid = volumeUuid;
10632        }
10633
10634        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10635    }
10636
10637    /**
10638     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10639     */
10640    private static boolean apkHasCode(String fileName) {
10641        StrictJarFile jarFile = null;
10642        try {
10643            jarFile = new StrictJarFile(fileName,
10644                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10645            return jarFile.findEntry("classes.dex") != null;
10646        } catch (IOException ignore) {
10647        } finally {
10648            try {
10649                if (jarFile != null) {
10650                    jarFile.close();
10651                }
10652            } catch (IOException ignore) {}
10653        }
10654        return false;
10655    }
10656
10657    /**
10658     * Enforces code policy for the package. This ensures that if an APK has
10659     * declared hasCode="true" in its manifest that the APK actually contains
10660     * code.
10661     *
10662     * @throws PackageManagerException If bytecode could not be found when it should exist
10663     */
10664    private static void assertCodePolicy(PackageParser.Package pkg)
10665            throws PackageManagerException {
10666        final boolean shouldHaveCode =
10667                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10668        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10669            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10670                    "Package " + pkg.baseCodePath + " code is missing");
10671        }
10672
10673        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10674            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10675                final boolean splitShouldHaveCode =
10676                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10677                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10678                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10679                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10680                }
10681            }
10682        }
10683    }
10684
10685    /**
10686     * Applies policy to the parsed package based upon the given policy flags.
10687     * Ensures the package is in a good state.
10688     * <p>
10689     * Implementation detail: This method must NOT have any side effect. It would
10690     * ideally be static, but, it requires locks to read system state.
10691     */
10692    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10693            final @ScanFlags int scanFlags) {
10694        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10695            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10696            if (pkg.applicationInfo.isDirectBootAware()) {
10697                // we're direct boot aware; set for all components
10698                for (PackageParser.Service s : pkg.services) {
10699                    s.info.encryptionAware = s.info.directBootAware = true;
10700                }
10701                for (PackageParser.Provider p : pkg.providers) {
10702                    p.info.encryptionAware = p.info.directBootAware = true;
10703                }
10704                for (PackageParser.Activity a : pkg.activities) {
10705                    a.info.encryptionAware = a.info.directBootAware = true;
10706                }
10707                for (PackageParser.Activity r : pkg.receivers) {
10708                    r.info.encryptionAware = r.info.directBootAware = true;
10709                }
10710            }
10711            if (compressedFileExists(pkg.codePath)) {
10712                pkg.isStub = true;
10713            }
10714        } else {
10715            // non system apps can't be flagged as core
10716            pkg.coreApp = false;
10717            // clear flags not applicable to regular apps
10718            pkg.applicationInfo.flags &=
10719                    ~ApplicationInfo.FLAG_PERSISTENT;
10720            pkg.applicationInfo.privateFlags &=
10721                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10722            pkg.applicationInfo.privateFlags &=
10723                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10724            // clear protected broadcasts
10725            pkg.protectedBroadcasts = null;
10726            // cap permission priorities
10727            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10728                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10729                    pkg.permissionGroups.get(i).info.priority = 0;
10730                }
10731            }
10732        }
10733        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10734            // ignore export request for single user receivers
10735            if (pkg.receivers != null) {
10736                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10737                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10738                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10739                        receiver.info.exported = false;
10740                    }
10741                }
10742            }
10743            // ignore export request for single user services
10744            if (pkg.services != null) {
10745                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10746                    final PackageParser.Service service = pkg.services.get(i);
10747                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10748                        service.info.exported = false;
10749                    }
10750                }
10751            }
10752            // ignore export request for single user providers
10753            if (pkg.providers != null) {
10754                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10755                    final PackageParser.Provider provider = pkg.providers.get(i);
10756                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10757                        provider.info.exported = false;
10758                    }
10759                }
10760            }
10761        }
10762
10763        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10764            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10765        }
10766
10767        if ((scanFlags & SCAN_AS_OEM) != 0) {
10768            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10769        }
10770
10771        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10772            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10773        }
10774
10775        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10776            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10777        }
10778
10779        if (!isSystemApp(pkg)) {
10780            // Only system apps can use these features.
10781            pkg.mOriginalPackages = null;
10782            pkg.mRealPackage = null;
10783            pkg.mAdoptPermissions = null;
10784        }
10785    }
10786
10787    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10788            throws PackageManagerException {
10789        if (object == null) {
10790            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10791        }
10792        return object;
10793    }
10794
10795    /**
10796     * Asserts the parsed package is valid according to the given policy. If the
10797     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10798     * <p>
10799     * Implementation detail: This method must NOT have any side effects. It would
10800     * ideally be static, but, it requires locks to read system state.
10801     *
10802     * @throws PackageManagerException If the package fails any of the validation checks
10803     */
10804    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10805            final @ScanFlags int scanFlags)
10806                    throws PackageManagerException {
10807        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10808            assertCodePolicy(pkg);
10809        }
10810
10811        if (pkg.applicationInfo.getCodePath() == null ||
10812                pkg.applicationInfo.getResourcePath() == null) {
10813            // Bail out. The resource and code paths haven't been set.
10814            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10815                    "Code and resource paths haven't been set correctly");
10816        }
10817
10818        // Make sure we're not adding any bogus keyset info
10819        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10820        ksms.assertScannedPackageValid(pkg);
10821
10822        synchronized (mPackages) {
10823            // The special "android" package can only be defined once
10824            if (pkg.packageName.equals("android")) {
10825                if (mAndroidApplication != null) {
10826                    Slog.w(TAG, "*************************************************");
10827                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10828                    Slog.w(TAG, " codePath=" + pkg.codePath);
10829                    Slog.w(TAG, "*************************************************");
10830                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10831                            "Core android package being redefined.  Skipping.");
10832                }
10833            }
10834
10835            // A package name must be unique; don't allow duplicates
10836            if (mPackages.containsKey(pkg.packageName)) {
10837                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10838                        "Application package " + pkg.packageName
10839                        + " already installed.  Skipping duplicate.");
10840            }
10841
10842            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10843                // Static libs have a synthetic package name containing the version
10844                // but we still want the base name to be unique.
10845                if (mPackages.containsKey(pkg.manifestPackageName)) {
10846                    throw new PackageManagerException(
10847                            "Duplicate static shared lib provider package");
10848                }
10849
10850                // Static shared libraries should have at least O target SDK
10851                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10852                    throw new PackageManagerException(
10853                            "Packages declaring static-shared libs must target O SDK or higher");
10854                }
10855
10856                // Package declaring static a shared lib cannot be instant apps
10857                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10858                    throw new PackageManagerException(
10859                            "Packages declaring static-shared libs cannot be instant apps");
10860                }
10861
10862                // Package declaring static a shared lib cannot be renamed since the package
10863                // name is synthetic and apps can't code around package manager internals.
10864                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10865                    throw new PackageManagerException(
10866                            "Packages declaring static-shared libs cannot be renamed");
10867                }
10868
10869                // Package declaring static a shared lib cannot declare child packages
10870                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10871                    throw new PackageManagerException(
10872                            "Packages declaring static-shared libs cannot have child packages");
10873                }
10874
10875                // Package declaring static a shared lib cannot declare dynamic libs
10876                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10877                    throw new PackageManagerException(
10878                            "Packages declaring static-shared libs cannot declare dynamic libs");
10879                }
10880
10881                // Package declaring static a shared lib cannot declare shared users
10882                if (pkg.mSharedUserId != null) {
10883                    throw new PackageManagerException(
10884                            "Packages declaring static-shared libs cannot declare shared users");
10885                }
10886
10887                // Static shared libs cannot declare activities
10888                if (!pkg.activities.isEmpty()) {
10889                    throw new PackageManagerException(
10890                            "Static shared libs cannot declare activities");
10891                }
10892
10893                // Static shared libs cannot declare services
10894                if (!pkg.services.isEmpty()) {
10895                    throw new PackageManagerException(
10896                            "Static shared libs cannot declare services");
10897                }
10898
10899                // Static shared libs cannot declare providers
10900                if (!pkg.providers.isEmpty()) {
10901                    throw new PackageManagerException(
10902                            "Static shared libs cannot declare content providers");
10903                }
10904
10905                // Static shared libs cannot declare receivers
10906                if (!pkg.receivers.isEmpty()) {
10907                    throw new PackageManagerException(
10908                            "Static shared libs cannot declare broadcast receivers");
10909                }
10910
10911                // Static shared libs cannot declare permission groups
10912                if (!pkg.permissionGroups.isEmpty()) {
10913                    throw new PackageManagerException(
10914                            "Static shared libs cannot declare permission groups");
10915                }
10916
10917                // Static shared libs cannot declare permissions
10918                if (!pkg.permissions.isEmpty()) {
10919                    throw new PackageManagerException(
10920                            "Static shared libs cannot declare permissions");
10921                }
10922
10923                // Static shared libs cannot declare protected broadcasts
10924                if (pkg.protectedBroadcasts != null) {
10925                    throw new PackageManagerException(
10926                            "Static shared libs cannot declare protected broadcasts");
10927                }
10928
10929                // Static shared libs cannot be overlay targets
10930                if (pkg.mOverlayTarget != null) {
10931                    throw new PackageManagerException(
10932                            "Static shared libs cannot be overlay targets");
10933                }
10934
10935                // The version codes must be ordered as lib versions
10936                long minVersionCode = Long.MIN_VALUE;
10937                long maxVersionCode = Long.MAX_VALUE;
10938
10939                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10940                        pkg.staticSharedLibName);
10941                if (versionedLib != null) {
10942                    final int versionCount = versionedLib.size();
10943                    for (int i = 0; i < versionCount; i++) {
10944                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10945                        final long libVersionCode = libInfo.getDeclaringPackage()
10946                                .getLongVersionCode();
10947                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10948                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10949                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10950                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10951                        } else {
10952                            minVersionCode = maxVersionCode = libVersionCode;
10953                            break;
10954                        }
10955                    }
10956                }
10957                if (pkg.getLongVersionCode() < minVersionCode
10958                        || pkg.getLongVersionCode() > maxVersionCode) {
10959                    throw new PackageManagerException("Static shared"
10960                            + " lib version codes must be ordered as lib versions");
10961                }
10962            }
10963
10964            // Only privileged apps and updated privileged apps can add child packages.
10965            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10966                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10967                    throw new PackageManagerException("Only privileged apps can add child "
10968                            + "packages. Ignoring package " + pkg.packageName);
10969                }
10970                final int childCount = pkg.childPackages.size();
10971                for (int i = 0; i < childCount; i++) {
10972                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10973                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10974                            childPkg.packageName)) {
10975                        throw new PackageManagerException("Can't override child of "
10976                                + "another disabled app. Ignoring package " + pkg.packageName);
10977                    }
10978                }
10979            }
10980
10981            // If we're only installing presumed-existing packages, require that the
10982            // scanned APK is both already known and at the path previously established
10983            // for it.  Previously unknown packages we pick up normally, but if we have an
10984            // a priori expectation about this package's install presence, enforce it.
10985            // With a singular exception for new system packages. When an OTA contains
10986            // a new system package, we allow the codepath to change from a system location
10987            // to the user-installed location. If we don't allow this change, any newer,
10988            // user-installed version of the application will be ignored.
10989            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10990                if (mExpectingBetter.containsKey(pkg.packageName)) {
10991                    logCriticalInfo(Log.WARN,
10992                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10993                } else {
10994                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10995                    if (known != null) {
10996                        if (DEBUG_PACKAGE_SCANNING) {
10997                            Log.d(TAG, "Examining " + pkg.codePath
10998                                    + " and requiring known paths " + known.codePathString
10999                                    + " & " + known.resourcePathString);
11000                        }
11001                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11002                                || !pkg.applicationInfo.getResourcePath().equals(
11003                                        known.resourcePathString)) {
11004                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11005                                    "Application package " + pkg.packageName
11006                                    + " found at " + pkg.applicationInfo.getCodePath()
11007                                    + " but expected at " + known.codePathString
11008                                    + "; ignoring.");
11009                        }
11010                    } else {
11011                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11012                                "Application package " + pkg.packageName
11013                                + " not found; ignoring.");
11014                    }
11015                }
11016            }
11017
11018            // Verify that this new package doesn't have any content providers
11019            // that conflict with existing packages.  Only do this if the
11020            // package isn't already installed, since we don't want to break
11021            // things that are installed.
11022            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11023                final int N = pkg.providers.size();
11024                int i;
11025                for (i=0; i<N; i++) {
11026                    PackageParser.Provider p = pkg.providers.get(i);
11027                    if (p.info.authority != null) {
11028                        String names[] = p.info.authority.split(";");
11029                        for (int j = 0; j < names.length; j++) {
11030                            if (mProvidersByAuthority.containsKey(names[j])) {
11031                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11032                                final String otherPackageName =
11033                                        ((other != null && other.getComponentName() != null) ?
11034                                                other.getComponentName().getPackageName() : "?");
11035                                throw new PackageManagerException(
11036                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11037                                        "Can't install because provider name " + names[j]
11038                                                + " (in package " + pkg.applicationInfo.packageName
11039                                                + ") is already used by " + otherPackageName);
11040                            }
11041                        }
11042                    }
11043                }
11044            }
11045
11046            // Verify that packages sharing a user with a privileged app are marked as privileged.
11047            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11048                SharedUserSetting sharedUserSetting = null;
11049                try {
11050                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11051                } catch (PackageManagerException ignore) {}
11052                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11053                    // Exempt SharedUsers signed with the platform key.
11054                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11055                    if ((platformPkgSetting.signatures.mSigningDetails
11056                            != PackageParser.SigningDetails.UNKNOWN)
11057                            && (compareSignatures(
11058                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11059                                    pkg.mSigningDetails.signatures)
11060                                            != PackageManager.SIGNATURE_MATCH)) {
11061                        throw new PackageManagerException("Apps that share a user with a " +
11062                                "privileged app must themselves be marked as privileged. " +
11063                                pkg.packageName + " shares privileged user " +
11064                                pkg.mSharedUserId + ".");
11065                    }
11066                }
11067            }
11068
11069            // Apply policies specific for runtime resource overlays (RROs).
11070            if (pkg.mOverlayTarget != null) {
11071                // System overlays have some restrictions on their use of the 'static' state.
11072                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11073                    // We are scanning a system overlay. This can be the first scan of the
11074                    // system/vendor/oem partition, or an update to the system overlay.
11075                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11076                        // This must be an update to a system overlay.
11077                        final PackageSetting previousPkg = assertNotNull(
11078                                mSettings.getPackageLPr(pkg.packageName),
11079                                "previous package state not present");
11080
11081                        // Static overlays cannot be updated.
11082                        if (previousPkg.pkg.mOverlayIsStatic) {
11083                            throw new PackageManagerException("Overlay " + pkg.packageName +
11084                                    " is static and cannot be upgraded.");
11085                        // Non-static overlays cannot be converted to static overlays.
11086                        } else if (pkg.mOverlayIsStatic) {
11087                            throw new PackageManagerException("Overlay " + pkg.packageName +
11088                                    " cannot be upgraded into a static overlay.");
11089                        }
11090                    }
11091                } else {
11092                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11093                    if (pkg.mOverlayIsStatic) {
11094                        throw new PackageManagerException("Overlay " + pkg.packageName +
11095                                " is static but not pre-installed.");
11096                    }
11097
11098                    // The only case where we allow installation of a non-system overlay is when
11099                    // its signature is signed with the platform certificate.
11100                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11101                    if ((platformPkgSetting.signatures.mSigningDetails
11102                            != PackageParser.SigningDetails.UNKNOWN)
11103                            && (compareSignatures(
11104                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11105                                    pkg.mSigningDetails.signatures)
11106                                            != PackageManager.SIGNATURE_MATCH)) {
11107                        throw new PackageManagerException("Overlay " + pkg.packageName +
11108                                " must be signed with the platform certificate.");
11109                    }
11110                }
11111            }
11112        }
11113    }
11114
11115    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11116            int type, String declaringPackageName, long declaringVersionCode) {
11117        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11118        if (versionedLib == null) {
11119            versionedLib = new LongSparseArray<>();
11120            mSharedLibraries.put(name, versionedLib);
11121            if (type == SharedLibraryInfo.TYPE_STATIC) {
11122                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11123            }
11124        } else if (versionedLib.indexOfKey(version) >= 0) {
11125            return false;
11126        }
11127        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11128                version, type, declaringPackageName, declaringVersionCode);
11129        versionedLib.put(version, libEntry);
11130        return true;
11131    }
11132
11133    private boolean removeSharedLibraryLPw(String name, long version) {
11134        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11135        if (versionedLib == null) {
11136            return false;
11137        }
11138        final int libIdx = versionedLib.indexOfKey(version);
11139        if (libIdx < 0) {
11140            return false;
11141        }
11142        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11143        versionedLib.remove(version);
11144        if (versionedLib.size() <= 0) {
11145            mSharedLibraries.remove(name);
11146            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11147                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11148                        .getPackageName());
11149            }
11150        }
11151        return true;
11152    }
11153
11154    /**
11155     * Adds a scanned package to the system. When this method is finished, the package will
11156     * be available for query, resolution, etc...
11157     */
11158    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11159            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11160        final String pkgName = pkg.packageName;
11161        if (mCustomResolverComponentName != null &&
11162                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11163            setUpCustomResolverActivity(pkg);
11164        }
11165
11166        if (pkg.packageName.equals("android")) {
11167            synchronized (mPackages) {
11168                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11169                    // Set up information for our fall-back user intent resolution activity.
11170                    mPlatformPackage = pkg;
11171                    pkg.mVersionCode = mSdkVersion;
11172                    pkg.mVersionCodeMajor = 0;
11173                    mAndroidApplication = pkg.applicationInfo;
11174                    if (!mResolverReplaced) {
11175                        mResolveActivity.applicationInfo = mAndroidApplication;
11176                        mResolveActivity.name = ResolverActivity.class.getName();
11177                        mResolveActivity.packageName = mAndroidApplication.packageName;
11178                        mResolveActivity.processName = "system:ui";
11179                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11180                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11181                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11182                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11183                        mResolveActivity.exported = true;
11184                        mResolveActivity.enabled = true;
11185                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11186                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11187                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11188                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11189                                | ActivityInfo.CONFIG_ORIENTATION
11190                                | ActivityInfo.CONFIG_KEYBOARD
11191                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11192                        mResolveInfo.activityInfo = mResolveActivity;
11193                        mResolveInfo.priority = 0;
11194                        mResolveInfo.preferredOrder = 0;
11195                        mResolveInfo.match = 0;
11196                        mResolveComponentName = new ComponentName(
11197                                mAndroidApplication.packageName, mResolveActivity.name);
11198                    }
11199                }
11200            }
11201        }
11202
11203        ArrayList<PackageParser.Package> clientLibPkgs = null;
11204        // writer
11205        synchronized (mPackages) {
11206            boolean hasStaticSharedLibs = false;
11207
11208            // Any app can add new static shared libraries
11209            if (pkg.staticSharedLibName != null) {
11210                // Static shared libs don't allow renaming as they have synthetic package
11211                // names to allow install of multiple versions, so use name from manifest.
11212                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11213                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11214                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11215                    hasStaticSharedLibs = true;
11216                } else {
11217                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11218                                + pkg.staticSharedLibName + " already exists; skipping");
11219                }
11220                // Static shared libs cannot be updated once installed since they
11221                // use synthetic package name which includes the version code, so
11222                // not need to update other packages's shared lib dependencies.
11223            }
11224
11225            if (!hasStaticSharedLibs
11226                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11227                // Only system apps can add new dynamic shared libraries.
11228                if (pkg.libraryNames != null) {
11229                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11230                        String name = pkg.libraryNames.get(i);
11231                        boolean allowed = false;
11232                        if (pkg.isUpdatedSystemApp()) {
11233                            // New library entries can only be added through the
11234                            // system image.  This is important to get rid of a lot
11235                            // of nasty edge cases: for example if we allowed a non-
11236                            // system update of the app to add a library, then uninstalling
11237                            // the update would make the library go away, and assumptions
11238                            // we made such as through app install filtering would now
11239                            // have allowed apps on the device which aren't compatible
11240                            // with it.  Better to just have the restriction here, be
11241                            // conservative, and create many fewer cases that can negatively
11242                            // impact the user experience.
11243                            final PackageSetting sysPs = mSettings
11244                                    .getDisabledSystemPkgLPr(pkg.packageName);
11245                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11246                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11247                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11248                                        allowed = true;
11249                                        break;
11250                                    }
11251                                }
11252                            }
11253                        } else {
11254                            allowed = true;
11255                        }
11256                        if (allowed) {
11257                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11258                                    SharedLibraryInfo.VERSION_UNDEFINED,
11259                                    SharedLibraryInfo.TYPE_DYNAMIC,
11260                                    pkg.packageName, pkg.getLongVersionCode())) {
11261                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11262                                        + name + " already exists; skipping");
11263                            }
11264                        } else {
11265                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11266                                    + name + " that is not declared on system image; skipping");
11267                        }
11268                    }
11269
11270                    if ((scanFlags & SCAN_BOOTING) == 0) {
11271                        // If we are not booting, we need to update any applications
11272                        // that are clients of our shared library.  If we are booting,
11273                        // this will all be done once the scan is complete.
11274                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11275                    }
11276                }
11277            }
11278        }
11279
11280        if ((scanFlags & SCAN_BOOTING) != 0) {
11281            // No apps can run during boot scan, so they don't need to be frozen
11282        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11283            // Caller asked to not kill app, so it's probably not frozen
11284        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11285            // Caller asked us to ignore frozen check for some reason; they
11286            // probably didn't know the package name
11287        } else {
11288            // We're doing major surgery on this package, so it better be frozen
11289            // right now to keep it from launching
11290            checkPackageFrozen(pkgName);
11291        }
11292
11293        // Also need to kill any apps that are dependent on the library.
11294        if (clientLibPkgs != null) {
11295            for (int i=0; i<clientLibPkgs.size(); i++) {
11296                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11297                killApplication(clientPkg.applicationInfo.packageName,
11298                        clientPkg.applicationInfo.uid, "update lib");
11299            }
11300        }
11301
11302        // writer
11303        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11304
11305        synchronized (mPackages) {
11306            // We don't expect installation to fail beyond this point
11307
11308            // Add the new setting to mSettings
11309            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11310            // Add the new setting to mPackages
11311            mPackages.put(pkg.applicationInfo.packageName, pkg);
11312            // Make sure we don't accidentally delete its data.
11313            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11314            while (iter.hasNext()) {
11315                PackageCleanItem item = iter.next();
11316                if (pkgName.equals(item.packageName)) {
11317                    iter.remove();
11318                }
11319            }
11320
11321            // Add the package's KeySets to the global KeySetManagerService
11322            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11323            ksms.addScannedPackageLPw(pkg);
11324
11325            int N = pkg.providers.size();
11326            StringBuilder r = null;
11327            int i;
11328            for (i=0; i<N; i++) {
11329                PackageParser.Provider p = pkg.providers.get(i);
11330                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11331                        p.info.processName);
11332                mProviders.addProvider(p);
11333                p.syncable = p.info.isSyncable;
11334                if (p.info.authority != null) {
11335                    String names[] = p.info.authority.split(";");
11336                    p.info.authority = null;
11337                    for (int j = 0; j < names.length; j++) {
11338                        if (j == 1 && p.syncable) {
11339                            // We only want the first authority for a provider to possibly be
11340                            // syncable, so if we already added this provider using a different
11341                            // authority clear the syncable flag. We copy the provider before
11342                            // changing it because the mProviders object contains a reference
11343                            // to a provider that we don't want to change.
11344                            // Only do this for the second authority since the resulting provider
11345                            // object can be the same for all future authorities for this provider.
11346                            p = new PackageParser.Provider(p);
11347                            p.syncable = false;
11348                        }
11349                        if (!mProvidersByAuthority.containsKey(names[j])) {
11350                            mProvidersByAuthority.put(names[j], p);
11351                            if (p.info.authority == null) {
11352                                p.info.authority = names[j];
11353                            } else {
11354                                p.info.authority = p.info.authority + ";" + names[j];
11355                            }
11356                            if (DEBUG_PACKAGE_SCANNING) {
11357                                if (chatty)
11358                                    Log.d(TAG, "Registered content provider: " + names[j]
11359                                            + ", className = " + p.info.name + ", isSyncable = "
11360                                            + p.info.isSyncable);
11361                            }
11362                        } else {
11363                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11364                            Slog.w(TAG, "Skipping provider name " + names[j] +
11365                                    " (in package " + pkg.applicationInfo.packageName +
11366                                    "): name already used by "
11367                                    + ((other != null && other.getComponentName() != null)
11368                                            ? other.getComponentName().getPackageName() : "?"));
11369                        }
11370                    }
11371                }
11372                if (chatty) {
11373                    if (r == null) {
11374                        r = new StringBuilder(256);
11375                    } else {
11376                        r.append(' ');
11377                    }
11378                    r.append(p.info.name);
11379                }
11380            }
11381            if (r != null) {
11382                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11383            }
11384
11385            N = pkg.services.size();
11386            r = null;
11387            for (i=0; i<N; i++) {
11388                PackageParser.Service s = pkg.services.get(i);
11389                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11390                        s.info.processName);
11391                mServices.addService(s);
11392                if (chatty) {
11393                    if (r == null) {
11394                        r = new StringBuilder(256);
11395                    } else {
11396                        r.append(' ');
11397                    }
11398                    r.append(s.info.name);
11399                }
11400            }
11401            if (r != null) {
11402                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11403            }
11404
11405            N = pkg.receivers.size();
11406            r = null;
11407            for (i=0; i<N; i++) {
11408                PackageParser.Activity a = pkg.receivers.get(i);
11409                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11410                        a.info.processName);
11411                mReceivers.addActivity(a, "receiver");
11412                if (chatty) {
11413                    if (r == null) {
11414                        r = new StringBuilder(256);
11415                    } else {
11416                        r.append(' ');
11417                    }
11418                    r.append(a.info.name);
11419                }
11420            }
11421            if (r != null) {
11422                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11423            }
11424
11425            N = pkg.activities.size();
11426            r = null;
11427            for (i=0; i<N; i++) {
11428                PackageParser.Activity a = pkg.activities.get(i);
11429                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11430                        a.info.processName);
11431                mActivities.addActivity(a, "activity");
11432                if (chatty) {
11433                    if (r == null) {
11434                        r = new StringBuilder(256);
11435                    } else {
11436                        r.append(' ');
11437                    }
11438                    r.append(a.info.name);
11439                }
11440            }
11441            if (r != null) {
11442                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11443            }
11444
11445            // Don't allow ephemeral applications to define new permissions groups.
11446            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11447                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11448                        + " ignored: instant apps cannot define new permission groups.");
11449            } else {
11450                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11451            }
11452
11453            // Don't allow ephemeral applications to define new permissions.
11454            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11455                Slog.w(TAG, "Permissions from package " + pkg.packageName
11456                        + " ignored: instant apps cannot define new permissions.");
11457            } else {
11458                mPermissionManager.addAllPermissions(pkg, chatty);
11459            }
11460
11461            N = pkg.instrumentation.size();
11462            r = null;
11463            for (i=0; i<N; i++) {
11464                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11465                a.info.packageName = pkg.applicationInfo.packageName;
11466                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11467                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11468                a.info.splitNames = pkg.splitNames;
11469                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11470                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11471                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11472                a.info.dataDir = pkg.applicationInfo.dataDir;
11473                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11474                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11475                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11476                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11477                mInstrumentation.put(a.getComponentName(), a);
11478                if (chatty) {
11479                    if (r == null) {
11480                        r = new StringBuilder(256);
11481                    } else {
11482                        r.append(' ');
11483                    }
11484                    r.append(a.info.name);
11485                }
11486            }
11487            if (r != null) {
11488                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11489            }
11490
11491            if (pkg.protectedBroadcasts != null) {
11492                N = pkg.protectedBroadcasts.size();
11493                synchronized (mProtectedBroadcasts) {
11494                    for (i = 0; i < N; i++) {
11495                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11496                    }
11497                }
11498            }
11499        }
11500
11501        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11502    }
11503
11504    /**
11505     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11506     * is derived purely on the basis of the contents of {@code scanFile} and
11507     * {@code cpuAbiOverride}.
11508     *
11509     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11510     */
11511    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11512            boolean extractLibs)
11513                    throws PackageManagerException {
11514        // Give ourselves some initial paths; we'll come back for another
11515        // pass once we've determined ABI below.
11516        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11517
11518        // We would never need to extract libs for forward-locked and external packages,
11519        // since the container service will do it for us. We shouldn't attempt to
11520        // extract libs from system app when it was not updated.
11521        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11522                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11523            extractLibs = false;
11524        }
11525
11526        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11527        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11528
11529        NativeLibraryHelper.Handle handle = null;
11530        try {
11531            handle = NativeLibraryHelper.Handle.create(pkg);
11532            // TODO(multiArch): This can be null for apps that didn't go through the
11533            // usual installation process. We can calculate it again, like we
11534            // do during install time.
11535            //
11536            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11537            // unnecessary.
11538            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11539
11540            // Null out the abis so that they can be recalculated.
11541            pkg.applicationInfo.primaryCpuAbi = null;
11542            pkg.applicationInfo.secondaryCpuAbi = null;
11543            if (isMultiArch(pkg.applicationInfo)) {
11544                // Warn if we've set an abiOverride for multi-lib packages..
11545                // By definition, we need to copy both 32 and 64 bit libraries for
11546                // such packages.
11547                if (pkg.cpuAbiOverride != null
11548                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11549                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11550                }
11551
11552                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11553                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11554                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11555                    if (extractLibs) {
11556                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11557                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11558                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11559                                useIsaSpecificSubdirs);
11560                    } else {
11561                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11562                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11563                    }
11564                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11565                }
11566
11567                // Shared library native code should be in the APK zip aligned
11568                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11569                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11570                            "Shared library native lib extraction not supported");
11571                }
11572
11573                maybeThrowExceptionForMultiArchCopy(
11574                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11575
11576                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11577                    if (extractLibs) {
11578                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11579                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11580                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11581                                useIsaSpecificSubdirs);
11582                    } else {
11583                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11584                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11585                    }
11586                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11587                }
11588
11589                maybeThrowExceptionForMultiArchCopy(
11590                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11591
11592                if (abi64 >= 0) {
11593                    // Shared library native libs should be in the APK zip aligned
11594                    if (extractLibs && pkg.isLibrary()) {
11595                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11596                                "Shared library native lib extraction not supported");
11597                    }
11598                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11599                }
11600
11601                if (abi32 >= 0) {
11602                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11603                    if (abi64 >= 0) {
11604                        if (pkg.use32bitAbi) {
11605                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11606                            pkg.applicationInfo.primaryCpuAbi = abi;
11607                        } else {
11608                            pkg.applicationInfo.secondaryCpuAbi = abi;
11609                        }
11610                    } else {
11611                        pkg.applicationInfo.primaryCpuAbi = abi;
11612                    }
11613                }
11614            } else {
11615                String[] abiList = (cpuAbiOverride != null) ?
11616                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11617
11618                // Enable gross and lame hacks for apps that are built with old
11619                // SDK tools. We must scan their APKs for renderscript bitcode and
11620                // not launch them if it's present. Don't bother checking on devices
11621                // that don't have 64 bit support.
11622                boolean needsRenderScriptOverride = false;
11623                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11624                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11625                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11626                    needsRenderScriptOverride = true;
11627                }
11628
11629                final int copyRet;
11630                if (extractLibs) {
11631                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11632                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11633                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11634                } else {
11635                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11636                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11637                }
11638                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11639
11640                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11641                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11642                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11643                }
11644
11645                if (copyRet >= 0) {
11646                    // Shared libraries that have native libs must be multi-architecture
11647                    if (pkg.isLibrary()) {
11648                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11649                                "Shared library with native libs must be multiarch");
11650                    }
11651                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11652                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11653                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11654                } else if (needsRenderScriptOverride) {
11655                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11656                }
11657            }
11658        } catch (IOException ioe) {
11659            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11660        } finally {
11661            IoUtils.closeQuietly(handle);
11662        }
11663
11664        // Now that we've calculated the ABIs and determined if it's an internal app,
11665        // we will go ahead and populate the nativeLibraryPath.
11666        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11667    }
11668
11669    /**
11670     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11671     * i.e, so that all packages can be run inside a single process if required.
11672     *
11673     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11674     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11675     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11676     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11677     * updating a package that belongs to a shared user.
11678     *
11679     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11680     * adds unnecessary complexity.
11681     */
11682    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11683            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11684        List<String> changedAbiCodePath = null;
11685        String requiredInstructionSet = null;
11686        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11687            requiredInstructionSet = VMRuntime.getInstructionSet(
11688                     scannedPackage.applicationInfo.primaryCpuAbi);
11689        }
11690
11691        PackageSetting requirer = null;
11692        for (PackageSetting ps : packagesForUser) {
11693            // If packagesForUser contains scannedPackage, we skip it. This will happen
11694            // when scannedPackage is an update of an existing package. Without this check,
11695            // we will never be able to change the ABI of any package belonging to a shared
11696            // user, even if it's compatible with other packages.
11697            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11698                if (ps.primaryCpuAbiString == null) {
11699                    continue;
11700                }
11701
11702                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11703                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11704                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11705                    // this but there's not much we can do.
11706                    String errorMessage = "Instruction set mismatch, "
11707                            + ((requirer == null) ? "[caller]" : requirer)
11708                            + " requires " + requiredInstructionSet + " whereas " + ps
11709                            + " requires " + instructionSet;
11710                    Slog.w(TAG, errorMessage);
11711                }
11712
11713                if (requiredInstructionSet == null) {
11714                    requiredInstructionSet = instructionSet;
11715                    requirer = ps;
11716                }
11717            }
11718        }
11719
11720        if (requiredInstructionSet != null) {
11721            String adjustedAbi;
11722            if (requirer != null) {
11723                // requirer != null implies that either scannedPackage was null or that scannedPackage
11724                // did not require an ABI, in which case we have to adjust scannedPackage to match
11725                // the ABI of the set (which is the same as requirer's ABI)
11726                adjustedAbi = requirer.primaryCpuAbiString;
11727                if (scannedPackage != null) {
11728                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11729                }
11730            } else {
11731                // requirer == null implies that we're updating all ABIs in the set to
11732                // match scannedPackage.
11733                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11734            }
11735
11736            for (PackageSetting ps : packagesForUser) {
11737                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11738                    if (ps.primaryCpuAbiString != null) {
11739                        continue;
11740                    }
11741
11742                    ps.primaryCpuAbiString = adjustedAbi;
11743                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11744                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11745                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11746                        if (DEBUG_ABI_SELECTION) {
11747                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11748                                    + " (requirer="
11749                                    + (requirer != null ? requirer.pkg : "null")
11750                                    + ", scannedPackage="
11751                                    + (scannedPackage != null ? scannedPackage : "null")
11752                                    + ")");
11753                        }
11754                        if (changedAbiCodePath == null) {
11755                            changedAbiCodePath = new ArrayList<>();
11756                        }
11757                        changedAbiCodePath.add(ps.codePathString);
11758                    }
11759                }
11760            }
11761        }
11762        return changedAbiCodePath;
11763    }
11764
11765    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11766        synchronized (mPackages) {
11767            mResolverReplaced = true;
11768            // Set up information for custom user intent resolution activity.
11769            mResolveActivity.applicationInfo = pkg.applicationInfo;
11770            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11771            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11772            mResolveActivity.processName = pkg.applicationInfo.packageName;
11773            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11774            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11775                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11776            mResolveActivity.theme = 0;
11777            mResolveActivity.exported = true;
11778            mResolveActivity.enabled = true;
11779            mResolveInfo.activityInfo = mResolveActivity;
11780            mResolveInfo.priority = 0;
11781            mResolveInfo.preferredOrder = 0;
11782            mResolveInfo.match = 0;
11783            mResolveComponentName = mCustomResolverComponentName;
11784            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11785                    mResolveComponentName);
11786        }
11787    }
11788
11789    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11790        if (installerActivity == null) {
11791            if (DEBUG_EPHEMERAL) {
11792                Slog.d(TAG, "Clear ephemeral installer activity");
11793            }
11794            mInstantAppInstallerActivity = null;
11795            return;
11796        }
11797
11798        if (DEBUG_EPHEMERAL) {
11799            Slog.d(TAG, "Set ephemeral installer activity: "
11800                    + installerActivity.getComponentName());
11801        }
11802        // Set up information for ephemeral installer activity
11803        mInstantAppInstallerActivity = installerActivity;
11804        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11805                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11806        mInstantAppInstallerActivity.exported = true;
11807        mInstantAppInstallerActivity.enabled = true;
11808        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11809        mInstantAppInstallerInfo.priority = 1;
11810        mInstantAppInstallerInfo.preferredOrder = 1;
11811        mInstantAppInstallerInfo.isDefault = true;
11812        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11813                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11814    }
11815
11816    private static String calculateBundledApkRoot(final String codePathString) {
11817        final File codePath = new File(codePathString);
11818        final File codeRoot;
11819        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11820            codeRoot = Environment.getRootDirectory();
11821        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11822            codeRoot = Environment.getOemDirectory();
11823        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11824            codeRoot = Environment.getVendorDirectory();
11825        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11826            codeRoot = Environment.getProductDirectory();
11827        } else {
11828            // Unrecognized code path; take its top real segment as the apk root:
11829            // e.g. /something/app/blah.apk => /something
11830            try {
11831                File f = codePath.getCanonicalFile();
11832                File parent = f.getParentFile();    // non-null because codePath is a file
11833                File tmp;
11834                while ((tmp = parent.getParentFile()) != null) {
11835                    f = parent;
11836                    parent = tmp;
11837                }
11838                codeRoot = f;
11839                Slog.w(TAG, "Unrecognized code path "
11840                        + codePath + " - using " + codeRoot);
11841            } catch (IOException e) {
11842                // Can't canonicalize the code path -- shenanigans?
11843                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11844                return Environment.getRootDirectory().getPath();
11845            }
11846        }
11847        return codeRoot.getPath();
11848    }
11849
11850    /**
11851     * Derive and set the location of native libraries for the given package,
11852     * which varies depending on where and how the package was installed.
11853     */
11854    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11855        final ApplicationInfo info = pkg.applicationInfo;
11856        final String codePath = pkg.codePath;
11857        final File codeFile = new File(codePath);
11858        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11859        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11860
11861        info.nativeLibraryRootDir = null;
11862        info.nativeLibraryRootRequiresIsa = false;
11863        info.nativeLibraryDir = null;
11864        info.secondaryNativeLibraryDir = null;
11865
11866        if (isApkFile(codeFile)) {
11867            // Monolithic install
11868            if (bundledApp) {
11869                // If "/system/lib64/apkname" exists, assume that is the per-package
11870                // native library directory to use; otherwise use "/system/lib/apkname".
11871                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11872                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11873                        getPrimaryInstructionSet(info));
11874
11875                // This is a bundled system app so choose the path based on the ABI.
11876                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11877                // is just the default path.
11878                final String apkName = deriveCodePathName(codePath);
11879                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11880                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11881                        apkName).getAbsolutePath();
11882
11883                if (info.secondaryCpuAbi != null) {
11884                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11885                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11886                            secondaryLibDir, apkName).getAbsolutePath();
11887                }
11888            } else if (asecApp) {
11889                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11890                        .getAbsolutePath();
11891            } else {
11892                final String apkName = deriveCodePathName(codePath);
11893                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11894                        .getAbsolutePath();
11895            }
11896
11897            info.nativeLibraryRootRequiresIsa = false;
11898            info.nativeLibraryDir = info.nativeLibraryRootDir;
11899        } else {
11900            // Cluster install
11901            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11902            info.nativeLibraryRootRequiresIsa = true;
11903
11904            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11905                    getPrimaryInstructionSet(info)).getAbsolutePath();
11906
11907            if (info.secondaryCpuAbi != null) {
11908                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11909                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11910            }
11911        }
11912    }
11913
11914    /**
11915     * Calculate the abis and roots for a bundled app. These can uniquely
11916     * be determined from the contents of the system partition, i.e whether
11917     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11918     * of this information, and instead assume that the system was built
11919     * sensibly.
11920     */
11921    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11922                                           PackageSetting pkgSetting) {
11923        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11924
11925        // If "/system/lib64/apkname" exists, assume that is the per-package
11926        // native library directory to use; otherwise use "/system/lib/apkname".
11927        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11928        setBundledAppAbi(pkg, apkRoot, apkName);
11929        // pkgSetting might be null during rescan following uninstall of updates
11930        // to a bundled app, so accommodate that possibility.  The settings in
11931        // that case will be established later from the parsed package.
11932        //
11933        // If the settings aren't null, sync them up with what we've just derived.
11934        // note that apkRoot isn't stored in the package settings.
11935        if (pkgSetting != null) {
11936            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11937            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11938        }
11939    }
11940
11941    /**
11942     * Deduces the ABI of a bundled app and sets the relevant fields on the
11943     * parsed pkg object.
11944     *
11945     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11946     *        under which system libraries are installed.
11947     * @param apkName the name of the installed package.
11948     */
11949    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11950        final File codeFile = new File(pkg.codePath);
11951
11952        final boolean has64BitLibs;
11953        final boolean has32BitLibs;
11954        if (isApkFile(codeFile)) {
11955            // Monolithic install
11956            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11957            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11958        } else {
11959            // Cluster install
11960            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11961            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11962                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11963                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11964                has64BitLibs = (new File(rootDir, isa)).exists();
11965            } else {
11966                has64BitLibs = false;
11967            }
11968            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11969                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11970                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11971                has32BitLibs = (new File(rootDir, isa)).exists();
11972            } else {
11973                has32BitLibs = false;
11974            }
11975        }
11976
11977        if (has64BitLibs && !has32BitLibs) {
11978            // The package has 64 bit libs, but not 32 bit libs. Its primary
11979            // ABI should be 64 bit. We can safely assume here that the bundled
11980            // native libraries correspond to the most preferred ABI in the list.
11981
11982            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11983            pkg.applicationInfo.secondaryCpuAbi = null;
11984        } else if (has32BitLibs && !has64BitLibs) {
11985            // The package has 32 bit libs but not 64 bit libs. Its primary
11986            // ABI should be 32 bit.
11987
11988            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11989            pkg.applicationInfo.secondaryCpuAbi = null;
11990        } else if (has32BitLibs && has64BitLibs) {
11991            // The application has both 64 and 32 bit bundled libraries. We check
11992            // here that the app declares multiArch support, and warn if it doesn't.
11993            //
11994            // We will be lenient here and record both ABIs. The primary will be the
11995            // ABI that's higher on the list, i.e, a device that's configured to prefer
11996            // 64 bit apps will see a 64 bit primary ABI,
11997
11998            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11999                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12000            }
12001
12002            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12003                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12004                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12005            } else {
12006                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12007                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12008            }
12009        } else {
12010            pkg.applicationInfo.primaryCpuAbi = null;
12011            pkg.applicationInfo.secondaryCpuAbi = null;
12012        }
12013    }
12014
12015    private void killApplication(String pkgName, int appId, String reason) {
12016        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12017    }
12018
12019    private void killApplication(String pkgName, int appId, int userId, String reason) {
12020        // Request the ActivityManager to kill the process(only for existing packages)
12021        // so that we do not end up in a confused state while the user is still using the older
12022        // version of the application while the new one gets installed.
12023        final long token = Binder.clearCallingIdentity();
12024        try {
12025            IActivityManager am = ActivityManager.getService();
12026            if (am != null) {
12027                try {
12028                    am.killApplication(pkgName, appId, userId, reason);
12029                } catch (RemoteException e) {
12030                }
12031            }
12032        } finally {
12033            Binder.restoreCallingIdentity(token);
12034        }
12035    }
12036
12037    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12038        // Remove the parent package setting
12039        PackageSetting ps = (PackageSetting) pkg.mExtras;
12040        if (ps != null) {
12041            removePackageLI(ps, chatty);
12042        }
12043        // Remove the child package setting
12044        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12045        for (int i = 0; i < childCount; i++) {
12046            PackageParser.Package childPkg = pkg.childPackages.get(i);
12047            ps = (PackageSetting) childPkg.mExtras;
12048            if (ps != null) {
12049                removePackageLI(ps, chatty);
12050            }
12051        }
12052    }
12053
12054    void removePackageLI(PackageSetting ps, boolean chatty) {
12055        if (DEBUG_INSTALL) {
12056            if (chatty)
12057                Log.d(TAG, "Removing package " + ps.name);
12058        }
12059
12060        // writer
12061        synchronized (mPackages) {
12062            mPackages.remove(ps.name);
12063            final PackageParser.Package pkg = ps.pkg;
12064            if (pkg != null) {
12065                cleanPackageDataStructuresLILPw(pkg, chatty);
12066            }
12067        }
12068    }
12069
12070    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12071        if (DEBUG_INSTALL) {
12072            if (chatty)
12073                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12074        }
12075
12076        // writer
12077        synchronized (mPackages) {
12078            // Remove the parent package
12079            mPackages.remove(pkg.applicationInfo.packageName);
12080            cleanPackageDataStructuresLILPw(pkg, chatty);
12081
12082            // Remove the child packages
12083            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12084            for (int i = 0; i < childCount; i++) {
12085                PackageParser.Package childPkg = pkg.childPackages.get(i);
12086                mPackages.remove(childPkg.applicationInfo.packageName);
12087                cleanPackageDataStructuresLILPw(childPkg, chatty);
12088            }
12089        }
12090    }
12091
12092    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12093        int N = pkg.providers.size();
12094        StringBuilder r = null;
12095        int i;
12096        for (i=0; i<N; i++) {
12097            PackageParser.Provider p = pkg.providers.get(i);
12098            mProviders.removeProvider(p);
12099            if (p.info.authority == null) {
12100
12101                /* There was another ContentProvider with this authority when
12102                 * this app was installed so this authority is null,
12103                 * Ignore it as we don't have to unregister the provider.
12104                 */
12105                continue;
12106            }
12107            String names[] = p.info.authority.split(";");
12108            for (int j = 0; j < names.length; j++) {
12109                if (mProvidersByAuthority.get(names[j]) == p) {
12110                    mProvidersByAuthority.remove(names[j]);
12111                    if (DEBUG_REMOVE) {
12112                        if (chatty)
12113                            Log.d(TAG, "Unregistered content provider: " + names[j]
12114                                    + ", className = " + p.info.name + ", isSyncable = "
12115                                    + p.info.isSyncable);
12116                    }
12117                }
12118            }
12119            if (DEBUG_REMOVE && chatty) {
12120                if (r == null) {
12121                    r = new StringBuilder(256);
12122                } else {
12123                    r.append(' ');
12124                }
12125                r.append(p.info.name);
12126            }
12127        }
12128        if (r != null) {
12129            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12130        }
12131
12132        N = pkg.services.size();
12133        r = null;
12134        for (i=0; i<N; i++) {
12135            PackageParser.Service s = pkg.services.get(i);
12136            mServices.removeService(s);
12137            if (chatty) {
12138                if (r == null) {
12139                    r = new StringBuilder(256);
12140                } else {
12141                    r.append(' ');
12142                }
12143                r.append(s.info.name);
12144            }
12145        }
12146        if (r != null) {
12147            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12148        }
12149
12150        N = pkg.receivers.size();
12151        r = null;
12152        for (i=0; i<N; i++) {
12153            PackageParser.Activity a = pkg.receivers.get(i);
12154            mReceivers.removeActivity(a, "receiver");
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, "  Receivers: " + r);
12166        }
12167
12168        N = pkg.activities.size();
12169        r = null;
12170        for (i=0; i<N; i++) {
12171            PackageParser.Activity a = pkg.activities.get(i);
12172            mActivities.removeActivity(a, "activity");
12173            if (DEBUG_REMOVE && chatty) {
12174                if (r == null) {
12175                    r = new StringBuilder(256);
12176                } else {
12177                    r.append(' ');
12178                }
12179                r.append(a.info.name);
12180            }
12181        }
12182        if (r != null) {
12183            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12184        }
12185
12186        mPermissionManager.removeAllPermissions(pkg, chatty);
12187
12188        N = pkg.instrumentation.size();
12189        r = null;
12190        for (i=0; i<N; i++) {
12191            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12192            mInstrumentation.remove(a.getComponentName());
12193            if (DEBUG_REMOVE && chatty) {
12194                if (r == null) {
12195                    r = new StringBuilder(256);
12196                } else {
12197                    r.append(' ');
12198                }
12199                r.append(a.info.name);
12200            }
12201        }
12202        if (r != null) {
12203            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12204        }
12205
12206        r = null;
12207        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12208            // Only system apps can hold shared libraries.
12209            if (pkg.libraryNames != null) {
12210                for (i = 0; i < pkg.libraryNames.size(); i++) {
12211                    String name = pkg.libraryNames.get(i);
12212                    if (removeSharedLibraryLPw(name, 0)) {
12213                        if (DEBUG_REMOVE && chatty) {
12214                            if (r == null) {
12215                                r = new StringBuilder(256);
12216                            } else {
12217                                r.append(' ');
12218                            }
12219                            r.append(name);
12220                        }
12221                    }
12222                }
12223            }
12224        }
12225
12226        r = null;
12227
12228        // Any package can hold static shared libraries.
12229        if (pkg.staticSharedLibName != null) {
12230            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12231                if (DEBUG_REMOVE && chatty) {
12232                    if (r == null) {
12233                        r = new StringBuilder(256);
12234                    } else {
12235                        r.append(' ');
12236                    }
12237                    r.append(pkg.staticSharedLibName);
12238                }
12239            }
12240        }
12241
12242        if (r != null) {
12243            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12244        }
12245    }
12246
12247
12248    final class ActivityIntentResolver
12249            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12250        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12251                boolean defaultOnly, int userId) {
12252            if (!sUserManager.exists(userId)) return null;
12253            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12254            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12255        }
12256
12257        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12258                int userId) {
12259            if (!sUserManager.exists(userId)) return null;
12260            mFlags = flags;
12261            return super.queryIntent(intent, resolvedType,
12262                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12263                    userId);
12264        }
12265
12266        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12267                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12268            if (!sUserManager.exists(userId)) return null;
12269            if (packageActivities == null) {
12270                return null;
12271            }
12272            mFlags = flags;
12273            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12274            final int N = packageActivities.size();
12275            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12276                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12277
12278            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12279            for (int i = 0; i < N; ++i) {
12280                intentFilters = packageActivities.get(i).intents;
12281                if (intentFilters != null && intentFilters.size() > 0) {
12282                    PackageParser.ActivityIntentInfo[] array =
12283                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12284                    intentFilters.toArray(array);
12285                    listCut.add(array);
12286                }
12287            }
12288            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12289        }
12290
12291        /**
12292         * Finds a privileged activity that matches the specified activity names.
12293         */
12294        private PackageParser.Activity findMatchingActivity(
12295                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12296            for (PackageParser.Activity sysActivity : activityList) {
12297                if (sysActivity.info.name.equals(activityInfo.name)) {
12298                    return sysActivity;
12299                }
12300                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12301                    return sysActivity;
12302                }
12303                if (sysActivity.info.targetActivity != null) {
12304                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12305                        return sysActivity;
12306                    }
12307                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12308                        return sysActivity;
12309                    }
12310                }
12311            }
12312            return null;
12313        }
12314
12315        public class IterGenerator<E> {
12316            public Iterator<E> generate(ActivityIntentInfo info) {
12317                return null;
12318            }
12319        }
12320
12321        public class ActionIterGenerator extends IterGenerator<String> {
12322            @Override
12323            public Iterator<String> generate(ActivityIntentInfo info) {
12324                return info.actionsIterator();
12325            }
12326        }
12327
12328        public class CategoriesIterGenerator extends IterGenerator<String> {
12329            @Override
12330            public Iterator<String> generate(ActivityIntentInfo info) {
12331                return info.categoriesIterator();
12332            }
12333        }
12334
12335        public class SchemesIterGenerator extends IterGenerator<String> {
12336            @Override
12337            public Iterator<String> generate(ActivityIntentInfo info) {
12338                return info.schemesIterator();
12339            }
12340        }
12341
12342        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12343            @Override
12344            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12345                return info.authoritiesIterator();
12346            }
12347        }
12348
12349        /**
12350         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12351         * MODIFIED. Do not pass in a list that should not be changed.
12352         */
12353        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12354                IterGenerator<T> generator, Iterator<T> searchIterator) {
12355            // loop through the set of actions; every one must be found in the intent filter
12356            while (searchIterator.hasNext()) {
12357                // we must have at least one filter in the list to consider a match
12358                if (intentList.size() == 0) {
12359                    break;
12360                }
12361
12362                final T searchAction = searchIterator.next();
12363
12364                // loop through the set of intent filters
12365                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12366                while (intentIter.hasNext()) {
12367                    final ActivityIntentInfo intentInfo = intentIter.next();
12368                    boolean selectionFound = false;
12369
12370                    // loop through the intent filter's selection criteria; at least one
12371                    // of them must match the searched criteria
12372                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12373                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12374                        final T intentSelection = intentSelectionIter.next();
12375                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12376                            selectionFound = true;
12377                            break;
12378                        }
12379                    }
12380
12381                    // the selection criteria wasn't found in this filter's set; this filter
12382                    // is not a potential match
12383                    if (!selectionFound) {
12384                        intentIter.remove();
12385                    }
12386                }
12387            }
12388        }
12389
12390        private boolean isProtectedAction(ActivityIntentInfo filter) {
12391            final Iterator<String> actionsIter = filter.actionsIterator();
12392            while (actionsIter != null && actionsIter.hasNext()) {
12393                final String filterAction = actionsIter.next();
12394                if (PROTECTED_ACTIONS.contains(filterAction)) {
12395                    return true;
12396                }
12397            }
12398            return false;
12399        }
12400
12401        /**
12402         * Adjusts the priority of the given intent filter according to policy.
12403         * <p>
12404         * <ul>
12405         * <li>The priority for non privileged applications is capped to '0'</li>
12406         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12407         * <li>The priority for unbundled updates to privileged applications is capped to the
12408         *      priority defined on the system partition</li>
12409         * </ul>
12410         * <p>
12411         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12412         * allowed to obtain any priority on any action.
12413         */
12414        private void adjustPriority(
12415                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12416            // nothing to do; priority is fine as-is
12417            if (intent.getPriority() <= 0) {
12418                return;
12419            }
12420
12421            final ActivityInfo activityInfo = intent.activity.info;
12422            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12423
12424            final boolean privilegedApp =
12425                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12426            if (!privilegedApp) {
12427                // non-privileged applications can never define a priority >0
12428                if (DEBUG_FILTERS) {
12429                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12430                            + " package: " + applicationInfo.packageName
12431                            + " activity: " + intent.activity.className
12432                            + " origPrio: " + intent.getPriority());
12433                }
12434                intent.setPriority(0);
12435                return;
12436            }
12437
12438            if (systemActivities == null) {
12439                // the system package is not disabled; we're parsing the system partition
12440                if (isProtectedAction(intent)) {
12441                    if (mDeferProtectedFilters) {
12442                        // We can't deal with these just yet. No component should ever obtain a
12443                        // >0 priority for a protected actions, with ONE exception -- the setup
12444                        // wizard. The setup wizard, however, cannot be known until we're able to
12445                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12446                        // until all intent filters have been processed. Chicken, meet egg.
12447                        // Let the filter temporarily have a high priority and rectify the
12448                        // priorities after all system packages have been scanned.
12449                        mProtectedFilters.add(intent);
12450                        if (DEBUG_FILTERS) {
12451                            Slog.i(TAG, "Protected action; save for later;"
12452                                    + " package: " + applicationInfo.packageName
12453                                    + " activity: " + intent.activity.className
12454                                    + " origPrio: " + intent.getPriority());
12455                        }
12456                        return;
12457                    } else {
12458                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12459                            Slog.i(TAG, "No setup wizard;"
12460                                + " All protected intents capped to priority 0");
12461                        }
12462                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12463                            if (DEBUG_FILTERS) {
12464                                Slog.i(TAG, "Found setup wizard;"
12465                                    + " allow priority " + intent.getPriority() + ";"
12466                                    + " package: " + intent.activity.info.packageName
12467                                    + " activity: " + intent.activity.className
12468                                    + " priority: " + intent.getPriority());
12469                            }
12470                            // setup wizard gets whatever it wants
12471                            return;
12472                        }
12473                        if (DEBUG_FILTERS) {
12474                            Slog.i(TAG, "Protected action; cap priority to 0;"
12475                                    + " package: " + intent.activity.info.packageName
12476                                    + " activity: " + intent.activity.className
12477                                    + " origPrio: " + intent.getPriority());
12478                        }
12479                        intent.setPriority(0);
12480                        return;
12481                    }
12482                }
12483                // privileged apps on the system image get whatever priority they request
12484                return;
12485            }
12486
12487            // privileged app unbundled update ... try to find the same activity
12488            final PackageParser.Activity foundActivity =
12489                    findMatchingActivity(systemActivities, activityInfo);
12490            if (foundActivity == null) {
12491                // this is a new activity; it cannot obtain >0 priority
12492                if (DEBUG_FILTERS) {
12493                    Slog.i(TAG, "New activity; cap priority to 0;"
12494                            + " package: " + applicationInfo.packageName
12495                            + " activity: " + intent.activity.className
12496                            + " origPrio: " + intent.getPriority());
12497                }
12498                intent.setPriority(0);
12499                return;
12500            }
12501
12502            // found activity, now check for filter equivalence
12503
12504            // a shallow copy is enough; we modify the list, not its contents
12505            final List<ActivityIntentInfo> intentListCopy =
12506                    new ArrayList<>(foundActivity.intents);
12507            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12508
12509            // find matching action subsets
12510            final Iterator<String> actionsIterator = intent.actionsIterator();
12511            if (actionsIterator != null) {
12512                getIntentListSubset(
12513                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12514                if (intentListCopy.size() == 0) {
12515                    // no more intents to match; we're not equivalent
12516                    if (DEBUG_FILTERS) {
12517                        Slog.i(TAG, "Mismatched action; 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 category subsets
12528            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12529            if (categoriesIterator != null) {
12530                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12531                        categoriesIterator);
12532                if (intentListCopy.size() == 0) {
12533                    // no more intents to match; we're not equivalent
12534                    if (DEBUG_FILTERS) {
12535                        Slog.i(TAG, "Mismatched category; 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 schemes subsets
12546            final Iterator<String> schemesIterator = intent.schemesIterator();
12547            if (schemesIterator != null) {
12548                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12549                        schemesIterator);
12550                if (intentListCopy.size() == 0) {
12551                    // no more intents to match; we're not equivalent
12552                    if (DEBUG_FILTERS) {
12553                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12554                                + " package: " + applicationInfo.packageName
12555                                + " activity: " + intent.activity.className
12556                                + " origPrio: " + intent.getPriority());
12557                    }
12558                    intent.setPriority(0);
12559                    return;
12560                }
12561            }
12562
12563            // find matching authorities subsets
12564            final Iterator<IntentFilter.AuthorityEntry>
12565                    authoritiesIterator = intent.authoritiesIterator();
12566            if (authoritiesIterator != null) {
12567                getIntentListSubset(intentListCopy,
12568                        new AuthoritiesIterGenerator(),
12569                        authoritiesIterator);
12570                if (intentListCopy.size() == 0) {
12571                    // no more intents to match; we're not equivalent
12572                    if (DEBUG_FILTERS) {
12573                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12574                                + " package: " + applicationInfo.packageName
12575                                + " activity: " + intent.activity.className
12576                                + " origPrio: " + intent.getPriority());
12577                    }
12578                    intent.setPriority(0);
12579                    return;
12580                }
12581            }
12582
12583            // we found matching filter(s); app gets the max priority of all intents
12584            int cappedPriority = 0;
12585            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12586                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12587            }
12588            if (intent.getPriority() > cappedPriority) {
12589                if (DEBUG_FILTERS) {
12590                    Slog.i(TAG, "Found matching filter(s);"
12591                            + " cap priority to " + cappedPriority + ";"
12592                            + " package: " + applicationInfo.packageName
12593                            + " activity: " + intent.activity.className
12594                            + " origPrio: " + intent.getPriority());
12595                }
12596                intent.setPriority(cappedPriority);
12597                return;
12598            }
12599            // all this for nothing; the requested priority was <= what was on the system
12600        }
12601
12602        public final void addActivity(PackageParser.Activity a, String type) {
12603            mActivities.put(a.getComponentName(), a);
12604            if (DEBUG_SHOW_INFO)
12605                Log.v(
12606                TAG, "  " + type + " " +
12607                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12608            if (DEBUG_SHOW_INFO)
12609                Log.v(TAG, "    Class=" + a.info.name);
12610            final int NI = a.intents.size();
12611            for (int j=0; j<NI; j++) {
12612                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12613                if ("activity".equals(type)) {
12614                    final PackageSetting ps =
12615                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12616                    final List<PackageParser.Activity> systemActivities =
12617                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12618                    adjustPriority(systemActivities, intent);
12619                }
12620                if (DEBUG_SHOW_INFO) {
12621                    Log.v(TAG, "    IntentFilter:");
12622                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12623                }
12624                if (!intent.debugCheck()) {
12625                    Log.w(TAG, "==> For Activity " + a.info.name);
12626                }
12627                addFilter(intent);
12628            }
12629        }
12630
12631        public final void removeActivity(PackageParser.Activity a, String type) {
12632            mActivities.remove(a.getComponentName());
12633            if (DEBUG_SHOW_INFO) {
12634                Log.v(TAG, "  " + type + " "
12635                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12636                                : a.info.name) + ":");
12637                Log.v(TAG, "    Class=" + a.info.name);
12638            }
12639            final int NI = a.intents.size();
12640            for (int j=0; j<NI; j++) {
12641                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12642                if (DEBUG_SHOW_INFO) {
12643                    Log.v(TAG, "    IntentFilter:");
12644                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12645                }
12646                removeFilter(intent);
12647            }
12648        }
12649
12650        @Override
12651        protected boolean allowFilterResult(
12652                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12653            ActivityInfo filterAi = filter.activity.info;
12654            for (int i=dest.size()-1; i>=0; i--) {
12655                ActivityInfo destAi = dest.get(i).activityInfo;
12656                if (destAi.name == filterAi.name
12657                        && destAi.packageName == filterAi.packageName) {
12658                    return false;
12659                }
12660            }
12661            return true;
12662        }
12663
12664        @Override
12665        protected ActivityIntentInfo[] newArray(int size) {
12666            return new ActivityIntentInfo[size];
12667        }
12668
12669        @Override
12670        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12671            if (!sUserManager.exists(userId)) return true;
12672            PackageParser.Package p = filter.activity.owner;
12673            if (p != null) {
12674                PackageSetting ps = (PackageSetting)p.mExtras;
12675                if (ps != null) {
12676                    // System apps are never considered stopped for purposes of
12677                    // filtering, because there may be no way for the user to
12678                    // actually re-launch them.
12679                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12680                            && ps.getStopped(userId);
12681                }
12682            }
12683            return false;
12684        }
12685
12686        @Override
12687        protected boolean isPackageForFilter(String packageName,
12688                PackageParser.ActivityIntentInfo info) {
12689            return packageName.equals(info.activity.owner.packageName);
12690        }
12691
12692        @Override
12693        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12694                int match, int userId) {
12695            if (!sUserManager.exists(userId)) return null;
12696            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12697                return null;
12698            }
12699            final PackageParser.Activity activity = info.activity;
12700            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12701            if (ps == null) {
12702                return null;
12703            }
12704            final PackageUserState userState = ps.readUserState(userId);
12705            ActivityInfo ai =
12706                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12707            if (ai == null) {
12708                return null;
12709            }
12710            final boolean matchExplicitlyVisibleOnly =
12711                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12712            final boolean matchVisibleToInstantApp =
12713                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12714            final boolean componentVisible =
12715                    matchVisibleToInstantApp
12716                    && info.isVisibleToInstantApp()
12717                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12718            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12719            // throw out filters that aren't visible to ephemeral apps
12720            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12721                return null;
12722            }
12723            // throw out instant app filters if we're not explicitly requesting them
12724            if (!matchInstantApp && userState.instantApp) {
12725                return null;
12726            }
12727            // throw out instant app filters if updates are available; will trigger
12728            // instant app resolution
12729            if (userState.instantApp && ps.isUpdateAvailable()) {
12730                return null;
12731            }
12732            final ResolveInfo res = new ResolveInfo();
12733            res.activityInfo = ai;
12734            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12735                res.filter = info;
12736            }
12737            if (info != null) {
12738                res.handleAllWebDataURI = info.handleAllWebDataURI();
12739            }
12740            res.priority = info.getPriority();
12741            res.preferredOrder = activity.owner.mPreferredOrder;
12742            //System.out.println("Result: " + res.activityInfo.className +
12743            //                   " = " + res.priority);
12744            res.match = match;
12745            res.isDefault = info.hasDefault;
12746            res.labelRes = info.labelRes;
12747            res.nonLocalizedLabel = info.nonLocalizedLabel;
12748            if (userNeedsBadging(userId)) {
12749                res.noResourceId = true;
12750            } else {
12751                res.icon = info.icon;
12752            }
12753            res.iconResourceId = info.icon;
12754            res.system = res.activityInfo.applicationInfo.isSystemApp();
12755            res.isInstantAppAvailable = userState.instantApp;
12756            return res;
12757        }
12758
12759        @Override
12760        protected void sortResults(List<ResolveInfo> results) {
12761            Collections.sort(results, mResolvePrioritySorter);
12762        }
12763
12764        @Override
12765        protected void dumpFilter(PrintWriter out, String prefix,
12766                PackageParser.ActivityIntentInfo filter) {
12767            out.print(prefix); out.print(
12768                    Integer.toHexString(System.identityHashCode(filter.activity)));
12769                    out.print(' ');
12770                    filter.activity.printComponentShortName(out);
12771                    out.print(" filter ");
12772                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12773        }
12774
12775        @Override
12776        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12777            return filter.activity;
12778        }
12779
12780        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12781            PackageParser.Activity activity = (PackageParser.Activity)label;
12782            out.print(prefix); out.print(
12783                    Integer.toHexString(System.identityHashCode(activity)));
12784                    out.print(' ');
12785                    activity.printComponentShortName(out);
12786            if (count > 1) {
12787                out.print(" ("); out.print(count); out.print(" filters)");
12788            }
12789            out.println();
12790        }
12791
12792        // Keys are String (activity class name), values are Activity.
12793        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12794                = new ArrayMap<ComponentName, PackageParser.Activity>();
12795        private int mFlags;
12796    }
12797
12798    private final class ServiceIntentResolver
12799            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12800        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12801                boolean defaultOnly, int userId) {
12802            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12803            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12804        }
12805
12806        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12807                int userId) {
12808            if (!sUserManager.exists(userId)) return null;
12809            mFlags = flags;
12810            return super.queryIntent(intent, resolvedType,
12811                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12812                    userId);
12813        }
12814
12815        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12816                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12817            if (!sUserManager.exists(userId)) return null;
12818            if (packageServices == null) {
12819                return null;
12820            }
12821            mFlags = flags;
12822            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12823            final int N = packageServices.size();
12824            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12825                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12826
12827            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12828            for (int i = 0; i < N; ++i) {
12829                intentFilters = packageServices.get(i).intents;
12830                if (intentFilters != null && intentFilters.size() > 0) {
12831                    PackageParser.ServiceIntentInfo[] array =
12832                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12833                    intentFilters.toArray(array);
12834                    listCut.add(array);
12835                }
12836            }
12837            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12838        }
12839
12840        public final void addService(PackageParser.Service s) {
12841            mServices.put(s.getComponentName(), s);
12842            if (DEBUG_SHOW_INFO) {
12843                Log.v(TAG, "  "
12844                        + (s.info.nonLocalizedLabel != null
12845                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12846                Log.v(TAG, "    Class=" + s.info.name);
12847            }
12848            final int NI = s.intents.size();
12849            int j;
12850            for (j=0; j<NI; j++) {
12851                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12852                if (DEBUG_SHOW_INFO) {
12853                    Log.v(TAG, "    IntentFilter:");
12854                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12855                }
12856                if (!intent.debugCheck()) {
12857                    Log.w(TAG, "==> For Service " + s.info.name);
12858                }
12859                addFilter(intent);
12860            }
12861        }
12862
12863        public final void removeService(PackageParser.Service s) {
12864            mServices.remove(s.getComponentName());
12865            if (DEBUG_SHOW_INFO) {
12866                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12867                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12868                Log.v(TAG, "    Class=" + s.info.name);
12869            }
12870            final int NI = s.intents.size();
12871            int j;
12872            for (j=0; j<NI; j++) {
12873                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12874                if (DEBUG_SHOW_INFO) {
12875                    Log.v(TAG, "    IntentFilter:");
12876                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12877                }
12878                removeFilter(intent);
12879            }
12880        }
12881
12882        @Override
12883        protected boolean allowFilterResult(
12884                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12885            ServiceInfo filterSi = filter.service.info;
12886            for (int i=dest.size()-1; i>=0; i--) {
12887                ServiceInfo destAi = dest.get(i).serviceInfo;
12888                if (destAi.name == filterSi.name
12889                        && destAi.packageName == filterSi.packageName) {
12890                    return false;
12891                }
12892            }
12893            return true;
12894        }
12895
12896        @Override
12897        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12898            return new PackageParser.ServiceIntentInfo[size];
12899        }
12900
12901        @Override
12902        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12903            if (!sUserManager.exists(userId)) return true;
12904            PackageParser.Package p = filter.service.owner;
12905            if (p != null) {
12906                PackageSetting ps = (PackageSetting)p.mExtras;
12907                if (ps != null) {
12908                    // System apps are never considered stopped for purposes of
12909                    // filtering, because there may be no way for the user to
12910                    // actually re-launch them.
12911                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12912                            && ps.getStopped(userId);
12913                }
12914            }
12915            return false;
12916        }
12917
12918        @Override
12919        protected boolean isPackageForFilter(String packageName,
12920                PackageParser.ServiceIntentInfo info) {
12921            return packageName.equals(info.service.owner.packageName);
12922        }
12923
12924        @Override
12925        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12926                int match, int userId) {
12927            if (!sUserManager.exists(userId)) return null;
12928            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12929            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12930                return null;
12931            }
12932            final PackageParser.Service service = info.service;
12933            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12934            if (ps == null) {
12935                return null;
12936            }
12937            final PackageUserState userState = ps.readUserState(userId);
12938            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12939                    userState, userId);
12940            if (si == null) {
12941                return null;
12942            }
12943            final boolean matchVisibleToInstantApp =
12944                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12945            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12946            // throw out filters that aren't visible to ephemeral apps
12947            if (matchVisibleToInstantApp
12948                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12949                return null;
12950            }
12951            // throw out ephemeral filters if we're not explicitly requesting them
12952            if (!isInstantApp && userState.instantApp) {
12953                return null;
12954            }
12955            // throw out instant app filters if updates are available; will trigger
12956            // instant app resolution
12957            if (userState.instantApp && ps.isUpdateAvailable()) {
12958                return null;
12959            }
12960            final ResolveInfo res = new ResolveInfo();
12961            res.serviceInfo = si;
12962            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12963                res.filter = filter;
12964            }
12965            res.priority = info.getPriority();
12966            res.preferredOrder = service.owner.mPreferredOrder;
12967            res.match = match;
12968            res.isDefault = info.hasDefault;
12969            res.labelRes = info.labelRes;
12970            res.nonLocalizedLabel = info.nonLocalizedLabel;
12971            res.icon = info.icon;
12972            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12973            return res;
12974        }
12975
12976        @Override
12977        protected void sortResults(List<ResolveInfo> results) {
12978            Collections.sort(results, mResolvePrioritySorter);
12979        }
12980
12981        @Override
12982        protected void dumpFilter(PrintWriter out, String prefix,
12983                PackageParser.ServiceIntentInfo filter) {
12984            out.print(prefix); out.print(
12985                    Integer.toHexString(System.identityHashCode(filter.service)));
12986                    out.print(' ');
12987                    filter.service.printComponentShortName(out);
12988                    out.print(" filter ");
12989                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12990                    if (filter.service.info.permission != null) {
12991                        out.print(" permission "); out.println(filter.service.info.permission);
12992                    } else {
12993                        out.println();
12994                    }
12995        }
12996
12997        @Override
12998        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12999            return filter.service;
13000        }
13001
13002        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13003            PackageParser.Service service = (PackageParser.Service)label;
13004            out.print(prefix); out.print(
13005                    Integer.toHexString(System.identityHashCode(service)));
13006                    out.print(' ');
13007                    service.printComponentShortName(out);
13008            if (count > 1) {
13009                out.print(" ("); out.print(count); out.print(" filters)");
13010            }
13011            out.println();
13012        }
13013
13014//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13015//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13016//            final List<ResolveInfo> retList = Lists.newArrayList();
13017//            while (i.hasNext()) {
13018//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13019//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13020//                    retList.add(resolveInfo);
13021//                }
13022//            }
13023//            return retList;
13024//        }
13025
13026        // Keys are String (activity class name), values are Activity.
13027        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13028                = new ArrayMap<ComponentName, PackageParser.Service>();
13029        private int mFlags;
13030    }
13031
13032    private final class ProviderIntentResolver
13033            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13034        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13035                boolean defaultOnly, int userId) {
13036            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13037            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13038        }
13039
13040        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13041                int userId) {
13042            if (!sUserManager.exists(userId))
13043                return null;
13044            mFlags = flags;
13045            return super.queryIntent(intent, resolvedType,
13046                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13047                    userId);
13048        }
13049
13050        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13051                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13052            if (!sUserManager.exists(userId))
13053                return null;
13054            if (packageProviders == null) {
13055                return null;
13056            }
13057            mFlags = flags;
13058            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13059            final int N = packageProviders.size();
13060            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13061                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13062
13063            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13064            for (int i = 0; i < N; ++i) {
13065                intentFilters = packageProviders.get(i).intents;
13066                if (intentFilters != null && intentFilters.size() > 0) {
13067                    PackageParser.ProviderIntentInfo[] array =
13068                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13069                    intentFilters.toArray(array);
13070                    listCut.add(array);
13071                }
13072            }
13073            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13074        }
13075
13076        public final void addProvider(PackageParser.Provider p) {
13077            if (mProviders.containsKey(p.getComponentName())) {
13078                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13079                return;
13080            }
13081
13082            mProviders.put(p.getComponentName(), p);
13083            if (DEBUG_SHOW_INFO) {
13084                Log.v(TAG, "  "
13085                        + (p.info.nonLocalizedLabel != null
13086                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13087                Log.v(TAG, "    Class=" + p.info.name);
13088            }
13089            final int NI = p.intents.size();
13090            int j;
13091            for (j = 0; j < NI; j++) {
13092                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13093                if (DEBUG_SHOW_INFO) {
13094                    Log.v(TAG, "    IntentFilter:");
13095                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13096                }
13097                if (!intent.debugCheck()) {
13098                    Log.w(TAG, "==> For Provider " + p.info.name);
13099                }
13100                addFilter(intent);
13101            }
13102        }
13103
13104        public final void removeProvider(PackageParser.Provider p) {
13105            mProviders.remove(p.getComponentName());
13106            if (DEBUG_SHOW_INFO) {
13107                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13108                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13109                Log.v(TAG, "    Class=" + p.info.name);
13110            }
13111            final int NI = p.intents.size();
13112            int j;
13113            for (j = 0; j < NI; j++) {
13114                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13115                if (DEBUG_SHOW_INFO) {
13116                    Log.v(TAG, "    IntentFilter:");
13117                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13118                }
13119                removeFilter(intent);
13120            }
13121        }
13122
13123        @Override
13124        protected boolean allowFilterResult(
13125                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13126            ProviderInfo filterPi = filter.provider.info;
13127            for (int i = dest.size() - 1; i >= 0; i--) {
13128                ProviderInfo destPi = dest.get(i).providerInfo;
13129                if (destPi.name == filterPi.name
13130                        && destPi.packageName == filterPi.packageName) {
13131                    return false;
13132                }
13133            }
13134            return true;
13135        }
13136
13137        @Override
13138        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13139            return new PackageParser.ProviderIntentInfo[size];
13140        }
13141
13142        @Override
13143        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13144            if (!sUserManager.exists(userId))
13145                return true;
13146            PackageParser.Package p = filter.provider.owner;
13147            if (p != null) {
13148                PackageSetting ps = (PackageSetting) p.mExtras;
13149                if (ps != null) {
13150                    // System apps are never considered stopped for purposes of
13151                    // filtering, because there may be no way for the user to
13152                    // actually re-launch them.
13153                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13154                            && ps.getStopped(userId);
13155                }
13156            }
13157            return false;
13158        }
13159
13160        @Override
13161        protected boolean isPackageForFilter(String packageName,
13162                PackageParser.ProviderIntentInfo info) {
13163            return packageName.equals(info.provider.owner.packageName);
13164        }
13165
13166        @Override
13167        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13168                int match, int userId) {
13169            if (!sUserManager.exists(userId))
13170                return null;
13171            final PackageParser.ProviderIntentInfo info = filter;
13172            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13173                return null;
13174            }
13175            final PackageParser.Provider provider = info.provider;
13176            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13177            if (ps == null) {
13178                return null;
13179            }
13180            final PackageUserState userState = ps.readUserState(userId);
13181            final boolean matchVisibleToInstantApp =
13182                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13183            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13184            // throw out filters that aren't visible to instant applications
13185            if (matchVisibleToInstantApp
13186                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13187                return null;
13188            }
13189            // throw out instant application filters if we're not explicitly requesting them
13190            if (!isInstantApp && userState.instantApp) {
13191                return null;
13192            }
13193            // throw out instant application filters if updates are available; will trigger
13194            // instant application resolution
13195            if (userState.instantApp && ps.isUpdateAvailable()) {
13196                return null;
13197            }
13198            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13199                    userState, userId);
13200            if (pi == null) {
13201                return null;
13202            }
13203            final ResolveInfo res = new ResolveInfo();
13204            res.providerInfo = pi;
13205            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13206                res.filter = filter;
13207            }
13208            res.priority = info.getPriority();
13209            res.preferredOrder = provider.owner.mPreferredOrder;
13210            res.match = match;
13211            res.isDefault = info.hasDefault;
13212            res.labelRes = info.labelRes;
13213            res.nonLocalizedLabel = info.nonLocalizedLabel;
13214            res.icon = info.icon;
13215            res.system = res.providerInfo.applicationInfo.isSystemApp();
13216            return res;
13217        }
13218
13219        @Override
13220        protected void sortResults(List<ResolveInfo> results) {
13221            Collections.sort(results, mResolvePrioritySorter);
13222        }
13223
13224        @Override
13225        protected void dumpFilter(PrintWriter out, String prefix,
13226                PackageParser.ProviderIntentInfo filter) {
13227            out.print(prefix);
13228            out.print(
13229                    Integer.toHexString(System.identityHashCode(filter.provider)));
13230            out.print(' ');
13231            filter.provider.printComponentShortName(out);
13232            out.print(" filter ");
13233            out.println(Integer.toHexString(System.identityHashCode(filter)));
13234        }
13235
13236        @Override
13237        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13238            return filter.provider;
13239        }
13240
13241        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13242            PackageParser.Provider provider = (PackageParser.Provider)label;
13243            out.print(prefix); out.print(
13244                    Integer.toHexString(System.identityHashCode(provider)));
13245                    out.print(' ');
13246                    provider.printComponentShortName(out);
13247            if (count > 1) {
13248                out.print(" ("); out.print(count); out.print(" filters)");
13249            }
13250            out.println();
13251        }
13252
13253        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13254                = new ArrayMap<ComponentName, PackageParser.Provider>();
13255        private int mFlags;
13256    }
13257
13258    static final class EphemeralIntentResolver
13259            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13260            AuxiliaryResolveInfo.AuxiliaryFilter> {
13261        /**
13262         * The result that has the highest defined order. Ordering applies on a
13263         * per-package basis. Mapping is from package name to Pair of order and
13264         * EphemeralResolveInfo.
13265         * <p>
13266         * NOTE: This is implemented as a field variable for convenience and efficiency.
13267         * By having a field variable, we're able to track filter ordering as soon as
13268         * a non-zero order is defined. Otherwise, multiple loops across the result set
13269         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13270         * this needs to be contained entirely within {@link #filterResults}.
13271         */
13272        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13273
13274        @Override
13275        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13276            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13277        }
13278
13279        @Override
13280        protected boolean isPackageForFilter(String packageName,
13281                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13282            return true;
13283        }
13284
13285        @Override
13286        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13287                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13288            if (!sUserManager.exists(userId)) {
13289                return null;
13290            }
13291            final String packageName = responseObj.resolveInfo.getPackageName();
13292            final Integer order = responseObj.getOrder();
13293            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13294                    mOrderResult.get(packageName);
13295            // ordering is enabled and this item's order isn't high enough
13296            if (lastOrderResult != null && lastOrderResult.first >= order) {
13297                return null;
13298            }
13299            final InstantAppResolveInfo res = responseObj.resolveInfo;
13300            if (order > 0) {
13301                // non-zero order, enable ordering
13302                mOrderResult.put(packageName, new Pair<>(order, res));
13303            }
13304            return responseObj;
13305        }
13306
13307        @Override
13308        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13309            // only do work if ordering is enabled [most of the time it won't be]
13310            if (mOrderResult.size() == 0) {
13311                return;
13312            }
13313            int resultSize = results.size();
13314            for (int i = 0; i < resultSize; i++) {
13315                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13316                final String packageName = info.getPackageName();
13317                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13318                if (savedInfo == null) {
13319                    // package doesn't having ordering
13320                    continue;
13321                }
13322                if (savedInfo.second == info) {
13323                    // circled back to the highest ordered item; remove from order list
13324                    mOrderResult.remove(packageName);
13325                    if (mOrderResult.size() == 0) {
13326                        // no more ordered items
13327                        break;
13328                    }
13329                    continue;
13330                }
13331                // item has a worse order, remove it from the result list
13332                results.remove(i);
13333                resultSize--;
13334                i--;
13335            }
13336        }
13337    }
13338
13339    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13340            new Comparator<ResolveInfo>() {
13341        public int compare(ResolveInfo r1, ResolveInfo r2) {
13342            int v1 = r1.priority;
13343            int v2 = r2.priority;
13344            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13345            if (v1 != v2) {
13346                return (v1 > v2) ? -1 : 1;
13347            }
13348            v1 = r1.preferredOrder;
13349            v2 = r2.preferredOrder;
13350            if (v1 != v2) {
13351                return (v1 > v2) ? -1 : 1;
13352            }
13353            if (r1.isDefault != r2.isDefault) {
13354                return r1.isDefault ? -1 : 1;
13355            }
13356            v1 = r1.match;
13357            v2 = r2.match;
13358            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13359            if (v1 != v2) {
13360                return (v1 > v2) ? -1 : 1;
13361            }
13362            if (r1.system != r2.system) {
13363                return r1.system ? -1 : 1;
13364            }
13365            if (r1.activityInfo != null) {
13366                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13367            }
13368            if (r1.serviceInfo != null) {
13369                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13370            }
13371            if (r1.providerInfo != null) {
13372                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13373            }
13374            return 0;
13375        }
13376    };
13377
13378    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13379            new Comparator<ProviderInfo>() {
13380        public int compare(ProviderInfo p1, ProviderInfo p2) {
13381            final int v1 = p1.initOrder;
13382            final int v2 = p2.initOrder;
13383            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13384        }
13385    };
13386
13387    @Override
13388    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13389            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13390            final int[] userIds, int[] instantUserIds) {
13391        mHandler.post(new Runnable() {
13392            @Override
13393            public void run() {
13394                try {
13395                    final IActivityManager am = ActivityManager.getService();
13396                    if (am == null) return;
13397                    final int[] resolvedUserIds;
13398                    if (userIds == null) {
13399                        resolvedUserIds = am.getRunningUserIds();
13400                    } else {
13401                        resolvedUserIds = userIds;
13402                    }
13403                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13404                            resolvedUserIds, false);
13405                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13406                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13407                                instantUserIds, true);
13408                    }
13409                } catch (RemoteException ex) {
13410                }
13411            }
13412        });
13413    }
13414
13415    @Override
13416    public void notifyPackageAdded(String packageName) {
13417        final PackageListObserver[] observers;
13418        synchronized (mPackages) {
13419            if (mPackageListObservers.size() == 0) {
13420                return;
13421            }
13422            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13423        }
13424        for (int i = observers.length - 1; i >= 0; --i) {
13425            observers[i].onPackageAdded(packageName);
13426        }
13427    }
13428
13429    @Override
13430    public void notifyPackageRemoved(String packageName) {
13431        final PackageListObserver[] observers;
13432        synchronized (mPackages) {
13433            if (mPackageListObservers.size() == 0) {
13434                return;
13435            }
13436            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13437        }
13438        for (int i = observers.length - 1; i >= 0; --i) {
13439            observers[i].onPackageRemoved(packageName);
13440        }
13441    }
13442
13443    /**
13444     * Sends a broadcast for the given action.
13445     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13446     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13447     * the system and applications allowed to see instant applications to receive package
13448     * lifecycle events for instant applications.
13449     */
13450    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13451            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13452            int[] userIds, boolean isInstantApp)
13453                    throws RemoteException {
13454        for (int id : userIds) {
13455            final Intent intent = new Intent(action,
13456                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13457            final String[] requiredPermissions =
13458                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13459            if (extras != null) {
13460                intent.putExtras(extras);
13461            }
13462            if (targetPkg != null) {
13463                intent.setPackage(targetPkg);
13464            }
13465            // Modify the UID when posting to other users
13466            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13467            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13468                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13469                intent.putExtra(Intent.EXTRA_UID, uid);
13470            }
13471            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13472            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13473            if (DEBUG_BROADCASTS) {
13474                RuntimeException here = new RuntimeException("here");
13475                here.fillInStackTrace();
13476                Slog.d(TAG, "Sending to user " + id + ": "
13477                        + intent.toShortString(false, true, false, false)
13478                        + " " + intent.getExtras(), here);
13479            }
13480            am.broadcastIntent(null, intent, null, finishedReceiver,
13481                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13482                    null, finishedReceiver != null, false, id);
13483        }
13484    }
13485
13486    /**
13487     * Check if the external storage media is available. This is true if there
13488     * is a mounted external storage medium or if the external storage is
13489     * emulated.
13490     */
13491    private boolean isExternalMediaAvailable() {
13492        return mMediaMounted || Environment.isExternalStorageEmulated();
13493    }
13494
13495    @Override
13496    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13497        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13498            return null;
13499        }
13500        if (!isExternalMediaAvailable()) {
13501                // If the external storage is no longer mounted at this point,
13502                // the caller may not have been able to delete all of this
13503                // packages files and can not delete any more.  Bail.
13504            return null;
13505        }
13506        synchronized (mPackages) {
13507            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13508            if (lastPackage != null) {
13509                pkgs.remove(lastPackage);
13510            }
13511            if (pkgs.size() > 0) {
13512                return pkgs.get(0);
13513            }
13514        }
13515        return null;
13516    }
13517
13518    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13519        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13520                userId, andCode ? 1 : 0, packageName);
13521        if (mSystemReady) {
13522            msg.sendToTarget();
13523        } else {
13524            if (mPostSystemReadyMessages == null) {
13525                mPostSystemReadyMessages = new ArrayList<>();
13526            }
13527            mPostSystemReadyMessages.add(msg);
13528        }
13529    }
13530
13531    void startCleaningPackages() {
13532        // reader
13533        if (!isExternalMediaAvailable()) {
13534            return;
13535        }
13536        synchronized (mPackages) {
13537            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13538                return;
13539            }
13540        }
13541        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13542        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13543        IActivityManager am = ActivityManager.getService();
13544        if (am != null) {
13545            int dcsUid = -1;
13546            synchronized (mPackages) {
13547                if (!mDefaultContainerWhitelisted) {
13548                    mDefaultContainerWhitelisted = true;
13549                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13550                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13551                }
13552            }
13553            try {
13554                if (dcsUid > 0) {
13555                    am.backgroundWhitelistUid(dcsUid);
13556                }
13557                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13558                        UserHandle.USER_SYSTEM);
13559            } catch (RemoteException e) {
13560            }
13561        }
13562    }
13563
13564    /**
13565     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13566     * it is acting on behalf on an enterprise or the user).
13567     *
13568     * Note that the ordering of the conditionals in this method is important. The checks we perform
13569     * are as follows, in this order:
13570     *
13571     * 1) If the install is being performed by a system app, we can trust the app to have set the
13572     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13573     *    what it is.
13574     * 2) If the install is being performed by a device or profile owner app, the install reason
13575     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13576     *    set the install reason correctly. If the app targets an older SDK version where install
13577     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13578     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13579     * 3) In all other cases, the install is being performed by a regular app that is neither part
13580     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13581     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13582     *    set to enterprise policy and if so, change it to unknown instead.
13583     */
13584    private int fixUpInstallReason(String installerPackageName, int installerUid,
13585            int installReason) {
13586        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13587                == PERMISSION_GRANTED) {
13588            // If the install is being performed by a system app, we trust that app to have set the
13589            // install reason correctly.
13590            return installReason;
13591        }
13592
13593        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13594            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13595        if (dpm != null) {
13596            ComponentName owner = null;
13597            try {
13598                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13599                if (owner == null) {
13600                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13601                }
13602            } catch (RemoteException e) {
13603            }
13604            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13605                // If the install is being performed by a device or profile owner, the install
13606                // reason should be enterprise policy.
13607                return PackageManager.INSTALL_REASON_POLICY;
13608            }
13609        }
13610
13611        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13612            // If the install is being performed by a regular app (i.e. neither system app nor
13613            // device or profile owner), we have no reason to believe that the app is acting on
13614            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13615            // change it to unknown instead.
13616            return PackageManager.INSTALL_REASON_UNKNOWN;
13617        }
13618
13619        // If the install is being performed by a regular app and the install reason was set to any
13620        // value but enterprise policy, leave the install reason unchanged.
13621        return installReason;
13622    }
13623
13624    void installStage(String packageName, File stagedDir,
13625            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13626            String installerPackageName, int installerUid, UserHandle user,
13627            PackageParser.SigningDetails signingDetails) {
13628        if (DEBUG_EPHEMERAL) {
13629            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13630                Slog.d(TAG, "Ephemeral install of " + packageName);
13631            }
13632        }
13633        final VerificationInfo verificationInfo = new VerificationInfo(
13634                sessionParams.originatingUri, sessionParams.referrerUri,
13635                sessionParams.originatingUid, installerUid);
13636
13637        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13638
13639        final Message msg = mHandler.obtainMessage(INIT_COPY);
13640        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13641                sessionParams.installReason);
13642        final InstallParams params = new InstallParams(origin, null, observer,
13643                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13644                verificationInfo, user, sessionParams.abiOverride,
13645                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13646        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13647        msg.obj = params;
13648
13649        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13650                System.identityHashCode(msg.obj));
13651        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13652                System.identityHashCode(msg.obj));
13653
13654        mHandler.sendMessage(msg);
13655    }
13656
13657    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13658            int userId) {
13659        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13660        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13661        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13662        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13663        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13664                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13665
13666        // Send a session commit broadcast
13667        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13668        info.installReason = pkgSetting.getInstallReason(userId);
13669        info.appPackageName = packageName;
13670        sendSessionCommitBroadcast(info, userId);
13671    }
13672
13673    @Override
13674    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13675            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13676        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13677            return;
13678        }
13679        Bundle extras = new Bundle(1);
13680        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13681        final int uid = UserHandle.getUid(
13682                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13683        extras.putInt(Intent.EXTRA_UID, uid);
13684
13685        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13686                packageName, extras, 0, null, null, userIds, instantUserIds);
13687        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13688            mHandler.post(() -> {
13689                        for (int userId : userIds) {
13690                            sendBootCompletedBroadcastToSystemApp(
13691                                    packageName, includeStopped, userId);
13692                        }
13693                    }
13694            );
13695        }
13696    }
13697
13698    /**
13699     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13700     * automatically without needing an explicit launch.
13701     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13702     */
13703    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13704            int userId) {
13705        // If user is not running, the app didn't miss any broadcast
13706        if (!mUserManagerInternal.isUserRunning(userId)) {
13707            return;
13708        }
13709        final IActivityManager am = ActivityManager.getService();
13710        try {
13711            // Deliver LOCKED_BOOT_COMPLETED first
13712            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13713                    .setPackage(packageName);
13714            if (includeStopped) {
13715                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13716            }
13717            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13718            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13719                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13720
13721            // Deliver BOOT_COMPLETED only if user is unlocked
13722            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13723                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13724                if (includeStopped) {
13725                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13726                }
13727                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13728                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13729            }
13730        } catch (RemoteException e) {
13731            throw e.rethrowFromSystemServer();
13732        }
13733    }
13734
13735    @Override
13736    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13737            int userId) {
13738        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13739        PackageSetting pkgSetting;
13740        final int callingUid = Binder.getCallingUid();
13741        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13742                true /* requireFullPermission */, true /* checkShell */,
13743                "setApplicationHiddenSetting for user " + userId);
13744
13745        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13746            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13747            return false;
13748        }
13749
13750        long callingId = Binder.clearCallingIdentity();
13751        try {
13752            boolean sendAdded = false;
13753            boolean sendRemoved = false;
13754            // writer
13755            synchronized (mPackages) {
13756                pkgSetting = mSettings.mPackages.get(packageName);
13757                if (pkgSetting == null) {
13758                    return false;
13759                }
13760                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13761                    return false;
13762                }
13763                // Do not allow "android" is being disabled
13764                if ("android".equals(packageName)) {
13765                    Slog.w(TAG, "Cannot hide package: android");
13766                    return false;
13767                }
13768                // Cannot hide static shared libs as they are considered
13769                // a part of the using app (emulating static linking). Also
13770                // static libs are installed always on internal storage.
13771                PackageParser.Package pkg = mPackages.get(packageName);
13772                if (pkg != null && pkg.staticSharedLibName != null) {
13773                    Slog.w(TAG, "Cannot hide package: " + packageName
13774                            + " providing static shared library: "
13775                            + pkg.staticSharedLibName);
13776                    return false;
13777                }
13778                // Only allow protected packages to hide themselves.
13779                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13780                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13781                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13782                    return false;
13783                }
13784
13785                if (pkgSetting.getHidden(userId) != hidden) {
13786                    pkgSetting.setHidden(hidden, userId);
13787                    mSettings.writePackageRestrictionsLPr(userId);
13788                    if (hidden) {
13789                        sendRemoved = true;
13790                    } else {
13791                        sendAdded = true;
13792                    }
13793                }
13794            }
13795            if (sendAdded) {
13796                sendPackageAddedForUser(packageName, pkgSetting, userId);
13797                return true;
13798            }
13799            if (sendRemoved) {
13800                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13801                        "hiding pkg");
13802                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13803                return true;
13804            }
13805        } finally {
13806            Binder.restoreCallingIdentity(callingId);
13807        }
13808        return false;
13809    }
13810
13811    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13812            int userId) {
13813        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13814        info.removedPackage = packageName;
13815        info.installerPackageName = pkgSetting.installerPackageName;
13816        info.removedUsers = new int[] {userId};
13817        info.broadcastUsers = new int[] {userId};
13818        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13819        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13820    }
13821
13822    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13823        if (pkgList.length > 0) {
13824            Bundle extras = new Bundle(1);
13825            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13826
13827            sendPackageBroadcast(
13828                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13829                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13830                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13831                    new int[] {userId}, null);
13832        }
13833    }
13834
13835    /**
13836     * Returns true if application is not found or there was an error. Otherwise it returns
13837     * the hidden state of the package for the given user.
13838     */
13839    @Override
13840    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13841        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13842        final int callingUid = Binder.getCallingUid();
13843        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13844                true /* requireFullPermission */, false /* checkShell */,
13845                "getApplicationHidden for user " + userId);
13846        PackageSetting ps;
13847        long callingId = Binder.clearCallingIdentity();
13848        try {
13849            // writer
13850            synchronized (mPackages) {
13851                ps = mSettings.mPackages.get(packageName);
13852                if (ps == null) {
13853                    return true;
13854                }
13855                if (filterAppAccessLPr(ps, callingUid, userId)) {
13856                    return true;
13857                }
13858                return ps.getHidden(userId);
13859            }
13860        } finally {
13861            Binder.restoreCallingIdentity(callingId);
13862        }
13863    }
13864
13865    /**
13866     * @hide
13867     */
13868    @Override
13869    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13870            int installReason) {
13871        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13872                null);
13873        PackageSetting pkgSetting;
13874        final int callingUid = Binder.getCallingUid();
13875        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13876                true /* requireFullPermission */, true /* checkShell */,
13877                "installExistingPackage for user " + userId);
13878        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13879            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13880        }
13881
13882        long callingId = Binder.clearCallingIdentity();
13883        try {
13884            boolean installed = false;
13885            final boolean instantApp =
13886                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13887            final boolean fullApp =
13888                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13889
13890            // writer
13891            synchronized (mPackages) {
13892                pkgSetting = mSettings.mPackages.get(packageName);
13893                if (pkgSetting == null) {
13894                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13895                }
13896                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13897                    // only allow the existing package to be used if it's installed as a full
13898                    // application for at least one user
13899                    boolean installAllowed = false;
13900                    for (int checkUserId : sUserManager.getUserIds()) {
13901                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13902                        if (installAllowed) {
13903                            break;
13904                        }
13905                    }
13906                    if (!installAllowed) {
13907                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13908                    }
13909                }
13910                if (!pkgSetting.getInstalled(userId)) {
13911                    pkgSetting.setInstalled(true, userId);
13912                    pkgSetting.setHidden(false, userId);
13913                    pkgSetting.setInstallReason(installReason, userId);
13914                    mSettings.writePackageRestrictionsLPr(userId);
13915                    mSettings.writeKernelMappingLPr(pkgSetting);
13916                    installed = true;
13917                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13918                    // upgrade app from instant to full; we don't allow app downgrade
13919                    installed = true;
13920                }
13921                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13922            }
13923
13924            if (installed) {
13925                if (pkgSetting.pkg != null) {
13926                    synchronized (mInstallLock) {
13927                        // We don't need to freeze for a brand new install
13928                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13929                    }
13930                }
13931                sendPackageAddedForUser(packageName, pkgSetting, userId);
13932                synchronized (mPackages) {
13933                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13934                }
13935            }
13936        } finally {
13937            Binder.restoreCallingIdentity(callingId);
13938        }
13939
13940        return PackageManager.INSTALL_SUCCEEDED;
13941    }
13942
13943    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13944            boolean instantApp, boolean fullApp) {
13945        // no state specified; do nothing
13946        if (!instantApp && !fullApp) {
13947            return;
13948        }
13949        if (userId != UserHandle.USER_ALL) {
13950            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13951                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13952            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13953                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13954            }
13955        } else {
13956            for (int currentUserId : sUserManager.getUserIds()) {
13957                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13958                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13959                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13960                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13961                }
13962            }
13963        }
13964    }
13965
13966    boolean isUserRestricted(int userId, String restrictionKey) {
13967        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13968        if (restrictions.getBoolean(restrictionKey, false)) {
13969            Log.w(TAG, "User is restricted: " + restrictionKey);
13970            return true;
13971        }
13972        return false;
13973    }
13974
13975    @Override
13976    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13977            int userId) {
13978        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13979        final int callingUid = Binder.getCallingUid();
13980        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13981                true /* requireFullPermission */, true /* checkShell */,
13982                "setPackagesSuspended for user " + userId);
13983
13984        if (ArrayUtils.isEmpty(packageNames)) {
13985            return packageNames;
13986        }
13987
13988        // List of package names for whom the suspended state has changed.
13989        List<String> changedPackages = new ArrayList<>(packageNames.length);
13990        // List of package names for whom the suspended state is not set as requested in this
13991        // method.
13992        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13993        long callingId = Binder.clearCallingIdentity();
13994        try {
13995            for (int i = 0; i < packageNames.length; i++) {
13996                String packageName = packageNames[i];
13997                boolean changed = false;
13998                final int appId;
13999                synchronized (mPackages) {
14000                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14001                    if (pkgSetting == null
14002                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14003                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14004                                + "\". Skipping suspending/un-suspending.");
14005                        unactionedPackages.add(packageName);
14006                        continue;
14007                    }
14008                    appId = pkgSetting.appId;
14009                    if (pkgSetting.getSuspended(userId) != suspended) {
14010                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14011                            unactionedPackages.add(packageName);
14012                            continue;
14013                        }
14014                        pkgSetting.setSuspended(suspended, userId);
14015                        mSettings.writePackageRestrictionsLPr(userId);
14016                        changed = true;
14017                        changedPackages.add(packageName);
14018                    }
14019                }
14020
14021                if (changed && suspended) {
14022                    killApplication(packageName, UserHandle.getUid(userId, appId),
14023                            "suspending package");
14024                }
14025            }
14026        } finally {
14027            Binder.restoreCallingIdentity(callingId);
14028        }
14029
14030        if (!changedPackages.isEmpty()) {
14031            sendPackagesSuspendedForUser(changedPackages.toArray(
14032                    new String[changedPackages.size()]), userId, suspended);
14033        }
14034
14035        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14036    }
14037
14038    @Override
14039    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14040        final int callingUid = Binder.getCallingUid();
14041        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14042                true /* requireFullPermission */, false /* checkShell */,
14043                "isPackageSuspendedForUser for user " + userId);
14044        synchronized (mPackages) {
14045            final PackageSetting ps = mSettings.mPackages.get(packageName);
14046            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14047                throw new IllegalArgumentException("Unknown target package: " + packageName);
14048            }
14049            return ps.getSuspended(userId);
14050        }
14051    }
14052
14053    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14054        if (isPackageDeviceAdmin(packageName, userId)) {
14055            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14056                    + "\": has an active device admin");
14057            return false;
14058        }
14059
14060        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14061        if (packageName.equals(activeLauncherPackageName)) {
14062            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14063                    + "\": contains the active launcher");
14064            return false;
14065        }
14066
14067        if (packageName.equals(mRequiredInstallerPackage)) {
14068            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14069                    + "\": required for package installation");
14070            return false;
14071        }
14072
14073        if (packageName.equals(mRequiredUninstallerPackage)) {
14074            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14075                    + "\": required for package uninstallation");
14076            return false;
14077        }
14078
14079        if (packageName.equals(mRequiredVerifierPackage)) {
14080            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14081                    + "\": required for package verification");
14082            return false;
14083        }
14084
14085        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14086            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14087                    + "\": is the default dialer");
14088            return false;
14089        }
14090
14091        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14092            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14093                    + "\": protected package");
14094            return false;
14095        }
14096
14097        // Cannot suspend static shared libs as they are considered
14098        // a part of the using app (emulating static linking). Also
14099        // static libs are installed always on internal storage.
14100        PackageParser.Package pkg = mPackages.get(packageName);
14101        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14102            Slog.w(TAG, "Cannot suspend package: " + packageName
14103                    + " providing static shared library: "
14104                    + pkg.staticSharedLibName);
14105            return false;
14106        }
14107
14108        return true;
14109    }
14110
14111    private String getActiveLauncherPackageName(int userId) {
14112        Intent intent = new Intent(Intent.ACTION_MAIN);
14113        intent.addCategory(Intent.CATEGORY_HOME);
14114        ResolveInfo resolveInfo = resolveIntent(
14115                intent,
14116                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14117                PackageManager.MATCH_DEFAULT_ONLY,
14118                userId);
14119
14120        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14121    }
14122
14123    private String getDefaultDialerPackageName(int userId) {
14124        synchronized (mPackages) {
14125            return mSettings.getDefaultDialerPackageNameLPw(userId);
14126        }
14127    }
14128
14129    @Override
14130    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14131        mContext.enforceCallingOrSelfPermission(
14132                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14133                "Only package verification agents can verify applications");
14134
14135        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14136        final PackageVerificationResponse response = new PackageVerificationResponse(
14137                verificationCode, Binder.getCallingUid());
14138        msg.arg1 = id;
14139        msg.obj = response;
14140        mHandler.sendMessage(msg);
14141    }
14142
14143    @Override
14144    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14145            long millisecondsToDelay) {
14146        mContext.enforceCallingOrSelfPermission(
14147                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14148                "Only package verification agents can extend verification timeouts");
14149
14150        final PackageVerificationState state = mPendingVerification.get(id);
14151        final PackageVerificationResponse response = new PackageVerificationResponse(
14152                verificationCodeAtTimeout, Binder.getCallingUid());
14153
14154        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14155            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14156        }
14157        if (millisecondsToDelay < 0) {
14158            millisecondsToDelay = 0;
14159        }
14160        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14161                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14162            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14163        }
14164
14165        if ((state != null) && !state.timeoutExtended()) {
14166            state.extendTimeout();
14167
14168            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14169            msg.arg1 = id;
14170            msg.obj = response;
14171            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14172        }
14173    }
14174
14175    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14176            int verificationCode, UserHandle user) {
14177        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14178        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14179        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14180        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14181        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14182
14183        mContext.sendBroadcastAsUser(intent, user,
14184                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14185    }
14186
14187    private ComponentName matchComponentForVerifier(String packageName,
14188            List<ResolveInfo> receivers) {
14189        ActivityInfo targetReceiver = null;
14190
14191        final int NR = receivers.size();
14192        for (int i = 0; i < NR; i++) {
14193            final ResolveInfo info = receivers.get(i);
14194            if (info.activityInfo == null) {
14195                continue;
14196            }
14197
14198            if (packageName.equals(info.activityInfo.packageName)) {
14199                targetReceiver = info.activityInfo;
14200                break;
14201            }
14202        }
14203
14204        if (targetReceiver == null) {
14205            return null;
14206        }
14207
14208        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14209    }
14210
14211    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14212            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14213        if (pkgInfo.verifiers.length == 0) {
14214            return null;
14215        }
14216
14217        final int N = pkgInfo.verifiers.length;
14218        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14219        for (int i = 0; i < N; i++) {
14220            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14221
14222            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14223                    receivers);
14224            if (comp == null) {
14225                continue;
14226            }
14227
14228            final int verifierUid = getUidForVerifier(verifierInfo);
14229            if (verifierUid == -1) {
14230                continue;
14231            }
14232
14233            if (DEBUG_VERIFY) {
14234                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14235                        + " with the correct signature");
14236            }
14237            sufficientVerifiers.add(comp);
14238            verificationState.addSufficientVerifier(verifierUid);
14239        }
14240
14241        return sufficientVerifiers;
14242    }
14243
14244    private int getUidForVerifier(VerifierInfo verifierInfo) {
14245        synchronized (mPackages) {
14246            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14247            if (pkg == null) {
14248                return -1;
14249            } else if (pkg.mSigningDetails.signatures.length != 1) {
14250                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14251                        + " has more than one signature; ignoring");
14252                return -1;
14253            }
14254
14255            /*
14256             * If the public key of the package's signature does not match
14257             * our expected public key, then this is a different package and
14258             * we should skip.
14259             */
14260
14261            final byte[] expectedPublicKey;
14262            try {
14263                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14264                final PublicKey publicKey = verifierSig.getPublicKey();
14265                expectedPublicKey = publicKey.getEncoded();
14266            } catch (CertificateException e) {
14267                return -1;
14268            }
14269
14270            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14271
14272            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14273                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14274                        + " does not have the expected public key; ignoring");
14275                return -1;
14276            }
14277
14278            return pkg.applicationInfo.uid;
14279        }
14280    }
14281
14282    @Override
14283    public void finishPackageInstall(int token, boolean didLaunch) {
14284        enforceSystemOrRoot("Only the system is allowed to finish installs");
14285
14286        if (DEBUG_INSTALL) {
14287            Slog.v(TAG, "BM finishing package install for " + token);
14288        }
14289        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14290
14291        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14292        mHandler.sendMessage(msg);
14293    }
14294
14295    /**
14296     * Get the verification agent timeout.  Used for both the APK verifier and the
14297     * intent filter verifier.
14298     *
14299     * @return verification timeout in milliseconds
14300     */
14301    private long getVerificationTimeout() {
14302        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14303                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14304                DEFAULT_VERIFICATION_TIMEOUT);
14305    }
14306
14307    /**
14308     * Get the default verification agent response code.
14309     *
14310     * @return default verification response code
14311     */
14312    private int getDefaultVerificationResponse(UserHandle user) {
14313        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14314            return PackageManager.VERIFICATION_REJECT;
14315        }
14316        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14317                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14318                DEFAULT_VERIFICATION_RESPONSE);
14319    }
14320
14321    /**
14322     * Check whether or not package verification has been enabled.
14323     *
14324     * @return true if verification should be performed
14325     */
14326    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14327        if (!DEFAULT_VERIFY_ENABLE) {
14328            return false;
14329        }
14330
14331        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14332
14333        // Check if installing from ADB
14334        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14335            // Do not run verification in a test harness environment
14336            if (ActivityManager.isRunningInTestHarness()) {
14337                return false;
14338            }
14339            if (ensureVerifyAppsEnabled) {
14340                return true;
14341            }
14342            // Check if the developer does not want package verification for ADB installs
14343            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14344                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14345                return false;
14346            }
14347        } else {
14348            // only when not installed from ADB, skip verification for instant apps when
14349            // the installer and verifier are the same.
14350            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14351                if (mInstantAppInstallerActivity != null
14352                        && mInstantAppInstallerActivity.packageName.equals(
14353                                mRequiredVerifierPackage)) {
14354                    try {
14355                        mContext.getSystemService(AppOpsManager.class)
14356                                .checkPackage(installerUid, mRequiredVerifierPackage);
14357                        if (DEBUG_VERIFY) {
14358                            Slog.i(TAG, "disable verification for instant app");
14359                        }
14360                        return false;
14361                    } catch (SecurityException ignore) { }
14362                }
14363            }
14364        }
14365
14366        if (ensureVerifyAppsEnabled) {
14367            return true;
14368        }
14369
14370        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14371                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14372    }
14373
14374    @Override
14375    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14376            throws RemoteException {
14377        mContext.enforceCallingOrSelfPermission(
14378                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14379                "Only intentfilter verification agents can verify applications");
14380
14381        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14382        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14383                Binder.getCallingUid(), verificationCode, failedDomains);
14384        msg.arg1 = id;
14385        msg.obj = response;
14386        mHandler.sendMessage(msg);
14387    }
14388
14389    @Override
14390    public int getIntentVerificationStatus(String packageName, int userId) {
14391        final int callingUid = Binder.getCallingUid();
14392        if (UserHandle.getUserId(callingUid) != userId) {
14393            mContext.enforceCallingOrSelfPermission(
14394                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14395                    "getIntentVerificationStatus" + userId);
14396        }
14397        if (getInstantAppPackageName(callingUid) != null) {
14398            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14399        }
14400        synchronized (mPackages) {
14401            final PackageSetting ps = mSettings.mPackages.get(packageName);
14402            if (ps == null
14403                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14404                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14405            }
14406            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14407        }
14408    }
14409
14410    @Override
14411    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14412        mContext.enforceCallingOrSelfPermission(
14413                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14414
14415        boolean result = false;
14416        synchronized (mPackages) {
14417            final PackageSetting ps = mSettings.mPackages.get(packageName);
14418            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14419                return false;
14420            }
14421            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14422        }
14423        if (result) {
14424            scheduleWritePackageRestrictionsLocked(userId);
14425        }
14426        return result;
14427    }
14428
14429    @Override
14430    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14431            String packageName) {
14432        final int callingUid = Binder.getCallingUid();
14433        if (getInstantAppPackageName(callingUid) != null) {
14434            return ParceledListSlice.emptyList();
14435        }
14436        synchronized (mPackages) {
14437            final PackageSetting ps = mSettings.mPackages.get(packageName);
14438            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14439                return ParceledListSlice.emptyList();
14440            }
14441            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14442        }
14443    }
14444
14445    @Override
14446    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14447        if (TextUtils.isEmpty(packageName)) {
14448            return ParceledListSlice.emptyList();
14449        }
14450        final int callingUid = Binder.getCallingUid();
14451        final int callingUserId = UserHandle.getUserId(callingUid);
14452        synchronized (mPackages) {
14453            PackageParser.Package pkg = mPackages.get(packageName);
14454            if (pkg == null || pkg.activities == null) {
14455                return ParceledListSlice.emptyList();
14456            }
14457            if (pkg.mExtras == null) {
14458                return ParceledListSlice.emptyList();
14459            }
14460            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14461            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14462                return ParceledListSlice.emptyList();
14463            }
14464            final int count = pkg.activities.size();
14465            ArrayList<IntentFilter> result = new ArrayList<>();
14466            for (int n=0; n<count; n++) {
14467                PackageParser.Activity activity = pkg.activities.get(n);
14468                if (activity.intents != null && activity.intents.size() > 0) {
14469                    result.addAll(activity.intents);
14470                }
14471            }
14472            return new ParceledListSlice<>(result);
14473        }
14474    }
14475
14476    @Override
14477    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14478        mContext.enforceCallingOrSelfPermission(
14479                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14480        if (UserHandle.getCallingUserId() != userId) {
14481            mContext.enforceCallingOrSelfPermission(
14482                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14483        }
14484
14485        synchronized (mPackages) {
14486            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14487            if (packageName != null) {
14488                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14489                        packageName, userId);
14490            }
14491            return result;
14492        }
14493    }
14494
14495    @Override
14496    public String getDefaultBrowserPackageName(int userId) {
14497        if (UserHandle.getCallingUserId() != userId) {
14498            mContext.enforceCallingOrSelfPermission(
14499                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14500        }
14501        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14502            return null;
14503        }
14504        synchronized (mPackages) {
14505            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14506        }
14507    }
14508
14509    /**
14510     * Get the "allow unknown sources" setting.
14511     *
14512     * @return the current "allow unknown sources" setting
14513     */
14514    private int getUnknownSourcesSettings() {
14515        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14516                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14517                -1);
14518    }
14519
14520    @Override
14521    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14522        final int callingUid = Binder.getCallingUid();
14523        if (getInstantAppPackageName(callingUid) != null) {
14524            return;
14525        }
14526        // writer
14527        synchronized (mPackages) {
14528            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14529            if (targetPackageSetting == null
14530                    || filterAppAccessLPr(
14531                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14532                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14533            }
14534
14535            PackageSetting installerPackageSetting;
14536            if (installerPackageName != null) {
14537                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14538                if (installerPackageSetting == null) {
14539                    throw new IllegalArgumentException("Unknown installer package: "
14540                            + installerPackageName);
14541                }
14542            } else {
14543                installerPackageSetting = null;
14544            }
14545
14546            Signature[] callerSignature;
14547            Object obj = mSettings.getUserIdLPr(callingUid);
14548            if (obj != null) {
14549                if (obj instanceof SharedUserSetting) {
14550                    callerSignature =
14551                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14552                } else if (obj instanceof PackageSetting) {
14553                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14554                } else {
14555                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14556                }
14557            } else {
14558                throw new SecurityException("Unknown calling UID: " + callingUid);
14559            }
14560
14561            // Verify: can't set installerPackageName to a package that is
14562            // not signed with the same cert as the caller.
14563            if (installerPackageSetting != null) {
14564                if (compareSignatures(callerSignature,
14565                        installerPackageSetting.signatures.mSigningDetails.signatures)
14566                        != PackageManager.SIGNATURE_MATCH) {
14567                    throw new SecurityException(
14568                            "Caller does not have same cert as new installer package "
14569                            + installerPackageName);
14570                }
14571            }
14572
14573            // Verify: if target already has an installer package, it must
14574            // be signed with the same cert as the caller.
14575            if (targetPackageSetting.installerPackageName != null) {
14576                PackageSetting setting = mSettings.mPackages.get(
14577                        targetPackageSetting.installerPackageName);
14578                // If the currently set package isn't valid, then it's always
14579                // okay to change it.
14580                if (setting != null) {
14581                    if (compareSignatures(callerSignature,
14582                            setting.signatures.mSigningDetails.signatures)
14583                            != PackageManager.SIGNATURE_MATCH) {
14584                        throw new SecurityException(
14585                                "Caller does not have same cert as old installer package "
14586                                + targetPackageSetting.installerPackageName);
14587                    }
14588                }
14589            }
14590
14591            // Okay!
14592            targetPackageSetting.installerPackageName = installerPackageName;
14593            if (installerPackageName != null) {
14594                mSettings.mInstallerPackages.add(installerPackageName);
14595            }
14596            scheduleWriteSettingsLocked();
14597        }
14598    }
14599
14600    @Override
14601    public void setApplicationCategoryHint(String packageName, int categoryHint,
14602            String callerPackageName) {
14603        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14604            throw new SecurityException("Instant applications don't have access to this method");
14605        }
14606        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14607                callerPackageName);
14608        synchronized (mPackages) {
14609            PackageSetting ps = mSettings.mPackages.get(packageName);
14610            if (ps == null) {
14611                throw new IllegalArgumentException("Unknown target package " + packageName);
14612            }
14613            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14614                throw new IllegalArgumentException("Unknown target package " + packageName);
14615            }
14616            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14617                throw new IllegalArgumentException("Calling package " + callerPackageName
14618                        + " is not installer for " + packageName);
14619            }
14620
14621            if (ps.categoryHint != categoryHint) {
14622                ps.categoryHint = categoryHint;
14623                scheduleWriteSettingsLocked();
14624            }
14625        }
14626    }
14627
14628    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14629        // Queue up an async operation since the package installation may take a little while.
14630        mHandler.post(new Runnable() {
14631            public void run() {
14632                mHandler.removeCallbacks(this);
14633                 // Result object to be returned
14634                PackageInstalledInfo res = new PackageInstalledInfo();
14635                res.setReturnCode(currentStatus);
14636                res.uid = -1;
14637                res.pkg = null;
14638                res.removedInfo = null;
14639                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14640                    args.doPreInstall(res.returnCode);
14641                    synchronized (mInstallLock) {
14642                        installPackageTracedLI(args, res);
14643                    }
14644                    args.doPostInstall(res.returnCode, res.uid);
14645                }
14646
14647                // A restore should be performed at this point if (a) the install
14648                // succeeded, (b) the operation is not an update, and (c) the new
14649                // package has not opted out of backup participation.
14650                final boolean update = res.removedInfo != null
14651                        && res.removedInfo.removedPackage != null;
14652                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14653                boolean doRestore = !update
14654                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14655
14656                // Set up the post-install work request bookkeeping.  This will be used
14657                // and cleaned up by the post-install event handling regardless of whether
14658                // there's a restore pass performed.  Token values are >= 1.
14659                int token;
14660                if (mNextInstallToken < 0) mNextInstallToken = 1;
14661                token = mNextInstallToken++;
14662
14663                PostInstallData data = new PostInstallData(args, res);
14664                mRunningInstalls.put(token, data);
14665                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14666
14667                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14668                    // Pass responsibility to the Backup Manager.  It will perform a
14669                    // restore if appropriate, then pass responsibility back to the
14670                    // Package Manager to run the post-install observer callbacks
14671                    // and broadcasts.
14672                    IBackupManager bm = IBackupManager.Stub.asInterface(
14673                            ServiceManager.getService(Context.BACKUP_SERVICE));
14674                    if (bm != null) {
14675                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14676                                + " to BM for possible restore");
14677                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14678                        try {
14679                            // TODO: http://b/22388012
14680                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14681                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14682                            } else {
14683                                doRestore = false;
14684                            }
14685                        } catch (RemoteException e) {
14686                            // can't happen; the backup manager is local
14687                        } catch (Exception e) {
14688                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14689                            doRestore = false;
14690                        }
14691                    } else {
14692                        Slog.e(TAG, "Backup Manager not found!");
14693                        doRestore = false;
14694                    }
14695                }
14696
14697                if (!doRestore) {
14698                    // No restore possible, or the Backup Manager was mysteriously not
14699                    // available -- just fire the post-install work request directly.
14700                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14701
14702                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14703
14704                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14705                    mHandler.sendMessage(msg);
14706                }
14707            }
14708        });
14709    }
14710
14711    /**
14712     * Callback from PackageSettings whenever an app is first transitioned out of the
14713     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14714     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14715     * here whether the app is the target of an ongoing install, and only send the
14716     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14717     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14718     * handling.
14719     */
14720    void notifyFirstLaunch(final String packageName, final String installerPackage,
14721            final int userId) {
14722        // Serialize this with the rest of the install-process message chain.  In the
14723        // restore-at-install case, this Runnable will necessarily run before the
14724        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14725        // are coherent.  In the non-restore case, the app has already completed install
14726        // and been launched through some other means, so it is not in a problematic
14727        // state for observers to see the FIRST_LAUNCH signal.
14728        mHandler.post(new Runnable() {
14729            @Override
14730            public void run() {
14731                for (int i = 0; i < mRunningInstalls.size(); i++) {
14732                    final PostInstallData data = mRunningInstalls.valueAt(i);
14733                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14734                        continue;
14735                    }
14736                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14737                        // right package; but is it for the right user?
14738                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14739                            if (userId == data.res.newUsers[uIndex]) {
14740                                if (DEBUG_BACKUP) {
14741                                    Slog.i(TAG, "Package " + packageName
14742                                            + " being restored so deferring FIRST_LAUNCH");
14743                                }
14744                                return;
14745                            }
14746                        }
14747                    }
14748                }
14749                // didn't find it, so not being restored
14750                if (DEBUG_BACKUP) {
14751                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14752                }
14753                final boolean isInstantApp = isInstantApp(packageName, userId);
14754                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14755                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14756                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14757            }
14758        });
14759    }
14760
14761    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14762            int[] userIds, int[] instantUserIds) {
14763        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14764                installerPkg, null, userIds, instantUserIds);
14765    }
14766
14767    private abstract class HandlerParams {
14768        private static final int MAX_RETRIES = 4;
14769
14770        /**
14771         * Number of times startCopy() has been attempted and had a non-fatal
14772         * error.
14773         */
14774        private int mRetries = 0;
14775
14776        /** User handle for the user requesting the information or installation. */
14777        private final UserHandle mUser;
14778        String traceMethod;
14779        int traceCookie;
14780
14781        HandlerParams(UserHandle user) {
14782            mUser = user;
14783        }
14784
14785        UserHandle getUser() {
14786            return mUser;
14787        }
14788
14789        HandlerParams setTraceMethod(String traceMethod) {
14790            this.traceMethod = traceMethod;
14791            return this;
14792        }
14793
14794        HandlerParams setTraceCookie(int traceCookie) {
14795            this.traceCookie = traceCookie;
14796            return this;
14797        }
14798
14799        final boolean startCopy() {
14800            boolean res;
14801            try {
14802                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14803
14804                if (++mRetries > MAX_RETRIES) {
14805                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14806                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14807                    handleServiceError();
14808                    return false;
14809                } else {
14810                    handleStartCopy();
14811                    res = true;
14812                }
14813            } catch (RemoteException e) {
14814                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14815                mHandler.sendEmptyMessage(MCS_RECONNECT);
14816                res = false;
14817            }
14818            handleReturnCode();
14819            return res;
14820        }
14821
14822        final void serviceError() {
14823            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14824            handleServiceError();
14825            handleReturnCode();
14826        }
14827
14828        abstract void handleStartCopy() throws RemoteException;
14829        abstract void handleServiceError();
14830        abstract void handleReturnCode();
14831    }
14832
14833    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14834        for (File path : paths) {
14835            try {
14836                mcs.clearDirectory(path.getAbsolutePath());
14837            } catch (RemoteException e) {
14838            }
14839        }
14840    }
14841
14842    static class OriginInfo {
14843        /**
14844         * Location where install is coming from, before it has been
14845         * copied/renamed into place. This could be a single monolithic APK
14846         * file, or a cluster directory. This location may be untrusted.
14847         */
14848        final File file;
14849
14850        /**
14851         * Flag indicating that {@link #file} or {@link #cid} has already been
14852         * staged, meaning downstream users don't need to defensively copy the
14853         * contents.
14854         */
14855        final boolean staged;
14856
14857        /**
14858         * Flag indicating that {@link #file} or {@link #cid} is an already
14859         * installed app that is being moved.
14860         */
14861        final boolean existing;
14862
14863        final String resolvedPath;
14864        final File resolvedFile;
14865
14866        static OriginInfo fromNothing() {
14867            return new OriginInfo(null, false, false);
14868        }
14869
14870        static OriginInfo fromUntrustedFile(File file) {
14871            return new OriginInfo(file, false, false);
14872        }
14873
14874        static OriginInfo fromExistingFile(File file) {
14875            return new OriginInfo(file, false, true);
14876        }
14877
14878        static OriginInfo fromStagedFile(File file) {
14879            return new OriginInfo(file, true, false);
14880        }
14881
14882        private OriginInfo(File file, boolean staged, boolean existing) {
14883            this.file = file;
14884            this.staged = staged;
14885            this.existing = existing;
14886
14887            if (file != null) {
14888                resolvedPath = file.getAbsolutePath();
14889                resolvedFile = file;
14890            } else {
14891                resolvedPath = null;
14892                resolvedFile = null;
14893            }
14894        }
14895    }
14896
14897    static class MoveInfo {
14898        final int moveId;
14899        final String fromUuid;
14900        final String toUuid;
14901        final String packageName;
14902        final String dataAppName;
14903        final int appId;
14904        final String seinfo;
14905        final int targetSdkVersion;
14906
14907        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14908                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14909            this.moveId = moveId;
14910            this.fromUuid = fromUuid;
14911            this.toUuid = toUuid;
14912            this.packageName = packageName;
14913            this.dataAppName = dataAppName;
14914            this.appId = appId;
14915            this.seinfo = seinfo;
14916            this.targetSdkVersion = targetSdkVersion;
14917        }
14918    }
14919
14920    static class VerificationInfo {
14921        /** A constant used to indicate that a uid value is not present. */
14922        public static final int NO_UID = -1;
14923
14924        /** URI referencing where the package was downloaded from. */
14925        final Uri originatingUri;
14926
14927        /** HTTP referrer URI associated with the originatingURI. */
14928        final Uri referrer;
14929
14930        /** UID of the application that the install request originated from. */
14931        final int originatingUid;
14932
14933        /** UID of application requesting the install */
14934        final int installerUid;
14935
14936        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14937            this.originatingUri = originatingUri;
14938            this.referrer = referrer;
14939            this.originatingUid = originatingUid;
14940            this.installerUid = installerUid;
14941        }
14942    }
14943
14944    class InstallParams extends HandlerParams {
14945        final OriginInfo origin;
14946        final MoveInfo move;
14947        final IPackageInstallObserver2 observer;
14948        int installFlags;
14949        final String installerPackageName;
14950        final String volumeUuid;
14951        private InstallArgs mArgs;
14952        private int mRet;
14953        final String packageAbiOverride;
14954        final String[] grantedRuntimePermissions;
14955        final VerificationInfo verificationInfo;
14956        final PackageParser.SigningDetails signingDetails;
14957        final int installReason;
14958
14959        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14960                int installFlags, String installerPackageName, String volumeUuid,
14961                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14962                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14963            super(user);
14964            this.origin = origin;
14965            this.move = move;
14966            this.observer = observer;
14967            this.installFlags = installFlags;
14968            this.installerPackageName = installerPackageName;
14969            this.volumeUuid = volumeUuid;
14970            this.verificationInfo = verificationInfo;
14971            this.packageAbiOverride = packageAbiOverride;
14972            this.grantedRuntimePermissions = grantedPermissions;
14973            this.signingDetails = signingDetails;
14974            this.installReason = installReason;
14975        }
14976
14977        @Override
14978        public String toString() {
14979            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14980                    + " file=" + origin.file + "}";
14981        }
14982
14983        private int installLocationPolicy(PackageInfoLite pkgLite) {
14984            String packageName = pkgLite.packageName;
14985            int installLocation = pkgLite.installLocation;
14986            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14987            // reader
14988            synchronized (mPackages) {
14989                // Currently installed package which the new package is attempting to replace or
14990                // null if no such package is installed.
14991                PackageParser.Package installedPkg = mPackages.get(packageName);
14992                // Package which currently owns the data which the new package will own if installed.
14993                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14994                // will be null whereas dataOwnerPkg will contain information about the package
14995                // which was uninstalled while keeping its data.
14996                PackageParser.Package dataOwnerPkg = installedPkg;
14997                if (dataOwnerPkg  == null) {
14998                    PackageSetting ps = mSettings.mPackages.get(packageName);
14999                    if (ps != null) {
15000                        dataOwnerPkg = ps.pkg;
15001                    }
15002                }
15003
15004                if (dataOwnerPkg != null) {
15005                    // If installed, the package will get access to data left on the device by its
15006                    // predecessor. As a security measure, this is permited only if this is not a
15007                    // version downgrade or if the predecessor package is marked as debuggable and
15008                    // a downgrade is explicitly requested.
15009                    //
15010                    // On debuggable platform builds, downgrades are permitted even for
15011                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15012                    // not offer security guarantees and thus it's OK to disable some security
15013                    // mechanisms to make debugging/testing easier on those builds. However, even on
15014                    // debuggable builds downgrades of packages are permitted only if requested via
15015                    // installFlags. This is because we aim to keep the behavior of debuggable
15016                    // platform builds as close as possible to the behavior of non-debuggable
15017                    // platform builds.
15018                    final boolean downgradeRequested =
15019                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15020                    final boolean packageDebuggable =
15021                                (dataOwnerPkg.applicationInfo.flags
15022                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15023                    final boolean downgradePermitted =
15024                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15025                    if (!downgradePermitted) {
15026                        try {
15027                            checkDowngrade(dataOwnerPkg, pkgLite);
15028                        } catch (PackageManagerException e) {
15029                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15030                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15031                        }
15032                    }
15033                }
15034
15035                if (installedPkg != null) {
15036                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15037                        // Check for updated system application.
15038                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15039                            if (onSd) {
15040                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15041                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15042                            }
15043                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15044                        } else {
15045                            if (onSd) {
15046                                // Install flag overrides everything.
15047                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15048                            }
15049                            // If current upgrade specifies particular preference
15050                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15051                                // Application explicitly specified internal.
15052                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15053                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15054                                // App explictly prefers external. Let policy decide
15055                            } else {
15056                                // Prefer previous location
15057                                if (isExternal(installedPkg)) {
15058                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15059                                }
15060                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15061                            }
15062                        }
15063                    } else {
15064                        // Invalid install. Return error code
15065                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15066                    }
15067                }
15068            }
15069            // All the special cases have been taken care of.
15070            // Return result based on recommended install location.
15071            if (onSd) {
15072                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15073            }
15074            return pkgLite.recommendedInstallLocation;
15075        }
15076
15077        /*
15078         * Invoke remote method to get package information and install
15079         * location values. Override install location based on default
15080         * policy if needed and then create install arguments based
15081         * on the install location.
15082         */
15083        public void handleStartCopy() throws RemoteException {
15084            int ret = PackageManager.INSTALL_SUCCEEDED;
15085
15086            // If we're already staged, we've firmly committed to an install location
15087            if (origin.staged) {
15088                if (origin.file != null) {
15089                    installFlags |= PackageManager.INSTALL_INTERNAL;
15090                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15091                } else {
15092                    throw new IllegalStateException("Invalid stage location");
15093                }
15094            }
15095
15096            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15097            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15098            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15099            PackageInfoLite pkgLite = null;
15100
15101            if (onInt && onSd) {
15102                // Check if both bits are set.
15103                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15104                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15105            } else if (onSd && ephemeral) {
15106                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15107                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15108            } else {
15109                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15110                        packageAbiOverride);
15111
15112                if (DEBUG_EPHEMERAL && ephemeral) {
15113                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15114                }
15115
15116                /*
15117                 * If we have too little free space, try to free cache
15118                 * before giving up.
15119                 */
15120                if (!origin.staged && pkgLite.recommendedInstallLocation
15121                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15122                    // TODO: focus freeing disk space on the target device
15123                    final StorageManager storage = StorageManager.from(mContext);
15124                    final long lowThreshold = storage.getStorageLowBytes(
15125                            Environment.getDataDirectory());
15126
15127                    final long sizeBytes = mContainerService.calculateInstalledSize(
15128                            origin.resolvedPath, packageAbiOverride);
15129
15130                    try {
15131                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15132                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15133                                installFlags, packageAbiOverride);
15134                    } catch (InstallerException e) {
15135                        Slog.w(TAG, "Failed to free cache", e);
15136                    }
15137
15138                    /*
15139                     * The cache free must have deleted the file we
15140                     * downloaded to install.
15141                     *
15142                     * TODO: fix the "freeCache" call to not delete
15143                     *       the file we care about.
15144                     */
15145                    if (pkgLite.recommendedInstallLocation
15146                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15147                        pkgLite.recommendedInstallLocation
15148                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15149                    }
15150                }
15151            }
15152
15153            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15154                int loc = pkgLite.recommendedInstallLocation;
15155                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15156                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15157                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15158                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15159                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15160                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15161                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15162                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15163                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15164                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15165                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15166                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15167                } else {
15168                    // Override with defaults if needed.
15169                    loc = installLocationPolicy(pkgLite);
15170                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15171                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15172                    } else if (!onSd && !onInt) {
15173                        // Override install location with flags
15174                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15175                            // Set the flag to install on external media.
15176                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15177                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15178                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15179                            if (DEBUG_EPHEMERAL) {
15180                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15181                            }
15182                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15183                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15184                                    |PackageManager.INSTALL_INTERNAL);
15185                        } else {
15186                            // Make sure the flag for installing on external
15187                            // media is unset
15188                            installFlags |= PackageManager.INSTALL_INTERNAL;
15189                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15190                        }
15191                    }
15192                }
15193            }
15194
15195            final InstallArgs args = createInstallArgs(this);
15196            mArgs = args;
15197
15198            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15199                // TODO: http://b/22976637
15200                // Apps installed for "all" users use the device owner to verify the app
15201                UserHandle verifierUser = getUser();
15202                if (verifierUser == UserHandle.ALL) {
15203                    verifierUser = UserHandle.SYSTEM;
15204                }
15205
15206                /*
15207                 * Determine if we have any installed package verifiers. If we
15208                 * do, then we'll defer to them to verify the packages.
15209                 */
15210                final int requiredUid = mRequiredVerifierPackage == null ? -1
15211                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15212                                verifierUser.getIdentifier());
15213                final int installerUid =
15214                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15215                if (!origin.existing && requiredUid != -1
15216                        && isVerificationEnabled(
15217                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15218                    final Intent verification = new Intent(
15219                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15220                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15221                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15222                            PACKAGE_MIME_TYPE);
15223                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15224
15225                    // Query all live verifiers based on current user state
15226                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15227                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15228                            false /*allowDynamicSplits*/);
15229
15230                    if (DEBUG_VERIFY) {
15231                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15232                                + verification.toString() + " with " + pkgLite.verifiers.length
15233                                + " optional verifiers");
15234                    }
15235
15236                    final int verificationId = mPendingVerificationToken++;
15237
15238                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15239
15240                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15241                            installerPackageName);
15242
15243                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15244                            installFlags);
15245
15246                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15247                            pkgLite.packageName);
15248
15249                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15250                            pkgLite.versionCode);
15251
15252                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15253                            pkgLite.getLongVersionCode());
15254
15255                    if (verificationInfo != null) {
15256                        if (verificationInfo.originatingUri != null) {
15257                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15258                                    verificationInfo.originatingUri);
15259                        }
15260                        if (verificationInfo.referrer != null) {
15261                            verification.putExtra(Intent.EXTRA_REFERRER,
15262                                    verificationInfo.referrer);
15263                        }
15264                        if (verificationInfo.originatingUid >= 0) {
15265                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15266                                    verificationInfo.originatingUid);
15267                        }
15268                        if (verificationInfo.installerUid >= 0) {
15269                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15270                                    verificationInfo.installerUid);
15271                        }
15272                    }
15273
15274                    final PackageVerificationState verificationState = new PackageVerificationState(
15275                            requiredUid, args);
15276
15277                    mPendingVerification.append(verificationId, verificationState);
15278
15279                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15280                            receivers, verificationState);
15281
15282                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15283                    final long idleDuration = getVerificationTimeout();
15284
15285                    /*
15286                     * If any sufficient verifiers were listed in the package
15287                     * manifest, attempt to ask them.
15288                     */
15289                    if (sufficientVerifiers != null) {
15290                        final int N = sufficientVerifiers.size();
15291                        if (N == 0) {
15292                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15293                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15294                        } else {
15295                            for (int i = 0; i < N; i++) {
15296                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15297                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15298                                        verifierComponent.getPackageName(), idleDuration,
15299                                        verifierUser.getIdentifier(), false, "package verifier");
15300
15301                                final Intent sufficientIntent = new Intent(verification);
15302                                sufficientIntent.setComponent(verifierComponent);
15303                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15304                            }
15305                        }
15306                    }
15307
15308                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15309                            mRequiredVerifierPackage, receivers);
15310                    if (ret == PackageManager.INSTALL_SUCCEEDED
15311                            && mRequiredVerifierPackage != null) {
15312                        Trace.asyncTraceBegin(
15313                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15314                        /*
15315                         * Send the intent to the required verification agent,
15316                         * but only start the verification timeout after the
15317                         * target BroadcastReceivers have run.
15318                         */
15319                        verification.setComponent(requiredVerifierComponent);
15320                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15321                                mRequiredVerifierPackage, idleDuration,
15322                                verifierUser.getIdentifier(), false, "package verifier");
15323                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15324                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15325                                new BroadcastReceiver() {
15326                                    @Override
15327                                    public void onReceive(Context context, Intent intent) {
15328                                        final Message msg = mHandler
15329                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15330                                        msg.arg1 = verificationId;
15331                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15332                                    }
15333                                }, null, 0, null, null);
15334
15335                        /*
15336                         * We don't want the copy to proceed until verification
15337                         * succeeds, so null out this field.
15338                         */
15339                        mArgs = null;
15340                    }
15341                } else {
15342                    /*
15343                     * No package verification is enabled, so immediately start
15344                     * the remote call to initiate copy using temporary file.
15345                     */
15346                    ret = args.copyApk(mContainerService, true);
15347                }
15348            }
15349
15350            mRet = ret;
15351        }
15352
15353        @Override
15354        void handleReturnCode() {
15355            // If mArgs is null, then MCS couldn't be reached. When it
15356            // reconnects, it will try again to install. At that point, this
15357            // will succeed.
15358            if (mArgs != null) {
15359                processPendingInstall(mArgs, mRet);
15360            }
15361        }
15362
15363        @Override
15364        void handleServiceError() {
15365            mArgs = createInstallArgs(this);
15366            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15367        }
15368    }
15369
15370    private InstallArgs createInstallArgs(InstallParams params) {
15371        if (params.move != null) {
15372            return new MoveInstallArgs(params);
15373        } else {
15374            return new FileInstallArgs(params);
15375        }
15376    }
15377
15378    /**
15379     * Create args that describe an existing installed package. Typically used
15380     * when cleaning up old installs, or used as a move source.
15381     */
15382    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15383            String resourcePath, String[] instructionSets) {
15384        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15385    }
15386
15387    static abstract class InstallArgs {
15388        /** @see InstallParams#origin */
15389        final OriginInfo origin;
15390        /** @see InstallParams#move */
15391        final MoveInfo move;
15392
15393        final IPackageInstallObserver2 observer;
15394        // Always refers to PackageManager flags only
15395        final int installFlags;
15396        final String installerPackageName;
15397        final String volumeUuid;
15398        final UserHandle user;
15399        final String abiOverride;
15400        final String[] installGrantPermissions;
15401        /** If non-null, drop an async trace when the install completes */
15402        final String traceMethod;
15403        final int traceCookie;
15404        final PackageParser.SigningDetails signingDetails;
15405        final int installReason;
15406
15407        // The list of instruction sets supported by this app. This is currently
15408        // only used during the rmdex() phase to clean up resources. We can get rid of this
15409        // if we move dex files under the common app path.
15410        /* nullable */ String[] instructionSets;
15411
15412        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15413                int installFlags, String installerPackageName, String volumeUuid,
15414                UserHandle user, String[] instructionSets,
15415                String abiOverride, String[] installGrantPermissions,
15416                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15417                int installReason) {
15418            this.origin = origin;
15419            this.move = move;
15420            this.installFlags = installFlags;
15421            this.observer = observer;
15422            this.installerPackageName = installerPackageName;
15423            this.volumeUuid = volumeUuid;
15424            this.user = user;
15425            this.instructionSets = instructionSets;
15426            this.abiOverride = abiOverride;
15427            this.installGrantPermissions = installGrantPermissions;
15428            this.traceMethod = traceMethod;
15429            this.traceCookie = traceCookie;
15430            this.signingDetails = signingDetails;
15431            this.installReason = installReason;
15432        }
15433
15434        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15435        abstract int doPreInstall(int status);
15436
15437        /**
15438         * Rename package into final resting place. All paths on the given
15439         * scanned package should be updated to reflect the rename.
15440         */
15441        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15442        abstract int doPostInstall(int status, int uid);
15443
15444        /** @see PackageSettingBase#codePathString */
15445        abstract String getCodePath();
15446        /** @see PackageSettingBase#resourcePathString */
15447        abstract String getResourcePath();
15448
15449        // Need installer lock especially for dex file removal.
15450        abstract void cleanUpResourcesLI();
15451        abstract boolean doPostDeleteLI(boolean delete);
15452
15453        /**
15454         * Called before the source arguments are copied. This is used mostly
15455         * for MoveParams when it needs to read the source file to put it in the
15456         * destination.
15457         */
15458        int doPreCopy() {
15459            return PackageManager.INSTALL_SUCCEEDED;
15460        }
15461
15462        /**
15463         * Called after the source arguments are copied. This is used mostly for
15464         * MoveParams when it needs to read the source file to put it in the
15465         * destination.
15466         */
15467        int doPostCopy(int uid) {
15468            return PackageManager.INSTALL_SUCCEEDED;
15469        }
15470
15471        protected boolean isFwdLocked() {
15472            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15473        }
15474
15475        protected boolean isExternalAsec() {
15476            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15477        }
15478
15479        protected boolean isEphemeral() {
15480            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15481        }
15482
15483        UserHandle getUser() {
15484            return user;
15485        }
15486    }
15487
15488    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15489        if (!allCodePaths.isEmpty()) {
15490            if (instructionSets == null) {
15491                throw new IllegalStateException("instructionSet == null");
15492            }
15493            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15494            for (String codePath : allCodePaths) {
15495                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15496                    try {
15497                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15498                    } catch (InstallerException ignored) {
15499                    }
15500                }
15501            }
15502        }
15503    }
15504
15505    /**
15506     * Logic to handle installation of non-ASEC applications, including copying
15507     * and renaming logic.
15508     */
15509    class FileInstallArgs extends InstallArgs {
15510        private File codeFile;
15511        private File resourceFile;
15512
15513        // Example topology:
15514        // /data/app/com.example/base.apk
15515        // /data/app/com.example/split_foo.apk
15516        // /data/app/com.example/lib/arm/libfoo.so
15517        // /data/app/com.example/lib/arm64/libfoo.so
15518        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15519
15520        /** New install */
15521        FileInstallArgs(InstallParams params) {
15522            super(params.origin, params.move, params.observer, params.installFlags,
15523                    params.installerPackageName, params.volumeUuid,
15524                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15525                    params.grantedRuntimePermissions,
15526                    params.traceMethod, params.traceCookie, params.signingDetails,
15527                    params.installReason);
15528            if (isFwdLocked()) {
15529                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15530            }
15531        }
15532
15533        /** Existing install */
15534        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15535            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15536                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15537                    PackageManager.INSTALL_REASON_UNKNOWN);
15538            this.codeFile = (codePath != null) ? new File(codePath) : null;
15539            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15540        }
15541
15542        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15543            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15544            try {
15545                return doCopyApk(imcs, temp);
15546            } finally {
15547                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15548            }
15549        }
15550
15551        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15552            if (origin.staged) {
15553                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15554                codeFile = origin.file;
15555                resourceFile = origin.file;
15556                return PackageManager.INSTALL_SUCCEEDED;
15557            }
15558
15559            try {
15560                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15561                final File tempDir =
15562                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15563                codeFile = tempDir;
15564                resourceFile = tempDir;
15565            } catch (IOException e) {
15566                Slog.w(TAG, "Failed to create copy file: " + e);
15567                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15568            }
15569
15570            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15571                @Override
15572                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15573                    if (!FileUtils.isValidExtFilename(name)) {
15574                        throw new IllegalArgumentException("Invalid filename: " + name);
15575                    }
15576                    try {
15577                        final File file = new File(codeFile, name);
15578                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15579                                O_RDWR | O_CREAT, 0644);
15580                        Os.chmod(file.getAbsolutePath(), 0644);
15581                        return new ParcelFileDescriptor(fd);
15582                    } catch (ErrnoException e) {
15583                        throw new RemoteException("Failed to open: " + e.getMessage());
15584                    }
15585                }
15586            };
15587
15588            int ret = PackageManager.INSTALL_SUCCEEDED;
15589            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15590            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15591                Slog.e(TAG, "Failed to copy package");
15592                return ret;
15593            }
15594
15595            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15596            NativeLibraryHelper.Handle handle = null;
15597            try {
15598                handle = NativeLibraryHelper.Handle.create(codeFile);
15599                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15600                        abiOverride);
15601            } catch (IOException e) {
15602                Slog.e(TAG, "Copying native libraries failed", e);
15603                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15604            } finally {
15605                IoUtils.closeQuietly(handle);
15606            }
15607
15608            return ret;
15609        }
15610
15611        int doPreInstall(int status) {
15612            if (status != PackageManager.INSTALL_SUCCEEDED) {
15613                cleanUp();
15614            }
15615            return status;
15616        }
15617
15618        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15619            if (status != PackageManager.INSTALL_SUCCEEDED) {
15620                cleanUp();
15621                return false;
15622            }
15623
15624            final File targetDir = codeFile.getParentFile();
15625            final File beforeCodeFile = codeFile;
15626            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15627
15628            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15629            try {
15630                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15631            } catch (ErrnoException e) {
15632                Slog.w(TAG, "Failed to rename", e);
15633                return false;
15634            }
15635
15636            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15637                Slog.w(TAG, "Failed to restorecon");
15638                return false;
15639            }
15640
15641            // Reflect the rename internally
15642            codeFile = afterCodeFile;
15643            resourceFile = afterCodeFile;
15644
15645            // Reflect the rename in scanned details
15646            try {
15647                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15648            } catch (IOException e) {
15649                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15650                return false;
15651            }
15652            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15653                    afterCodeFile, pkg.baseCodePath));
15654            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15655                    afterCodeFile, pkg.splitCodePaths));
15656
15657            // Reflect the rename in app info
15658            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15659            pkg.setApplicationInfoCodePath(pkg.codePath);
15660            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15661            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15662            pkg.setApplicationInfoResourcePath(pkg.codePath);
15663            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15664            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15665
15666            return true;
15667        }
15668
15669        int doPostInstall(int status, int uid) {
15670            if (status != PackageManager.INSTALL_SUCCEEDED) {
15671                cleanUp();
15672            }
15673            return status;
15674        }
15675
15676        @Override
15677        String getCodePath() {
15678            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15679        }
15680
15681        @Override
15682        String getResourcePath() {
15683            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15684        }
15685
15686        private boolean cleanUp() {
15687            if (codeFile == null || !codeFile.exists()) {
15688                return false;
15689            }
15690
15691            removeCodePathLI(codeFile);
15692
15693            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15694                resourceFile.delete();
15695            }
15696
15697            return true;
15698        }
15699
15700        void cleanUpResourcesLI() {
15701            // Try enumerating all code paths before deleting
15702            List<String> allCodePaths = Collections.EMPTY_LIST;
15703            if (codeFile != null && codeFile.exists()) {
15704                try {
15705                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15706                    allCodePaths = pkg.getAllCodePaths();
15707                } catch (PackageParserException e) {
15708                    // Ignored; we tried our best
15709                }
15710            }
15711
15712            cleanUp();
15713            removeDexFiles(allCodePaths, instructionSets);
15714        }
15715
15716        boolean doPostDeleteLI(boolean delete) {
15717            // XXX err, shouldn't we respect the delete flag?
15718            cleanUpResourcesLI();
15719            return true;
15720        }
15721    }
15722
15723    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15724            PackageManagerException {
15725        if (copyRet < 0) {
15726            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15727                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15728                throw new PackageManagerException(copyRet, message);
15729            }
15730        }
15731    }
15732
15733    /**
15734     * Extract the StorageManagerService "container ID" from the full code path of an
15735     * .apk.
15736     */
15737    static String cidFromCodePath(String fullCodePath) {
15738        int eidx = fullCodePath.lastIndexOf("/");
15739        String subStr1 = fullCodePath.substring(0, eidx);
15740        int sidx = subStr1.lastIndexOf("/");
15741        return subStr1.substring(sidx+1, eidx);
15742    }
15743
15744    /**
15745     * Logic to handle movement of existing installed applications.
15746     */
15747    class MoveInstallArgs extends InstallArgs {
15748        private File codeFile;
15749        private File resourceFile;
15750
15751        /** New install */
15752        MoveInstallArgs(InstallParams params) {
15753            super(params.origin, params.move, params.observer, params.installFlags,
15754                    params.installerPackageName, params.volumeUuid,
15755                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15756                    params.grantedRuntimePermissions,
15757                    params.traceMethod, params.traceCookie, params.signingDetails,
15758                    params.installReason);
15759        }
15760
15761        int copyApk(IMediaContainerService imcs, boolean temp) {
15762            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15763                    + move.fromUuid + " to " + move.toUuid);
15764            synchronized (mInstaller) {
15765                try {
15766                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15767                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15768                } catch (InstallerException e) {
15769                    Slog.w(TAG, "Failed to move app", e);
15770                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15771                }
15772            }
15773
15774            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15775            resourceFile = codeFile;
15776            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15777
15778            return PackageManager.INSTALL_SUCCEEDED;
15779        }
15780
15781        int doPreInstall(int status) {
15782            if (status != PackageManager.INSTALL_SUCCEEDED) {
15783                cleanUp(move.toUuid);
15784            }
15785            return status;
15786        }
15787
15788        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15789            if (status != PackageManager.INSTALL_SUCCEEDED) {
15790                cleanUp(move.toUuid);
15791                return false;
15792            }
15793
15794            // Reflect the move in app info
15795            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15796            pkg.setApplicationInfoCodePath(pkg.codePath);
15797            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15798            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15799            pkg.setApplicationInfoResourcePath(pkg.codePath);
15800            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15801            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15802
15803            return true;
15804        }
15805
15806        int doPostInstall(int status, int uid) {
15807            if (status == PackageManager.INSTALL_SUCCEEDED) {
15808                cleanUp(move.fromUuid);
15809            } else {
15810                cleanUp(move.toUuid);
15811            }
15812            return status;
15813        }
15814
15815        @Override
15816        String getCodePath() {
15817            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15818        }
15819
15820        @Override
15821        String getResourcePath() {
15822            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15823        }
15824
15825        private boolean cleanUp(String volumeUuid) {
15826            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15827                    move.dataAppName);
15828            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15829            final int[] userIds = sUserManager.getUserIds();
15830            synchronized (mInstallLock) {
15831                // Clean up both app data and code
15832                // All package moves are frozen until finished
15833                for (int userId : userIds) {
15834                    try {
15835                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15836                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15837                    } catch (InstallerException e) {
15838                        Slog.w(TAG, String.valueOf(e));
15839                    }
15840                }
15841                removeCodePathLI(codeFile);
15842            }
15843            return true;
15844        }
15845
15846        void cleanUpResourcesLI() {
15847            throw new UnsupportedOperationException();
15848        }
15849
15850        boolean doPostDeleteLI(boolean delete) {
15851            throw new UnsupportedOperationException();
15852        }
15853    }
15854
15855    static String getAsecPackageName(String packageCid) {
15856        int idx = packageCid.lastIndexOf("-");
15857        if (idx == -1) {
15858            return packageCid;
15859        }
15860        return packageCid.substring(0, idx);
15861    }
15862
15863    // Utility method used to create code paths based on package name and available index.
15864    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15865        String idxStr = "";
15866        int idx = 1;
15867        // Fall back to default value of idx=1 if prefix is not
15868        // part of oldCodePath
15869        if (oldCodePath != null) {
15870            String subStr = oldCodePath;
15871            // Drop the suffix right away
15872            if (suffix != null && subStr.endsWith(suffix)) {
15873                subStr = subStr.substring(0, subStr.length() - suffix.length());
15874            }
15875            // If oldCodePath already contains prefix find out the
15876            // ending index to either increment or decrement.
15877            int sidx = subStr.lastIndexOf(prefix);
15878            if (sidx != -1) {
15879                subStr = subStr.substring(sidx + prefix.length());
15880                if (subStr != null) {
15881                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15882                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15883                    }
15884                    try {
15885                        idx = Integer.parseInt(subStr);
15886                        if (idx <= 1) {
15887                            idx++;
15888                        } else {
15889                            idx--;
15890                        }
15891                    } catch(NumberFormatException e) {
15892                    }
15893                }
15894            }
15895        }
15896        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15897        return prefix + idxStr;
15898    }
15899
15900    private File getNextCodePath(File targetDir, String packageName) {
15901        File result;
15902        SecureRandom random = new SecureRandom();
15903        byte[] bytes = new byte[16];
15904        do {
15905            random.nextBytes(bytes);
15906            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15907            result = new File(targetDir, packageName + "-" + suffix);
15908        } while (result.exists());
15909        return result;
15910    }
15911
15912    // Utility method that returns the relative package path with respect
15913    // to the installation directory. Like say for /data/data/com.test-1.apk
15914    // string com.test-1 is returned.
15915    static String deriveCodePathName(String codePath) {
15916        if (codePath == null) {
15917            return null;
15918        }
15919        final File codeFile = new File(codePath);
15920        final String name = codeFile.getName();
15921        if (codeFile.isDirectory()) {
15922            return name;
15923        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15924            final int lastDot = name.lastIndexOf('.');
15925            return name.substring(0, lastDot);
15926        } else {
15927            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15928            return null;
15929        }
15930    }
15931
15932    static class PackageInstalledInfo {
15933        String name;
15934        int uid;
15935        // The set of users that originally had this package installed.
15936        int[] origUsers;
15937        // The set of users that now have this package installed.
15938        int[] newUsers;
15939        PackageParser.Package pkg;
15940        int returnCode;
15941        String returnMsg;
15942        String installerPackageName;
15943        PackageRemovedInfo removedInfo;
15944        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15945
15946        public void setError(int code, String msg) {
15947            setReturnCode(code);
15948            setReturnMessage(msg);
15949            Slog.w(TAG, msg);
15950        }
15951
15952        public void setError(String msg, PackageParserException e) {
15953            setReturnCode(e.error);
15954            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15955            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15956            for (int i = 0; i < childCount; i++) {
15957                addedChildPackages.valueAt(i).setError(msg, e);
15958            }
15959            Slog.w(TAG, msg, e);
15960        }
15961
15962        public void setError(String msg, PackageManagerException e) {
15963            returnCode = e.error;
15964            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15965            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15966            for (int i = 0; i < childCount; i++) {
15967                addedChildPackages.valueAt(i).setError(msg, e);
15968            }
15969            Slog.w(TAG, msg, e);
15970        }
15971
15972        public void setReturnCode(int returnCode) {
15973            this.returnCode = returnCode;
15974            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15975            for (int i = 0; i < childCount; i++) {
15976                addedChildPackages.valueAt(i).returnCode = returnCode;
15977            }
15978        }
15979
15980        private void setReturnMessage(String returnMsg) {
15981            this.returnMsg = returnMsg;
15982            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15983            for (int i = 0; i < childCount; i++) {
15984                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15985            }
15986        }
15987
15988        // In some error cases we want to convey more info back to the observer
15989        String origPackage;
15990        String origPermission;
15991    }
15992
15993    /*
15994     * Install a non-existing package.
15995     */
15996    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15997            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15998            String volumeUuid, PackageInstalledInfo res, int installReason) {
15999        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16000
16001        // Remember this for later, in case we need to rollback this install
16002        String pkgName = pkg.packageName;
16003
16004        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16005
16006        synchronized(mPackages) {
16007            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16008            if (renamedPackage != null) {
16009                // A package with the same name is already installed, though
16010                // it has been renamed to an older name.  The package we
16011                // are trying to install should be installed as an update to
16012                // the existing one, but that has not been requested, so bail.
16013                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16014                        + " without first uninstalling package running as "
16015                        + renamedPackage);
16016                return;
16017            }
16018            if (mPackages.containsKey(pkgName)) {
16019                // Don't allow installation over an existing package with the same name.
16020                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16021                        + " without first uninstalling.");
16022                return;
16023            }
16024        }
16025
16026        try {
16027            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16028                    System.currentTimeMillis(), user);
16029
16030            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16031
16032            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16033                prepareAppDataAfterInstallLIF(newPackage);
16034
16035            } else {
16036                // Remove package from internal structures, but keep around any
16037                // data that might have already existed
16038                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16039                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16040            }
16041        } catch (PackageManagerException e) {
16042            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16043        }
16044
16045        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16046    }
16047
16048    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16049        try (DigestInputStream digestStream =
16050                new DigestInputStream(new FileInputStream(file), digest)) {
16051            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16052        }
16053    }
16054
16055    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16056            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16057            PackageInstalledInfo res, int installReason) {
16058        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16059
16060        final PackageParser.Package oldPackage;
16061        final PackageSetting ps;
16062        final String pkgName = pkg.packageName;
16063        final int[] allUsers;
16064        final int[] installedUsers;
16065
16066        synchronized(mPackages) {
16067            oldPackage = mPackages.get(pkgName);
16068            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16069
16070            // don't allow upgrade to target a release SDK from a pre-release SDK
16071            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16072                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16073            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16074                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16075            if (oldTargetsPreRelease
16076                    && !newTargetsPreRelease
16077                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16078                Slog.w(TAG, "Can't install package targeting released sdk");
16079                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16080                return;
16081            }
16082
16083            ps = mSettings.mPackages.get(pkgName);
16084
16085            // verify signatures are valid
16086            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16087            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16088                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16089                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16090                            "New package not signed by keys specified by upgrade-keysets: "
16091                                    + pkgName);
16092                    return;
16093                }
16094            } else {
16095
16096                // default to original signature matching
16097                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16098                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16099                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16100                            "New package has a different signature: " + pkgName);
16101                    return;
16102                }
16103            }
16104
16105            // don't allow a system upgrade unless the upgrade hash matches
16106            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16107                byte[] digestBytes = null;
16108                try {
16109                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16110                    updateDigest(digest, new File(pkg.baseCodePath));
16111                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16112                        for (String path : pkg.splitCodePaths) {
16113                            updateDigest(digest, new File(path));
16114                        }
16115                    }
16116                    digestBytes = digest.digest();
16117                } catch (NoSuchAlgorithmException | IOException e) {
16118                    res.setError(INSTALL_FAILED_INVALID_APK,
16119                            "Could not compute hash: " + pkgName);
16120                    return;
16121                }
16122                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16123                    res.setError(INSTALL_FAILED_INVALID_APK,
16124                            "New package fails restrict-update check: " + pkgName);
16125                    return;
16126                }
16127                // retain upgrade restriction
16128                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16129            }
16130
16131            // Check for shared user id changes
16132            String invalidPackageName =
16133                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16134            if (invalidPackageName != null) {
16135                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16136                        "Package " + invalidPackageName + " tried to change user "
16137                                + oldPackage.mSharedUserId);
16138                return;
16139            }
16140
16141            // check if the new package supports all of the abis which the old package supports
16142            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16143            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16144            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16145                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16146                        "Update to package " + pkgName + " doesn't support multi arch");
16147                return;
16148            }
16149
16150            // In case of rollback, remember per-user/profile install state
16151            allUsers = sUserManager.getUserIds();
16152            installedUsers = ps.queryInstalledUsers(allUsers, true);
16153
16154            // don't allow an upgrade from full to ephemeral
16155            if (isInstantApp) {
16156                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16157                    for (int currentUser : allUsers) {
16158                        if (!ps.getInstantApp(currentUser)) {
16159                            // can't downgrade from full to instant
16160                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16161                                    + " for user: " + currentUser);
16162                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16163                            return;
16164                        }
16165                    }
16166                } else if (!ps.getInstantApp(user.getIdentifier())) {
16167                    // can't downgrade from full to instant
16168                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16169                            + " for user: " + user.getIdentifier());
16170                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16171                    return;
16172                }
16173            }
16174        }
16175
16176        // Update what is removed
16177        res.removedInfo = new PackageRemovedInfo(this);
16178        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16179        res.removedInfo.removedPackage = oldPackage.packageName;
16180        res.removedInfo.installerPackageName = ps.installerPackageName;
16181        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16182        res.removedInfo.isUpdate = true;
16183        res.removedInfo.origUsers = installedUsers;
16184        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16185        for (int i = 0; i < installedUsers.length; i++) {
16186            final int userId = installedUsers[i];
16187            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16188        }
16189
16190        final int childCount = (oldPackage.childPackages != null)
16191                ? oldPackage.childPackages.size() : 0;
16192        for (int i = 0; i < childCount; i++) {
16193            boolean childPackageUpdated = false;
16194            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16195            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16196            if (res.addedChildPackages != null) {
16197                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16198                if (childRes != null) {
16199                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16200                    childRes.removedInfo.removedPackage = childPkg.packageName;
16201                    if (childPs != null) {
16202                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16203                    }
16204                    childRes.removedInfo.isUpdate = true;
16205                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16206                    childPackageUpdated = true;
16207                }
16208            }
16209            if (!childPackageUpdated) {
16210                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16211                childRemovedRes.removedPackage = childPkg.packageName;
16212                if (childPs != null) {
16213                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16214                }
16215                childRemovedRes.isUpdate = false;
16216                childRemovedRes.dataRemoved = true;
16217                synchronized (mPackages) {
16218                    if (childPs != null) {
16219                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16220                    }
16221                }
16222                if (res.removedInfo.removedChildPackages == null) {
16223                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16224                }
16225                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16226            }
16227        }
16228
16229        boolean sysPkg = (isSystemApp(oldPackage));
16230        if (sysPkg) {
16231            // Set the system/privileged/oem/vendor/product flags as needed
16232            final boolean privileged =
16233                    (oldPackage.applicationInfo.privateFlags
16234                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16235            final boolean oem =
16236                    (oldPackage.applicationInfo.privateFlags
16237                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16238            final boolean vendor =
16239                    (oldPackage.applicationInfo.privateFlags
16240                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16241            final boolean product =
16242                    (oldPackage.applicationInfo.privateFlags
16243                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16244            final @ParseFlags int systemParseFlags = parseFlags;
16245            final @ScanFlags int systemScanFlags = scanFlags
16246                    | SCAN_AS_SYSTEM
16247                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16248                    | (oem ? SCAN_AS_OEM : 0)
16249                    | (vendor ? SCAN_AS_VENDOR : 0)
16250                    | (product ? SCAN_AS_PRODUCT : 0);
16251
16252            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16253                    user, allUsers, installerPackageName, res, installReason);
16254        } else {
16255            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16256                    user, allUsers, installerPackageName, res, installReason);
16257        }
16258    }
16259
16260    @Override
16261    public List<String> getPreviousCodePaths(String packageName) {
16262        final int callingUid = Binder.getCallingUid();
16263        final List<String> result = new ArrayList<>();
16264        if (getInstantAppPackageName(callingUid) != null) {
16265            return result;
16266        }
16267        final PackageSetting ps = mSettings.mPackages.get(packageName);
16268        if (ps != null
16269                && ps.oldCodePaths != null
16270                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16271            result.addAll(ps.oldCodePaths);
16272        }
16273        return result;
16274    }
16275
16276    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16277            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16278            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16279            String installerPackageName, PackageInstalledInfo res, int installReason) {
16280        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16281                + deletedPackage);
16282
16283        String pkgName = deletedPackage.packageName;
16284        boolean deletedPkg = true;
16285        boolean addedPkg = false;
16286        boolean updatedSettings = false;
16287        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16288        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16289                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16290
16291        final long origUpdateTime = (pkg.mExtras != null)
16292                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16293
16294        // First delete the existing package while retaining the data directory
16295        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16296                res.removedInfo, true, pkg)) {
16297            // If the existing package wasn't successfully deleted
16298            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16299            deletedPkg = false;
16300        } else {
16301            // Successfully deleted the old package; proceed with replace.
16302
16303            // If deleted package lived in a container, give users a chance to
16304            // relinquish resources before killing.
16305            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16306                if (DEBUG_INSTALL) {
16307                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16308                }
16309                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16310                final ArrayList<String> pkgList = new ArrayList<String>(1);
16311                pkgList.add(deletedPackage.applicationInfo.packageName);
16312                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16313            }
16314
16315            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16316                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16317
16318            try {
16319                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16320                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16321                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16322                        installReason);
16323
16324                // Update the in-memory copy of the previous code paths.
16325                PackageSetting ps = mSettings.mPackages.get(pkgName);
16326                if (!killApp) {
16327                    if (ps.oldCodePaths == null) {
16328                        ps.oldCodePaths = new ArraySet<>();
16329                    }
16330                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16331                    if (deletedPackage.splitCodePaths != null) {
16332                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16333                    }
16334                } else {
16335                    ps.oldCodePaths = null;
16336                }
16337                if (ps.childPackageNames != null) {
16338                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16339                        final String childPkgName = ps.childPackageNames.get(i);
16340                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16341                        childPs.oldCodePaths = ps.oldCodePaths;
16342                    }
16343                }
16344                // set instant app status, but, only if it's explicitly specified
16345                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16346                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16347                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16348                prepareAppDataAfterInstallLIF(newPackage);
16349                addedPkg = true;
16350                mDexManager.notifyPackageUpdated(newPackage.packageName,
16351                        newPackage.baseCodePath, newPackage.splitCodePaths);
16352            } catch (PackageManagerException e) {
16353                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16354            }
16355        }
16356
16357        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16358            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16359
16360            // Revert all internal state mutations and added folders for the failed install
16361            if (addedPkg) {
16362                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16363                        res.removedInfo, true, null);
16364            }
16365
16366            // Restore the old package
16367            if (deletedPkg) {
16368                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16369                File restoreFile = new File(deletedPackage.codePath);
16370                // Parse old package
16371                boolean oldExternal = isExternal(deletedPackage);
16372                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16373                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16374                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16375                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16376                try {
16377                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16378                            null);
16379                } catch (PackageManagerException e) {
16380                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16381                            + e.getMessage());
16382                    return;
16383                }
16384
16385                synchronized (mPackages) {
16386                    // Ensure the installer package name up to date
16387                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16388
16389                    // Update permissions for restored package
16390                    mPermissionManager.updatePermissions(
16391                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16392                            mPermissionCallback);
16393
16394                    mSettings.writeLPr();
16395                }
16396
16397                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16398            }
16399        } else {
16400            synchronized (mPackages) {
16401                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16402                if (ps != null) {
16403                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16404                    if (res.removedInfo.removedChildPackages != null) {
16405                        final int childCount = res.removedInfo.removedChildPackages.size();
16406                        // Iterate in reverse as we may modify the collection
16407                        for (int i = childCount - 1; i >= 0; i--) {
16408                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16409                            if (res.addedChildPackages.containsKey(childPackageName)) {
16410                                res.removedInfo.removedChildPackages.removeAt(i);
16411                            } else {
16412                                PackageRemovedInfo childInfo = res.removedInfo
16413                                        .removedChildPackages.valueAt(i);
16414                                childInfo.removedForAllUsers = mPackages.get(
16415                                        childInfo.removedPackage) == null;
16416                            }
16417                        }
16418                    }
16419                }
16420            }
16421        }
16422    }
16423
16424    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16425            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16426            final @ScanFlags int scanFlags, UserHandle user,
16427            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16428            int installReason) {
16429        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16430                + ", old=" + deletedPackage);
16431
16432        final boolean disabledSystem;
16433
16434        // Remove existing system package
16435        removePackageLI(deletedPackage, true);
16436
16437        synchronized (mPackages) {
16438            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16439        }
16440        if (!disabledSystem) {
16441            // We didn't need to disable the .apk as a current system package,
16442            // which means we are replacing another update that is already
16443            // installed.  We need to make sure to delete the older one's .apk.
16444            res.removedInfo.args = createInstallArgsForExisting(0,
16445                    deletedPackage.applicationInfo.getCodePath(),
16446                    deletedPackage.applicationInfo.getResourcePath(),
16447                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16448        } else {
16449            res.removedInfo.args = null;
16450        }
16451
16452        // Successfully disabled the old package. Now proceed with re-installation
16453        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16454                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16455
16456        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16457        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16458                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16459
16460        PackageParser.Package newPackage = null;
16461        try {
16462            // Add the package to the internal data structures
16463            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16464
16465            // Set the update and install times
16466            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16467            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16468                    System.currentTimeMillis());
16469
16470            // Update the package dynamic state if succeeded
16471            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16472                // Now that the install succeeded make sure we remove data
16473                // directories for any child package the update removed.
16474                final int deletedChildCount = (deletedPackage.childPackages != null)
16475                        ? deletedPackage.childPackages.size() : 0;
16476                final int newChildCount = (newPackage.childPackages != null)
16477                        ? newPackage.childPackages.size() : 0;
16478                for (int i = 0; i < deletedChildCount; i++) {
16479                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16480                    boolean childPackageDeleted = true;
16481                    for (int j = 0; j < newChildCount; j++) {
16482                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16483                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16484                            childPackageDeleted = false;
16485                            break;
16486                        }
16487                    }
16488                    if (childPackageDeleted) {
16489                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16490                                deletedChildPkg.packageName);
16491                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16492                            PackageRemovedInfo removedChildRes = res.removedInfo
16493                                    .removedChildPackages.get(deletedChildPkg.packageName);
16494                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16495                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16496                        }
16497                    }
16498                }
16499
16500                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16501                        installReason);
16502                prepareAppDataAfterInstallLIF(newPackage);
16503
16504                mDexManager.notifyPackageUpdated(newPackage.packageName,
16505                            newPackage.baseCodePath, newPackage.splitCodePaths);
16506            }
16507        } catch (PackageManagerException e) {
16508            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16509            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16510        }
16511
16512        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16513            // Re installation failed. Restore old information
16514            // Remove new pkg information
16515            if (newPackage != null) {
16516                removeInstalledPackageLI(newPackage, true);
16517            }
16518            // Add back the old system package
16519            try {
16520                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16521            } catch (PackageManagerException e) {
16522                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16523            }
16524
16525            synchronized (mPackages) {
16526                if (disabledSystem) {
16527                    enableSystemPackageLPw(deletedPackage);
16528                }
16529
16530                // Ensure the installer package name up to date
16531                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16532
16533                // Update permissions for restored package
16534                mPermissionManager.updatePermissions(
16535                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16536                        mPermissionCallback);
16537
16538                mSettings.writeLPr();
16539            }
16540
16541            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16542                    + " after failed upgrade");
16543        }
16544    }
16545
16546    /**
16547     * Checks whether the parent or any of the child packages have a change shared
16548     * user. For a package to be a valid update the shred users of the parent and
16549     * the children should match. We may later support changing child shared users.
16550     * @param oldPkg The updated package.
16551     * @param newPkg The update package.
16552     * @return The shared user that change between the versions.
16553     */
16554    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16555            PackageParser.Package newPkg) {
16556        // Check parent shared user
16557        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16558            return newPkg.packageName;
16559        }
16560        // Check child shared users
16561        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16562        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16563        for (int i = 0; i < newChildCount; i++) {
16564            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16565            // If this child was present, did it have the same shared user?
16566            for (int j = 0; j < oldChildCount; j++) {
16567                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16568                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16569                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16570                    return newChildPkg.packageName;
16571                }
16572            }
16573        }
16574        return null;
16575    }
16576
16577    private void removeNativeBinariesLI(PackageSetting ps) {
16578        // Remove the lib path for the parent package
16579        if (ps != null) {
16580            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16581            // Remove the lib path for the child packages
16582            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16583            for (int i = 0; i < childCount; i++) {
16584                PackageSetting childPs = null;
16585                synchronized (mPackages) {
16586                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16587                }
16588                if (childPs != null) {
16589                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16590                            .legacyNativeLibraryPathString);
16591                }
16592            }
16593        }
16594    }
16595
16596    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16597        // Enable the parent package
16598        mSettings.enableSystemPackageLPw(pkg.packageName);
16599        // Enable the child packages
16600        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16601        for (int i = 0; i < childCount; i++) {
16602            PackageParser.Package childPkg = pkg.childPackages.get(i);
16603            mSettings.enableSystemPackageLPw(childPkg.packageName);
16604        }
16605    }
16606
16607    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16608            PackageParser.Package newPkg) {
16609        // Disable the parent package (parent always replaced)
16610        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16611        // Disable the child packages
16612        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16613        for (int i = 0; i < childCount; i++) {
16614            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16615            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16616            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16617        }
16618        return disabled;
16619    }
16620
16621    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16622            String installerPackageName) {
16623        // Enable the parent package
16624        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16625        // Enable the child packages
16626        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16627        for (int i = 0; i < childCount; i++) {
16628            PackageParser.Package childPkg = pkg.childPackages.get(i);
16629            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16630        }
16631    }
16632
16633    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16634            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16635        // Update the parent package setting
16636        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16637                res, user, installReason);
16638        // Update the child packages setting
16639        final int childCount = (newPackage.childPackages != null)
16640                ? newPackage.childPackages.size() : 0;
16641        for (int i = 0; i < childCount; i++) {
16642            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16643            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16644            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16645                    childRes.origUsers, childRes, user, installReason);
16646        }
16647    }
16648
16649    private void updateSettingsInternalLI(PackageParser.Package pkg,
16650            String installerPackageName, int[] allUsers, int[] installedForUsers,
16651            PackageInstalledInfo res, UserHandle user, int installReason) {
16652        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16653
16654        String pkgName = pkg.packageName;
16655        synchronized (mPackages) {
16656            //write settings. the installStatus will be incomplete at this stage.
16657            //note that the new package setting would have already been
16658            //added to mPackages. It hasn't been persisted yet.
16659            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16660            // TODO: Remove this write? It's also written at the end of this method
16661            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16662            mSettings.writeLPr();
16663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16664        }
16665
16666        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16667        synchronized (mPackages) {
16668// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16669            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16670                    mPermissionCallback);
16671            // For system-bundled packages, we assume that installing an upgraded version
16672            // of the package implies that the user actually wants to run that new code,
16673            // so we enable the package.
16674            PackageSetting ps = mSettings.mPackages.get(pkgName);
16675            final int userId = user.getIdentifier();
16676            if (ps != null) {
16677                if (isSystemApp(pkg)) {
16678                    if (DEBUG_INSTALL) {
16679                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16680                    }
16681                    // Enable system package for requested users
16682                    if (res.origUsers != null) {
16683                        for (int origUserId : res.origUsers) {
16684                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16685                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16686                                        origUserId, installerPackageName);
16687                            }
16688                        }
16689                    }
16690                    // Also convey the prior install/uninstall state
16691                    if (allUsers != null && installedForUsers != null) {
16692                        for (int currentUserId : allUsers) {
16693                            final boolean installed = ArrayUtils.contains(
16694                                    installedForUsers, currentUserId);
16695                            if (DEBUG_INSTALL) {
16696                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16697                            }
16698                            ps.setInstalled(installed, currentUserId);
16699                        }
16700                        // these install state changes will be persisted in the
16701                        // upcoming call to mSettings.writeLPr().
16702                    }
16703                }
16704                // It's implied that when a user requests installation, they want the app to be
16705                // installed and enabled.
16706                if (userId != UserHandle.USER_ALL) {
16707                    ps.setInstalled(true, userId);
16708                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16709                }
16710
16711                // When replacing an existing package, preserve the original install reason for all
16712                // users that had the package installed before.
16713                final Set<Integer> previousUserIds = new ArraySet<>();
16714                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16715                    final int installReasonCount = res.removedInfo.installReasons.size();
16716                    for (int i = 0; i < installReasonCount; i++) {
16717                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16718                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16719                        ps.setInstallReason(previousInstallReason, previousUserId);
16720                        previousUserIds.add(previousUserId);
16721                    }
16722                }
16723
16724                // Set install reason for users that are having the package newly installed.
16725                if (userId == UserHandle.USER_ALL) {
16726                    for (int currentUserId : sUserManager.getUserIds()) {
16727                        if (!previousUserIds.contains(currentUserId)) {
16728                            ps.setInstallReason(installReason, currentUserId);
16729                        }
16730                    }
16731                } else if (!previousUserIds.contains(userId)) {
16732                    ps.setInstallReason(installReason, userId);
16733                }
16734                mSettings.writeKernelMappingLPr(ps);
16735            }
16736            res.name = pkgName;
16737            res.uid = pkg.applicationInfo.uid;
16738            res.pkg = pkg;
16739            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16740            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16741            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16742            //to update install status
16743            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16744            mSettings.writeLPr();
16745            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16746        }
16747
16748        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16749    }
16750
16751    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16752        try {
16753            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16754            installPackageLI(args, res);
16755        } finally {
16756            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16757        }
16758    }
16759
16760    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16761        final int installFlags = args.installFlags;
16762        final String installerPackageName = args.installerPackageName;
16763        final String volumeUuid = args.volumeUuid;
16764        final File tmpPackageFile = new File(args.getCodePath());
16765        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16766        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16767                || (args.volumeUuid != null));
16768        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16769        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16770        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16771        final boolean virtualPreload =
16772                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16773        boolean replace = false;
16774        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16775        if (args.move != null) {
16776            // moving a complete application; perform an initial scan on the new install location
16777            scanFlags |= SCAN_INITIAL;
16778        }
16779        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16780            scanFlags |= SCAN_DONT_KILL_APP;
16781        }
16782        if (instantApp) {
16783            scanFlags |= SCAN_AS_INSTANT_APP;
16784        }
16785        if (fullApp) {
16786            scanFlags |= SCAN_AS_FULL_APP;
16787        }
16788        if (virtualPreload) {
16789            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16790        }
16791
16792        // Result object to be returned
16793        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16794        res.installerPackageName = installerPackageName;
16795
16796        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16797
16798        // Sanity check
16799        if (instantApp && (forwardLocked || onExternal)) {
16800            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16801                    + " external=" + onExternal);
16802            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16803            return;
16804        }
16805
16806        // Retrieve PackageSettings and parse package
16807        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16808                | PackageParser.PARSE_ENFORCE_CODE
16809                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16810                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16811                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16812        PackageParser pp = new PackageParser();
16813        pp.setSeparateProcesses(mSeparateProcesses);
16814        pp.setDisplayMetrics(mMetrics);
16815        pp.setCallback(mPackageParserCallback);
16816
16817        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16818        final PackageParser.Package pkg;
16819        try {
16820            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16821            DexMetadataHelper.validatePackageDexMetadata(pkg);
16822        } catch (PackageParserException e) {
16823            res.setError("Failed parse during installPackageLI", e);
16824            return;
16825        } finally {
16826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16827        }
16828
16829        // Instant apps have several additional install-time checks.
16830        if (instantApp) {
16831            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16832                Slog.w(TAG,
16833                        "Instant app package " + pkg.packageName + " does not target at least O");
16834                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16835                        "Instant app package must target at least O");
16836                return;
16837            }
16838            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16839                Slog.w(TAG, "Instant app package " + pkg.packageName
16840                        + " does not target targetSandboxVersion 2");
16841                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16842                        "Instant app package must use targetSandboxVersion 2");
16843                return;
16844            }
16845            if (pkg.mSharedUserId != null) {
16846                Slog.w(TAG, "Instant app package " + pkg.packageName
16847                        + " may not declare sharedUserId.");
16848                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16849                        "Instant app package may not declare a sharedUserId");
16850                return;
16851            }
16852        }
16853
16854        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16855            // Static shared libraries have synthetic package names
16856            renameStaticSharedLibraryPackage(pkg);
16857
16858            // No static shared libs on external storage
16859            if (onExternal) {
16860                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16861                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16862                        "Packages declaring static-shared libs cannot be updated");
16863                return;
16864            }
16865        }
16866
16867        // If we are installing a clustered package add results for the children
16868        if (pkg.childPackages != null) {
16869            synchronized (mPackages) {
16870                final int childCount = pkg.childPackages.size();
16871                for (int i = 0; i < childCount; i++) {
16872                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16873                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16874                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16875                    childRes.pkg = childPkg;
16876                    childRes.name = childPkg.packageName;
16877                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16878                    if (childPs != null) {
16879                        childRes.origUsers = childPs.queryInstalledUsers(
16880                                sUserManager.getUserIds(), true);
16881                    }
16882                    if ((mPackages.containsKey(childPkg.packageName))) {
16883                        childRes.removedInfo = new PackageRemovedInfo(this);
16884                        childRes.removedInfo.removedPackage = childPkg.packageName;
16885                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16886                    }
16887                    if (res.addedChildPackages == null) {
16888                        res.addedChildPackages = new ArrayMap<>();
16889                    }
16890                    res.addedChildPackages.put(childPkg.packageName, childRes);
16891                }
16892            }
16893        }
16894
16895        // If package doesn't declare API override, mark that we have an install
16896        // time CPU ABI override.
16897        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16898            pkg.cpuAbiOverride = args.abiOverride;
16899        }
16900
16901        String pkgName = res.name = pkg.packageName;
16902        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16903            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16904                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16905                return;
16906            }
16907        }
16908
16909        try {
16910            // either use what we've been given or parse directly from the APK
16911            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16912                pkg.setSigningDetails(args.signingDetails);
16913            } else {
16914                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16915            }
16916        } catch (PackageParserException e) {
16917            res.setError("Failed collect during installPackageLI", e);
16918            return;
16919        }
16920
16921        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16922                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16923            Slog.w(TAG, "Instant app package " + pkg.packageName
16924                    + " is not signed with at least APK Signature Scheme v2");
16925            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16926                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16927            return;
16928        }
16929
16930        // Get rid of all references to package scan path via parser.
16931        pp = null;
16932        String oldCodePath = null;
16933        boolean systemApp = false;
16934        synchronized (mPackages) {
16935            // Check if installing already existing package
16936            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16937                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16938                if (pkg.mOriginalPackages != null
16939                        && pkg.mOriginalPackages.contains(oldName)
16940                        && mPackages.containsKey(oldName)) {
16941                    // This package is derived from an original package,
16942                    // and this device has been updating from that original
16943                    // name.  We must continue using the original name, so
16944                    // rename the new package here.
16945                    pkg.setPackageName(oldName);
16946                    pkgName = pkg.packageName;
16947                    replace = true;
16948                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16949                            + oldName + " pkgName=" + pkgName);
16950                } else if (mPackages.containsKey(pkgName)) {
16951                    // This package, under its official name, already exists
16952                    // on the device; we should replace it.
16953                    replace = true;
16954                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16955                }
16956
16957                // Child packages are installed through the parent package
16958                if (pkg.parentPackage != null) {
16959                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16960                            "Package " + pkg.packageName + " is child of package "
16961                                    + pkg.parentPackage.parentPackage + ". Child packages "
16962                                    + "can be updated only through the parent package.");
16963                    return;
16964                }
16965
16966                if (replace) {
16967                    // Prevent apps opting out from runtime permissions
16968                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16969                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16970                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16971                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16972                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16973                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16974                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16975                                        + " doesn't support runtime permissions but the old"
16976                                        + " target SDK " + oldTargetSdk + " does.");
16977                        return;
16978                    }
16979                    // Prevent persistent apps from being updated
16980                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16981                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16982                                "Package " + oldPackage.packageName + " is a persistent app. "
16983                                        + "Persistent apps are not updateable.");
16984                        return;
16985                    }
16986                    // Prevent apps from downgrading their targetSandbox.
16987                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16988                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16989                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16990                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16991                                "Package " + pkg.packageName + " new target sandbox "
16992                                + newTargetSandbox + " is incompatible with the previous value of"
16993                                + oldTargetSandbox + ".");
16994                        return;
16995                    }
16996
16997                    // Prevent installing of child packages
16998                    if (oldPackage.parentPackage != null) {
16999                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17000                                "Package " + pkg.packageName + " is child of package "
17001                                        + oldPackage.parentPackage + ". Child packages "
17002                                        + "can be updated only through the parent package.");
17003                        return;
17004                    }
17005                }
17006            }
17007
17008            PackageSetting ps = mSettings.mPackages.get(pkgName);
17009            if (ps != null) {
17010                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17011
17012                // Static shared libs have same package with different versions where
17013                // we internally use a synthetic package name to allow multiple versions
17014                // of the same package, therefore we need to compare signatures against
17015                // the package setting for the latest library version.
17016                PackageSetting signatureCheckPs = ps;
17017                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17018                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17019                    if (libraryEntry != null) {
17020                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17021                    }
17022                }
17023
17024                // Quick sanity check that we're signed correctly if updating;
17025                // we'll check this again later when scanning, but we want to
17026                // bail early here before tripping over redefined permissions.
17027                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17028                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17029                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17030                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17031                                + pkg.packageName + " upgrade keys do not match the "
17032                                + "previously installed version");
17033                        return;
17034                    }
17035                } else {
17036                    try {
17037                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17038                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17039                        // We don't care about disabledPkgSetting on install for now.
17040                        final boolean compatMatch = verifySignatures(
17041                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17042                                compareRecover);
17043                        // The new KeySets will be re-added later in the scanning process.
17044                        if (compatMatch) {
17045                            synchronized (mPackages) {
17046                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17047                            }
17048                        }
17049                    } catch (PackageManagerException e) {
17050                        res.setError(e.error, e.getMessage());
17051                        return;
17052                    }
17053                }
17054
17055                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17056                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17057                    systemApp = (ps.pkg.applicationInfo.flags &
17058                            ApplicationInfo.FLAG_SYSTEM) != 0;
17059                }
17060                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17061            }
17062
17063            int N = pkg.permissions.size();
17064            for (int i = N-1; i >= 0; i--) {
17065                final PackageParser.Permission perm = pkg.permissions.get(i);
17066                final BasePermission bp =
17067                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17068
17069                // Don't allow anyone but the system to define ephemeral permissions.
17070                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17071                        && !systemApp) {
17072                    Slog.w(TAG, "Non-System package " + pkg.packageName
17073                            + " attempting to delcare ephemeral permission "
17074                            + perm.info.name + "; Removing ephemeral.");
17075                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17076                }
17077
17078                // Check whether the newly-scanned package wants to define an already-defined perm
17079                if (bp != null) {
17080                    // If the defining package is signed with our cert, it's okay.  This
17081                    // also includes the "updating the same package" case, of course.
17082                    // "updating same package" could also involve key-rotation.
17083                    final boolean sigsOk;
17084                    final String sourcePackageName = bp.getSourcePackageName();
17085                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17086                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17087                    if (sourcePackageName.equals(pkg.packageName)
17088                            && (ksms.shouldCheckUpgradeKeySetLocked(
17089                                    sourcePackageSetting, scanFlags))) {
17090                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17091                    } else {
17092
17093                        // in the event of signing certificate rotation, we need to see if the
17094                        // package's certificate has rotated from the current one, or if it is an
17095                        // older certificate with which the current is ok with sharing permissions
17096                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17097                                        pkg.mSigningDetails,
17098                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17099                            sigsOk = true;
17100                        } else if (pkg.mSigningDetails.checkCapability(
17101                                        sourcePackageSetting.signatures.mSigningDetails,
17102                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17103
17104                            // the scanned package checks out, has signing certificate rotation
17105                            // history, and is newer; bring it over
17106                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17107                            sigsOk = true;
17108                        } else {
17109                            sigsOk = false;
17110                        }
17111                    }
17112                    if (!sigsOk) {
17113                        // If the owning package is the system itself, we log but allow
17114                        // install to proceed; we fail the install on all other permission
17115                        // redefinitions.
17116                        if (!sourcePackageName.equals("android")) {
17117                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17118                                    + pkg.packageName + " attempting to redeclare permission "
17119                                    + perm.info.name + " already owned by " + sourcePackageName);
17120                            res.origPermission = perm.info.name;
17121                            res.origPackage = sourcePackageName;
17122                            return;
17123                        } else {
17124                            Slog.w(TAG, "Package " + pkg.packageName
17125                                    + " attempting to redeclare system permission "
17126                                    + perm.info.name + "; ignoring new declaration");
17127                            pkg.permissions.remove(i);
17128                        }
17129                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17130                        // Prevent apps to change protection level to dangerous from any other
17131                        // type as this would allow a privilege escalation where an app adds a
17132                        // normal/signature permission in other app's group and later redefines
17133                        // it as dangerous leading to the group auto-grant.
17134                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17135                                == PermissionInfo.PROTECTION_DANGEROUS) {
17136                            if (bp != null && !bp.isRuntime()) {
17137                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17138                                        + "non-runtime permission " + perm.info.name
17139                                        + " to runtime; keeping old protection level");
17140                                perm.info.protectionLevel = bp.getProtectionLevel();
17141                            }
17142                        }
17143                    }
17144                }
17145            }
17146        }
17147
17148        if (systemApp) {
17149            if (onExternal) {
17150                // Abort update; system app can't be replaced with app on sdcard
17151                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17152                        "Cannot install updates to system apps on sdcard");
17153                return;
17154            } else if (instantApp) {
17155                // Abort update; system app can't be replaced with an instant app
17156                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17157                        "Cannot update a system app with an instant app");
17158                return;
17159            }
17160        }
17161
17162        if (args.move != null) {
17163            // We did an in-place move, so dex is ready to roll
17164            scanFlags |= SCAN_NO_DEX;
17165            scanFlags |= SCAN_MOVE;
17166
17167            synchronized (mPackages) {
17168                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17169                if (ps == null) {
17170                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17171                            "Missing settings for moved package " + pkgName);
17172                }
17173
17174                // We moved the entire application as-is, so bring over the
17175                // previously derived ABI information.
17176                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17177                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17178            }
17179
17180        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17181            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17182            scanFlags |= SCAN_NO_DEX;
17183
17184            try {
17185                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17186                    args.abiOverride : pkg.cpuAbiOverride);
17187                final boolean extractNativeLibs = !pkg.isLibrary();
17188                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17189            } catch (PackageManagerException pme) {
17190                Slog.e(TAG, "Error deriving application ABI", pme);
17191                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17192                return;
17193            }
17194
17195            // Shared libraries for the package need to be updated.
17196            synchronized (mPackages) {
17197                try {
17198                    updateSharedLibrariesLPr(pkg, null);
17199                } catch (PackageManagerException e) {
17200                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17201                }
17202            }
17203        }
17204
17205        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17206            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17207            return;
17208        }
17209
17210        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17211            String apkPath = null;
17212            synchronized (mPackages) {
17213                // Note that if the attacker managed to skip verify setup, for example by tampering
17214                // with the package settings, upon reboot we will do full apk verification when
17215                // verity is not detected.
17216                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17217                if (ps != null && ps.isPrivileged()) {
17218                    apkPath = pkg.baseCodePath;
17219                }
17220            }
17221
17222            if (apkPath != null) {
17223                final VerityUtils.SetupResult result =
17224                        VerityUtils.generateApkVeritySetupData(apkPath);
17225                if (result.isOk()) {
17226                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17227                    FileDescriptor fd = result.getUnownedFileDescriptor();
17228                    try {
17229                        mInstaller.installApkVerity(apkPath, fd);
17230                    } catch (InstallerException e) {
17231                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17232                                "Failed to set up verity: " + e);
17233                        return;
17234                    } finally {
17235                        IoUtils.closeQuietly(fd);
17236                    }
17237                } else if (result.isFailed()) {
17238                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17239                    return;
17240                } else {
17241                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17242                    // reboot.
17243                }
17244            }
17245        }
17246
17247        if (!instantApp) {
17248            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17249        } else {
17250            if (DEBUG_DOMAIN_VERIFICATION) {
17251                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17252            }
17253        }
17254
17255        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17256                "installPackageLI")) {
17257            if (replace) {
17258                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17259                    // Static libs have a synthetic package name containing the version
17260                    // and cannot be updated as an update would get a new package name,
17261                    // unless this is the exact same version code which is useful for
17262                    // development.
17263                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17264                    if (existingPkg != null &&
17265                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17266                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17267                                + "static-shared libs cannot be updated");
17268                        return;
17269                    }
17270                }
17271                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17272                        installerPackageName, res, args.installReason);
17273            } else {
17274                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17275                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17276            }
17277        }
17278
17279        // Prepare the application profiles for the new code paths.
17280        // This needs to be done before invoking dexopt so that any install-time profile
17281        // can be used for optimizations.
17282        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17283
17284        // Check whether we need to dexopt the app.
17285        //
17286        // NOTE: it is IMPORTANT to call dexopt:
17287        //   - after doRename which will sync the package data from PackageParser.Package and its
17288        //     corresponding ApplicationInfo.
17289        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17290        //     uid of the application (pkg.applicationInfo.uid).
17291        //     This update happens in place!
17292        //
17293        // We only need to dexopt if the package meets ALL of the following conditions:
17294        //   1) it is not forward locked.
17295        //   2) it is not on on an external ASEC container.
17296        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17297        //
17298        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17299        // complete, so we skip this step during installation. Instead, we'll take extra time
17300        // the first time the instant app starts. It's preferred to do it this way to provide
17301        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17302        // middle of running an instant app. The default behaviour can be overridden
17303        // via gservices.
17304        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17305                && !forwardLocked
17306                && !pkg.applicationInfo.isExternalAsec()
17307                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17308                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17309
17310        if (performDexopt) {
17311            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17312            // Do not run PackageDexOptimizer through the local performDexOpt
17313            // method because `pkg` may not be in `mPackages` yet.
17314            //
17315            // Also, don't fail application installs if the dexopt step fails.
17316            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17317                    REASON_INSTALL,
17318                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
17319            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17320                    null /* instructionSets */,
17321                    getOrCreateCompilerPackageStats(pkg),
17322                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17323                    dexoptOptions);
17324            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17325        }
17326
17327        // Notify BackgroundDexOptService that the package has been changed.
17328        // If this is an update of a package which used to fail to compile,
17329        // BackgroundDexOptService will remove it from its blacklist.
17330        // TODO: Layering violation
17331        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17332
17333        synchronized (mPackages) {
17334            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17335            if (ps != null) {
17336                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17337                ps.setUpdateAvailable(false /*updateAvailable*/);
17338            }
17339
17340            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17341            for (int i = 0; i < childCount; i++) {
17342                PackageParser.Package childPkg = pkg.childPackages.get(i);
17343                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17344                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17345                if (childPs != null) {
17346                    childRes.newUsers = childPs.queryInstalledUsers(
17347                            sUserManager.getUserIds(), true);
17348                }
17349            }
17350
17351            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17352                updateSequenceNumberLP(ps, res.newUsers);
17353                updateInstantAppInstallerLocked(pkgName);
17354            }
17355        }
17356    }
17357
17358    private void startIntentFilterVerifications(int userId, boolean replacing,
17359            PackageParser.Package pkg) {
17360        if (mIntentFilterVerifierComponent == null) {
17361            Slog.w(TAG, "No IntentFilter verification will not be done as "
17362                    + "there is no IntentFilterVerifier available!");
17363            return;
17364        }
17365
17366        final int verifierUid = getPackageUid(
17367                mIntentFilterVerifierComponent.getPackageName(),
17368                MATCH_DEBUG_TRIAGED_MISSING,
17369                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17370
17371        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17372        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17373        mHandler.sendMessage(msg);
17374
17375        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17376        for (int i = 0; i < childCount; i++) {
17377            PackageParser.Package childPkg = pkg.childPackages.get(i);
17378            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17379            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17380            mHandler.sendMessage(msg);
17381        }
17382    }
17383
17384    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17385            PackageParser.Package pkg) {
17386        int size = pkg.activities.size();
17387        if (size == 0) {
17388            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17389                    "No activity, so no need to verify any IntentFilter!");
17390            return;
17391        }
17392
17393        final boolean hasDomainURLs = hasDomainURLs(pkg);
17394        if (!hasDomainURLs) {
17395            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17396                    "No domain URLs, so no need to verify any IntentFilter!");
17397            return;
17398        }
17399
17400        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17401                + " if any IntentFilter from the " + size
17402                + " Activities needs verification ...");
17403
17404        int count = 0;
17405        final String packageName = pkg.packageName;
17406
17407        synchronized (mPackages) {
17408            // If this is a new install and we see that we've already run verification for this
17409            // package, we have nothing to do: it means the state was restored from backup.
17410            if (!replacing) {
17411                IntentFilterVerificationInfo ivi =
17412                        mSettings.getIntentFilterVerificationLPr(packageName);
17413                if (ivi != null) {
17414                    if (DEBUG_DOMAIN_VERIFICATION) {
17415                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17416                                + ivi.getStatusString());
17417                    }
17418                    return;
17419                }
17420            }
17421
17422            // If any filters need to be verified, then all need to be.
17423            boolean needToVerify = false;
17424            for (PackageParser.Activity a : pkg.activities) {
17425                for (ActivityIntentInfo filter : a.intents) {
17426                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17427                        if (DEBUG_DOMAIN_VERIFICATION) {
17428                            Slog.d(TAG,
17429                                    "Intent filter needs verification, so processing all filters");
17430                        }
17431                        needToVerify = true;
17432                        break;
17433                    }
17434                }
17435            }
17436
17437            if (needToVerify) {
17438                final int verificationId = mIntentFilterVerificationToken++;
17439                for (PackageParser.Activity a : pkg.activities) {
17440                    for (ActivityIntentInfo filter : a.intents) {
17441                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17442                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17443                                    "Verification needed for IntentFilter:" + filter.toString());
17444                            mIntentFilterVerifier.addOneIntentFilterVerification(
17445                                    verifierUid, userId, verificationId, filter, packageName);
17446                            count++;
17447                        }
17448                    }
17449                }
17450            }
17451        }
17452
17453        if (count > 0) {
17454            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17455                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17456                    +  " for userId:" + userId);
17457            mIntentFilterVerifier.startVerifications(userId);
17458        } else {
17459            if (DEBUG_DOMAIN_VERIFICATION) {
17460                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17461            }
17462        }
17463    }
17464
17465    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17466        final ComponentName cn  = filter.activity.getComponentName();
17467        final String packageName = cn.getPackageName();
17468
17469        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17470                packageName);
17471        if (ivi == null) {
17472            return true;
17473        }
17474        int status = ivi.getStatus();
17475        switch (status) {
17476            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17477            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17478                return true;
17479
17480            default:
17481                // Nothing to do
17482                return false;
17483        }
17484    }
17485
17486    private static boolean isMultiArch(ApplicationInfo info) {
17487        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17488    }
17489
17490    private static boolean isExternal(PackageParser.Package pkg) {
17491        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17492    }
17493
17494    private static boolean isExternal(PackageSetting ps) {
17495        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17496    }
17497
17498    private static boolean isSystemApp(PackageParser.Package pkg) {
17499        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17500    }
17501
17502    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17503        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17504    }
17505
17506    private static boolean isOemApp(PackageParser.Package pkg) {
17507        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17508    }
17509
17510    private static boolean isVendorApp(PackageParser.Package pkg) {
17511        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17512    }
17513
17514    private static boolean isProductApp(PackageParser.Package pkg) {
17515        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17516    }
17517
17518    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17519        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17520    }
17521
17522    private static boolean isSystemApp(PackageSetting ps) {
17523        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17524    }
17525
17526    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17527        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17528    }
17529
17530    private int packageFlagsToInstallFlags(PackageSetting ps) {
17531        int installFlags = 0;
17532        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17533            // This existing package was an external ASEC install when we have
17534            // the external flag without a UUID
17535            installFlags |= PackageManager.INSTALL_EXTERNAL;
17536        }
17537        if (ps.isForwardLocked()) {
17538            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17539        }
17540        return installFlags;
17541    }
17542
17543    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17544        if (isExternal(pkg)) {
17545            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17546                return mSettings.getExternalVersion();
17547            } else {
17548                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17549            }
17550        } else {
17551            return mSettings.getInternalVersion();
17552        }
17553    }
17554
17555    private void deleteTempPackageFiles() {
17556        final FilenameFilter filter = new FilenameFilter() {
17557            public boolean accept(File dir, String name) {
17558                return name.startsWith("vmdl") && name.endsWith(".tmp");
17559            }
17560        };
17561        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17562            file.delete();
17563        }
17564    }
17565
17566    @Override
17567    public void deletePackageAsUser(String packageName, int versionCode,
17568            IPackageDeleteObserver observer, int userId, int flags) {
17569        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17570                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17571    }
17572
17573    @Override
17574    public void deletePackageVersioned(VersionedPackage versionedPackage,
17575            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17576        final int callingUid = Binder.getCallingUid();
17577        mContext.enforceCallingOrSelfPermission(
17578                android.Manifest.permission.DELETE_PACKAGES, null);
17579        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17580        Preconditions.checkNotNull(versionedPackage);
17581        Preconditions.checkNotNull(observer);
17582        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17583                PackageManager.VERSION_CODE_HIGHEST,
17584                Long.MAX_VALUE, "versionCode must be >= -1");
17585
17586        final String packageName = versionedPackage.getPackageName();
17587        final long versionCode = versionedPackage.getLongVersionCode();
17588        final String internalPackageName;
17589        synchronized (mPackages) {
17590            // Normalize package name to handle renamed packages and static libs
17591            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17592        }
17593
17594        final int uid = Binder.getCallingUid();
17595        if (!isOrphaned(internalPackageName)
17596                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17597            try {
17598                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17599                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17600                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17601                observer.onUserActionRequired(intent);
17602            } catch (RemoteException re) {
17603            }
17604            return;
17605        }
17606        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17607        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17608        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17609            mContext.enforceCallingOrSelfPermission(
17610                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17611                    "deletePackage for user " + userId);
17612        }
17613
17614        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17615            try {
17616                observer.onPackageDeleted(packageName,
17617                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17618            } catch (RemoteException re) {
17619            }
17620            return;
17621        }
17622
17623        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17624            try {
17625                observer.onPackageDeleted(packageName,
17626                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17627            } catch (RemoteException re) {
17628            }
17629            return;
17630        }
17631
17632        if (DEBUG_REMOVE) {
17633            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17634                    + " deleteAllUsers: " + deleteAllUsers + " version="
17635                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17636                    ? "VERSION_CODE_HIGHEST" : versionCode));
17637        }
17638        // Queue up an async operation since the package deletion may take a little while.
17639        mHandler.post(new Runnable() {
17640            public void run() {
17641                mHandler.removeCallbacks(this);
17642                int returnCode;
17643                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17644                boolean doDeletePackage = true;
17645                if (ps != null) {
17646                    final boolean targetIsInstantApp =
17647                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17648                    doDeletePackage = !targetIsInstantApp
17649                            || canViewInstantApps;
17650                }
17651                if (doDeletePackage) {
17652                    if (!deleteAllUsers) {
17653                        returnCode = deletePackageX(internalPackageName, versionCode,
17654                                userId, deleteFlags);
17655                    } else {
17656                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17657                                internalPackageName, users);
17658                        // If nobody is blocking uninstall, proceed with delete for all users
17659                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17660                            returnCode = deletePackageX(internalPackageName, versionCode,
17661                                    userId, deleteFlags);
17662                        } else {
17663                            // Otherwise uninstall individually for users with blockUninstalls=false
17664                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17665                            for (int userId : users) {
17666                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17667                                    returnCode = deletePackageX(internalPackageName, versionCode,
17668                                            userId, userFlags);
17669                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17670                                        Slog.w(TAG, "Package delete failed for user " + userId
17671                                                + ", returnCode " + returnCode);
17672                                    }
17673                                }
17674                            }
17675                            // The app has only been marked uninstalled for certain users.
17676                            // We still need to report that delete was blocked
17677                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17678                        }
17679                    }
17680                } else {
17681                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17682                }
17683                try {
17684                    observer.onPackageDeleted(packageName, returnCode, null);
17685                } catch (RemoteException e) {
17686                    Log.i(TAG, "Observer no longer exists.");
17687                } //end catch
17688            } //end run
17689        });
17690    }
17691
17692    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17693        if (pkg.staticSharedLibName != null) {
17694            return pkg.manifestPackageName;
17695        }
17696        return pkg.packageName;
17697    }
17698
17699    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17700        // Handle renamed packages
17701        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17702        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17703
17704        // Is this a static library?
17705        LongSparseArray<SharedLibraryEntry> versionedLib =
17706                mStaticLibsByDeclaringPackage.get(packageName);
17707        if (versionedLib == null || versionedLib.size() <= 0) {
17708            return packageName;
17709        }
17710
17711        // Figure out which lib versions the caller can see
17712        LongSparseLongArray versionsCallerCanSee = null;
17713        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17714        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17715                && callingAppId != Process.ROOT_UID) {
17716            versionsCallerCanSee = new LongSparseLongArray();
17717            String libName = versionedLib.valueAt(0).info.getName();
17718            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17719            if (uidPackages != null) {
17720                for (String uidPackage : uidPackages) {
17721                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17722                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17723                    if (libIdx >= 0) {
17724                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17725                        versionsCallerCanSee.append(libVersion, libVersion);
17726                    }
17727                }
17728            }
17729        }
17730
17731        // Caller can see nothing - done
17732        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17733            return packageName;
17734        }
17735
17736        // Find the version the caller can see and the app version code
17737        SharedLibraryEntry highestVersion = null;
17738        final int versionCount = versionedLib.size();
17739        for (int i = 0; i < versionCount; i++) {
17740            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17741            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17742                    libEntry.info.getLongVersion()) < 0) {
17743                continue;
17744            }
17745            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17746            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17747                if (libVersionCode == versionCode) {
17748                    return libEntry.apk;
17749                }
17750            } else if (highestVersion == null) {
17751                highestVersion = libEntry;
17752            } else if (libVersionCode  > highestVersion.info
17753                    .getDeclaringPackage().getLongVersionCode()) {
17754                highestVersion = libEntry;
17755            }
17756        }
17757
17758        if (highestVersion != null) {
17759            return highestVersion.apk;
17760        }
17761
17762        return packageName;
17763    }
17764
17765    boolean isCallerVerifier(int callingUid) {
17766        final int callingUserId = UserHandle.getUserId(callingUid);
17767        return mRequiredVerifierPackage != null &&
17768                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17769    }
17770
17771    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17772        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17773              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17774            return true;
17775        }
17776        final int callingUserId = UserHandle.getUserId(callingUid);
17777        // If the caller installed the pkgName, then allow it to silently uninstall.
17778        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17779            return true;
17780        }
17781
17782        // Allow package verifier to silently uninstall.
17783        if (mRequiredVerifierPackage != null &&
17784                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17785            return true;
17786        }
17787
17788        // Allow package uninstaller to silently uninstall.
17789        if (mRequiredUninstallerPackage != null &&
17790                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17791            return true;
17792        }
17793
17794        // Allow storage manager to silently uninstall.
17795        if (mStorageManagerPackage != null &&
17796                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17797            return true;
17798        }
17799
17800        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17801        // uninstall for device owner provisioning.
17802        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17803                == PERMISSION_GRANTED) {
17804            return true;
17805        }
17806
17807        return false;
17808    }
17809
17810    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17811        int[] result = EMPTY_INT_ARRAY;
17812        for (int userId : userIds) {
17813            if (getBlockUninstallForUser(packageName, userId)) {
17814                result = ArrayUtils.appendInt(result, userId);
17815            }
17816        }
17817        return result;
17818    }
17819
17820    @Override
17821    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17822        final int callingUid = Binder.getCallingUid();
17823        if (getInstantAppPackageName(callingUid) != null
17824                && !isCallerSameApp(packageName, callingUid)) {
17825            return false;
17826        }
17827        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17828    }
17829
17830    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17831        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17832                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17833        try {
17834            if (dpm != null) {
17835                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17836                        /* callingUserOnly =*/ false);
17837                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17838                        : deviceOwnerComponentName.getPackageName();
17839                // Does the package contains the device owner?
17840                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17841                // this check is probably not needed, since DO should be registered as a device
17842                // admin on some user too. (Original bug for this: b/17657954)
17843                if (packageName.equals(deviceOwnerPackageName)) {
17844                    return true;
17845                }
17846                // Does it contain a device admin for any user?
17847                int[] users;
17848                if (userId == UserHandle.USER_ALL) {
17849                    users = sUserManager.getUserIds();
17850                } else {
17851                    users = new int[]{userId};
17852                }
17853                for (int i = 0; i < users.length; ++i) {
17854                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17855                        return true;
17856                    }
17857                }
17858            }
17859        } catch (RemoteException e) {
17860        }
17861        return false;
17862    }
17863
17864    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17865        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17866    }
17867
17868    /**
17869     *  This method is an internal method that could be get invoked either
17870     *  to delete an installed package or to clean up a failed installation.
17871     *  After deleting an installed package, a broadcast is sent to notify any
17872     *  listeners that the package has been removed. For cleaning up a failed
17873     *  installation, the broadcast is not necessary since the package's
17874     *  installation wouldn't have sent the initial broadcast either
17875     *  The key steps in deleting a package are
17876     *  deleting the package information in internal structures like mPackages,
17877     *  deleting the packages base directories through installd
17878     *  updating mSettings to reflect current status
17879     *  persisting settings for later use
17880     *  sending a broadcast if necessary
17881     */
17882    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17883        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17884        final boolean res;
17885
17886        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17887                ? UserHandle.USER_ALL : userId;
17888
17889        if (isPackageDeviceAdmin(packageName, removeUser)) {
17890            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17891            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17892        }
17893
17894        PackageSetting uninstalledPs = null;
17895        PackageParser.Package pkg = null;
17896
17897        // for the uninstall-updates case and restricted profiles, remember the per-
17898        // user handle installed state
17899        int[] allUsers;
17900        synchronized (mPackages) {
17901            uninstalledPs = mSettings.mPackages.get(packageName);
17902            if (uninstalledPs == null) {
17903                Slog.w(TAG, "Not removing non-existent package " + packageName);
17904                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17905            }
17906
17907            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17908                    && uninstalledPs.versionCode != versionCode) {
17909                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17910                        + uninstalledPs.versionCode + " != " + versionCode);
17911                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17912            }
17913
17914            // Static shared libs can be declared by any package, so let us not
17915            // allow removing a package if it provides a lib others depend on.
17916            pkg = mPackages.get(packageName);
17917
17918            allUsers = sUserManager.getUserIds();
17919
17920            if (pkg != null && pkg.staticSharedLibName != null) {
17921                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17922                        pkg.staticSharedLibVersion);
17923                if (libEntry != null) {
17924                    for (int currUserId : allUsers) {
17925                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17926                            continue;
17927                        }
17928                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17929                                libEntry.info, 0, currUserId);
17930                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17931                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17932                                    + " hosting lib " + libEntry.info.getName() + " version "
17933                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17934                                    + " for user " + currUserId);
17935                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17936                        }
17937                    }
17938                }
17939            }
17940
17941            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17942        }
17943
17944        final int freezeUser;
17945        if (isUpdatedSystemApp(uninstalledPs)
17946                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17947            // We're downgrading a system app, which will apply to all users, so
17948            // freeze them all during the downgrade
17949            freezeUser = UserHandle.USER_ALL;
17950        } else {
17951            freezeUser = removeUser;
17952        }
17953
17954        synchronized (mInstallLock) {
17955            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17956            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17957                    deleteFlags, "deletePackageX")) {
17958                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17959                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17960            }
17961            synchronized (mPackages) {
17962                if (res) {
17963                    if (pkg != null) {
17964                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17965                    }
17966                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17967                    updateInstantAppInstallerLocked(packageName);
17968                }
17969            }
17970        }
17971
17972        if (res) {
17973            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17974            info.sendPackageRemovedBroadcasts(killApp);
17975            info.sendSystemPackageUpdatedBroadcasts();
17976            info.sendSystemPackageAppearedBroadcasts();
17977        }
17978        // Force a gc here.
17979        Runtime.getRuntime().gc();
17980        // Delete the resources here after sending the broadcast to let
17981        // other processes clean up before deleting resources.
17982        if (info.args != null) {
17983            synchronized (mInstallLock) {
17984                info.args.doPostDeleteLI(true);
17985            }
17986        }
17987
17988        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17989    }
17990
17991    static class PackageRemovedInfo {
17992        final PackageSender packageSender;
17993        String removedPackage;
17994        String installerPackageName;
17995        int uid = -1;
17996        int removedAppId = -1;
17997        int[] origUsers;
17998        int[] removedUsers = null;
17999        int[] broadcastUsers = null;
18000        int[] instantUserIds = null;
18001        SparseArray<Integer> installReasons;
18002        boolean isRemovedPackageSystemUpdate = false;
18003        boolean isUpdate;
18004        boolean dataRemoved;
18005        boolean removedForAllUsers;
18006        boolean isStaticSharedLib;
18007        // Clean up resources deleted packages.
18008        InstallArgs args = null;
18009        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18010        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18011
18012        PackageRemovedInfo(PackageSender packageSender) {
18013            this.packageSender = packageSender;
18014        }
18015
18016        void sendPackageRemovedBroadcasts(boolean killApp) {
18017            sendPackageRemovedBroadcastInternal(killApp);
18018            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18019            for (int i = 0; i < childCount; i++) {
18020                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18021                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18022            }
18023        }
18024
18025        void sendSystemPackageUpdatedBroadcasts() {
18026            if (isRemovedPackageSystemUpdate) {
18027                sendSystemPackageUpdatedBroadcastsInternal();
18028                final int childCount = (removedChildPackages != null)
18029                        ? removedChildPackages.size() : 0;
18030                for (int i = 0; i < childCount; i++) {
18031                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18032                    if (childInfo.isRemovedPackageSystemUpdate) {
18033                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18034                    }
18035                }
18036            }
18037        }
18038
18039        void sendSystemPackageAppearedBroadcasts() {
18040            final int packageCount = (appearedChildPackages != null)
18041                    ? appearedChildPackages.size() : 0;
18042            for (int i = 0; i < packageCount; i++) {
18043                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18044                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18045                    true /*sendBootCompleted*/, false /*startReceiver*/,
18046                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18047            }
18048        }
18049
18050        private void sendSystemPackageUpdatedBroadcastsInternal() {
18051            Bundle extras = new Bundle(2);
18052            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18053            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18054            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18055                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18056            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18057                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18058            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18059                null, null, 0, removedPackage, null, null, null);
18060            if (installerPackageName != null) {
18061                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18062                        removedPackage, extras, 0 /*flags*/,
18063                        installerPackageName, null, null, null);
18064                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18065                        removedPackage, extras, 0 /*flags*/,
18066                        installerPackageName, null, null, null);
18067            }
18068        }
18069
18070        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18071            // Don't send static shared library removal broadcasts as these
18072            // libs are visible only the the apps that depend on them an one
18073            // cannot remove the library if it has a dependency.
18074            if (isStaticSharedLib) {
18075                return;
18076            }
18077            Bundle extras = new Bundle(2);
18078            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18079            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18080            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18081            if (isUpdate || isRemovedPackageSystemUpdate) {
18082                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18083            }
18084            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18085            if (removedPackage != null) {
18086                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18087                    removedPackage, extras, 0, null /*targetPackage*/, null,
18088                    broadcastUsers, instantUserIds);
18089                if (installerPackageName != null) {
18090                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18091                            removedPackage, extras, 0 /*flags*/,
18092                            installerPackageName, null, broadcastUsers, instantUserIds);
18093                }
18094                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18095                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18096                        removedPackage, extras,
18097                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18098                        null, null, broadcastUsers, instantUserIds);
18099                    packageSender.notifyPackageRemoved(removedPackage);
18100                }
18101            }
18102            if (removedAppId >= 0) {
18103                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18104                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18105                    null, null, broadcastUsers, instantUserIds);
18106            }
18107        }
18108
18109        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18110            removedUsers = userIds;
18111            if (removedUsers == null) {
18112                broadcastUsers = null;
18113                return;
18114            }
18115
18116            broadcastUsers = EMPTY_INT_ARRAY;
18117            instantUserIds = EMPTY_INT_ARRAY;
18118            for (int i = userIds.length - 1; i >= 0; --i) {
18119                final int userId = userIds[i];
18120                if (deletedPackageSetting.getInstantApp(userId)) {
18121                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18122                } else {
18123                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18124                }
18125            }
18126        }
18127    }
18128
18129    /*
18130     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18131     * flag is not set, the data directory is removed as well.
18132     * make sure this flag is set for partially installed apps. If not its meaningless to
18133     * delete a partially installed application.
18134     */
18135    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18136            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18137        String packageName = ps.name;
18138        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18139        // Retrieve object to delete permissions for shared user later on
18140        final PackageParser.Package deletedPkg;
18141        final PackageSetting deletedPs;
18142        // reader
18143        synchronized (mPackages) {
18144            deletedPkg = mPackages.get(packageName);
18145            deletedPs = mSettings.mPackages.get(packageName);
18146            if (outInfo != null) {
18147                outInfo.removedPackage = packageName;
18148                outInfo.installerPackageName = ps.installerPackageName;
18149                outInfo.isStaticSharedLib = deletedPkg != null
18150                        && deletedPkg.staticSharedLibName != null;
18151                outInfo.populateUsers(deletedPs == null ? null
18152                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18153            }
18154        }
18155
18156        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18157
18158        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18159            final PackageParser.Package resolvedPkg;
18160            if (deletedPkg != null) {
18161                resolvedPkg = deletedPkg;
18162            } else {
18163                // We don't have a parsed package when it lives on an ejected
18164                // adopted storage device, so fake something together
18165                resolvedPkg = new PackageParser.Package(ps.name);
18166                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18167            }
18168            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18169                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18170            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18171            if (outInfo != null) {
18172                outInfo.dataRemoved = true;
18173            }
18174            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18175        }
18176
18177        int removedAppId = -1;
18178
18179        // writer
18180        synchronized (mPackages) {
18181            boolean installedStateChanged = false;
18182            if (deletedPs != null) {
18183                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18184                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18185                    clearDefaultBrowserIfNeeded(packageName);
18186                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18187                    removedAppId = mSettings.removePackageLPw(packageName);
18188                    if (outInfo != null) {
18189                        outInfo.removedAppId = removedAppId;
18190                    }
18191                    mPermissionManager.updatePermissions(
18192                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18193                    if (deletedPs.sharedUser != null) {
18194                        // Remove permissions associated with package. Since runtime
18195                        // permissions are per user we have to kill the removed package
18196                        // or packages running under the shared user of the removed
18197                        // package if revoking the permissions requested only by the removed
18198                        // package is successful and this causes a change in gids.
18199                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18200                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18201                                    userId);
18202                            if (userIdToKill == UserHandle.USER_ALL
18203                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18204                                // If gids changed for this user, kill all affected packages.
18205                                mHandler.post(new Runnable() {
18206                                    @Override
18207                                    public void run() {
18208                                        // This has to happen with no lock held.
18209                                        killApplication(deletedPs.name, deletedPs.appId,
18210                                                KILL_APP_REASON_GIDS_CHANGED);
18211                                    }
18212                                });
18213                                break;
18214                            }
18215                        }
18216                    }
18217                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18218                }
18219                // make sure to preserve per-user disabled state if this removal was just
18220                // a downgrade of a system app to the factory package
18221                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18222                    if (DEBUG_REMOVE) {
18223                        Slog.d(TAG, "Propagating install state across downgrade");
18224                    }
18225                    for (int userId : allUserHandles) {
18226                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18227                        if (DEBUG_REMOVE) {
18228                            Slog.d(TAG, "    user " + userId + " => " + installed);
18229                        }
18230                        if (installed != ps.getInstalled(userId)) {
18231                            installedStateChanged = true;
18232                        }
18233                        ps.setInstalled(installed, userId);
18234                    }
18235                }
18236            }
18237            // can downgrade to reader
18238            if (writeSettings) {
18239                // Save settings now
18240                mSettings.writeLPr();
18241            }
18242            if (installedStateChanged) {
18243                mSettings.writeKernelMappingLPr(ps);
18244            }
18245        }
18246        if (removedAppId != -1) {
18247            // A user ID was deleted here. Go through all users and remove it
18248            // from KeyStore.
18249            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18250        }
18251    }
18252
18253    static boolean locationIsPrivileged(String path) {
18254        try {
18255            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18256            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18257            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18258            return path.startsWith(privilegedAppDir.getCanonicalPath())
18259                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18260                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18261        } catch (IOException e) {
18262            Slog.e(TAG, "Unable to access code path " + path);
18263        }
18264        return false;
18265    }
18266
18267    static boolean locationIsOem(String path) {
18268        try {
18269            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18270        } catch (IOException e) {
18271            Slog.e(TAG, "Unable to access code path " + path);
18272        }
18273        return false;
18274    }
18275
18276    static boolean locationIsVendor(String path) {
18277        try {
18278            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18279        } catch (IOException e) {
18280            Slog.e(TAG, "Unable to access code path " + path);
18281        }
18282        return false;
18283    }
18284
18285    static boolean locationIsProduct(String path) {
18286        try {
18287            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18288        } catch (IOException e) {
18289            Slog.e(TAG, "Unable to access code path " + path);
18290        }
18291        return false;
18292    }
18293
18294    /*
18295     * Tries to delete system package.
18296     */
18297    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18298            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18299            boolean writeSettings) {
18300        if (deletedPs.parentPackageName != null) {
18301            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18302            return false;
18303        }
18304
18305        final boolean applyUserRestrictions
18306                = (allUserHandles != null) && (outInfo.origUsers != null);
18307        final PackageSetting disabledPs;
18308        // Confirm if the system package has been updated
18309        // An updated system app can be deleted. This will also have to restore
18310        // the system pkg from system partition
18311        // reader
18312        synchronized (mPackages) {
18313            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18314        }
18315
18316        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18317                + " disabledPs=" + disabledPs);
18318
18319        if (disabledPs == null) {
18320            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18321            return false;
18322        } else if (DEBUG_REMOVE) {
18323            Slog.d(TAG, "Deleting system pkg from data partition");
18324        }
18325
18326        if (DEBUG_REMOVE) {
18327            if (applyUserRestrictions) {
18328                Slog.d(TAG, "Remembering install states:");
18329                for (int userId : allUserHandles) {
18330                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18331                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18332                }
18333            }
18334        }
18335
18336        // Delete the updated package
18337        outInfo.isRemovedPackageSystemUpdate = true;
18338        if (outInfo.removedChildPackages != null) {
18339            final int childCount = (deletedPs.childPackageNames != null)
18340                    ? deletedPs.childPackageNames.size() : 0;
18341            for (int i = 0; i < childCount; i++) {
18342                String childPackageName = deletedPs.childPackageNames.get(i);
18343                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18344                        .contains(childPackageName)) {
18345                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18346                            childPackageName);
18347                    if (childInfo != null) {
18348                        childInfo.isRemovedPackageSystemUpdate = true;
18349                    }
18350                }
18351            }
18352        }
18353
18354        if (disabledPs.versionCode < deletedPs.versionCode) {
18355            // Delete data for downgrades
18356            flags &= ~PackageManager.DELETE_KEEP_DATA;
18357        } else {
18358            // Preserve data by setting flag
18359            flags |= PackageManager.DELETE_KEEP_DATA;
18360        }
18361
18362        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18363                outInfo, writeSettings, disabledPs.pkg);
18364        if (!ret) {
18365            return false;
18366        }
18367
18368        // writer
18369        synchronized (mPackages) {
18370            // NOTE: The system package always needs to be enabled; even if it's for
18371            // a compressed stub. If we don't, installing the system package fails
18372            // during scan [scanning checks the disabled packages]. We will reverse
18373            // this later, after we've "installed" the stub.
18374            // Reinstate the old system package
18375            enableSystemPackageLPw(disabledPs.pkg);
18376            // Remove any native libraries from the upgraded package.
18377            removeNativeBinariesLI(deletedPs);
18378        }
18379
18380        // Install the system package
18381        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18382        try {
18383            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18384                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18385        } catch (PackageManagerException e) {
18386            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18387                    + e.getMessage());
18388            return false;
18389        } finally {
18390            if (disabledPs.pkg.isStub) {
18391                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18392            }
18393        }
18394        return true;
18395    }
18396
18397    /**
18398     * Installs a package that's already on the system partition.
18399     */
18400    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18401            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18402            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18403                    throws PackageManagerException {
18404        @ParseFlags int parseFlags =
18405                mDefParseFlags
18406                | PackageParser.PARSE_MUST_BE_APK
18407                | PackageParser.PARSE_IS_SYSTEM_DIR;
18408        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18409        if (isPrivileged || locationIsPrivileged(codePathString)) {
18410            scanFlags |= SCAN_AS_PRIVILEGED;
18411        }
18412        if (locationIsOem(codePathString)) {
18413            scanFlags |= SCAN_AS_OEM;
18414        }
18415        if (locationIsVendor(codePathString)) {
18416            scanFlags |= SCAN_AS_VENDOR;
18417        }
18418        if (locationIsProduct(codePathString)) {
18419            scanFlags |= SCAN_AS_PRODUCT;
18420        }
18421
18422        final File codePath = new File(codePathString);
18423        final PackageParser.Package pkg =
18424                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18425
18426        try {
18427            // update shared libraries for the newly re-installed system package
18428            updateSharedLibrariesLPr(pkg, null);
18429        } catch (PackageManagerException e) {
18430            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18431        }
18432
18433        prepareAppDataAfterInstallLIF(pkg);
18434
18435        // writer
18436        synchronized (mPackages) {
18437            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18438
18439            // Propagate the permissions state as we do not want to drop on the floor
18440            // runtime permissions. The update permissions method below will take
18441            // care of removing obsolete permissions and grant install permissions.
18442            if (origPermissionState != null) {
18443                ps.getPermissionsState().copyFrom(origPermissionState);
18444            }
18445            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18446                    mPermissionCallback);
18447
18448            final boolean applyUserRestrictions
18449                    = (allUserHandles != null) && (origUserHandles != null);
18450            if (applyUserRestrictions) {
18451                boolean installedStateChanged = false;
18452                if (DEBUG_REMOVE) {
18453                    Slog.d(TAG, "Propagating install state across reinstall");
18454                }
18455                for (int userId : allUserHandles) {
18456                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18457                    if (DEBUG_REMOVE) {
18458                        Slog.d(TAG, "    user " + userId + " => " + installed);
18459                    }
18460                    if (installed != ps.getInstalled(userId)) {
18461                        installedStateChanged = true;
18462                    }
18463                    ps.setInstalled(installed, userId);
18464
18465                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18466                }
18467                // Regardless of writeSettings we need to ensure that this restriction
18468                // state propagation is persisted
18469                mSettings.writeAllUsersPackageRestrictionsLPr();
18470                if (installedStateChanged) {
18471                    mSettings.writeKernelMappingLPr(ps);
18472                }
18473            }
18474            // can downgrade to reader here
18475            if (writeSettings) {
18476                mSettings.writeLPr();
18477            }
18478        }
18479        return pkg;
18480    }
18481
18482    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18483            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18484            PackageRemovedInfo outInfo, boolean writeSettings,
18485            PackageParser.Package replacingPackage) {
18486        synchronized (mPackages) {
18487            if (outInfo != null) {
18488                outInfo.uid = ps.appId;
18489            }
18490
18491            if (outInfo != null && outInfo.removedChildPackages != null) {
18492                final int childCount = (ps.childPackageNames != null)
18493                        ? ps.childPackageNames.size() : 0;
18494                for (int i = 0; i < childCount; i++) {
18495                    String childPackageName = ps.childPackageNames.get(i);
18496                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18497                    if (childPs == null) {
18498                        return false;
18499                    }
18500                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18501                            childPackageName);
18502                    if (childInfo != null) {
18503                        childInfo.uid = childPs.appId;
18504                    }
18505                }
18506            }
18507        }
18508
18509        // Delete package data from internal structures and also remove data if flag is set
18510        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18511
18512        // Delete the child packages data
18513        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18514        for (int i = 0; i < childCount; i++) {
18515            PackageSetting childPs;
18516            synchronized (mPackages) {
18517                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18518            }
18519            if (childPs != null) {
18520                PackageRemovedInfo childOutInfo = (outInfo != null
18521                        && outInfo.removedChildPackages != null)
18522                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18523                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18524                        && (replacingPackage != null
18525                        && !replacingPackage.hasChildPackage(childPs.name))
18526                        ? flags & ~DELETE_KEEP_DATA : flags;
18527                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18528                        deleteFlags, writeSettings);
18529            }
18530        }
18531
18532        // Delete application code and resources only for parent packages
18533        if (ps.parentPackageName == null) {
18534            if (deleteCodeAndResources && (outInfo != null)) {
18535                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18536                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18537                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18538            }
18539        }
18540
18541        return true;
18542    }
18543
18544    @Override
18545    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18546            int userId) {
18547        mContext.enforceCallingOrSelfPermission(
18548                android.Manifest.permission.DELETE_PACKAGES, null);
18549        synchronized (mPackages) {
18550            // Cannot block uninstall of static shared libs as they are
18551            // considered a part of the using app (emulating static linking).
18552            // Also static libs are installed always on internal storage.
18553            PackageParser.Package pkg = mPackages.get(packageName);
18554            if (pkg != null && pkg.staticSharedLibName != null) {
18555                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18556                        + " providing static shared library: " + pkg.staticSharedLibName);
18557                return false;
18558            }
18559            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18560            mSettings.writePackageRestrictionsLPr(userId);
18561        }
18562        return true;
18563    }
18564
18565    @Override
18566    public boolean getBlockUninstallForUser(String packageName, int userId) {
18567        synchronized (mPackages) {
18568            final PackageSetting ps = mSettings.mPackages.get(packageName);
18569            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18570                return false;
18571            }
18572            return mSettings.getBlockUninstallLPr(userId, packageName);
18573        }
18574    }
18575
18576    @Override
18577    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18578        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18579        synchronized (mPackages) {
18580            PackageSetting ps = mSettings.mPackages.get(packageName);
18581            if (ps == null) {
18582                Log.w(TAG, "Package doesn't exist: " + packageName);
18583                return false;
18584            }
18585            if (systemUserApp) {
18586                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18587            } else {
18588                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18589            }
18590            mSettings.writeLPr();
18591        }
18592        return true;
18593    }
18594
18595    /*
18596     * This method handles package deletion in general
18597     */
18598    private boolean deletePackageLIF(String packageName, UserHandle user,
18599            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18600            PackageRemovedInfo outInfo, boolean writeSettings,
18601            PackageParser.Package replacingPackage) {
18602        if (packageName == null) {
18603            Slog.w(TAG, "Attempt to delete null packageName.");
18604            return false;
18605        }
18606
18607        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18608
18609        PackageSetting ps;
18610        synchronized (mPackages) {
18611            ps = mSettings.mPackages.get(packageName);
18612            if (ps == null) {
18613                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18614                return false;
18615            }
18616
18617            if (ps.parentPackageName != null && (!isSystemApp(ps)
18618                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18619                if (DEBUG_REMOVE) {
18620                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18621                            + ((user == null) ? UserHandle.USER_ALL : user));
18622                }
18623                final int removedUserId = (user != null) ? user.getIdentifier()
18624                        : UserHandle.USER_ALL;
18625                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18626                    return false;
18627                }
18628                markPackageUninstalledForUserLPw(ps, user);
18629                scheduleWritePackageRestrictionsLocked(user);
18630                return true;
18631            }
18632        }
18633
18634        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18635                && user.getIdentifier() != UserHandle.USER_ALL)) {
18636            // The caller is asking that the package only be deleted for a single
18637            // user.  To do this, we just mark its uninstalled state and delete
18638            // its data. If this is a system app, we only allow this to happen if
18639            // they have set the special DELETE_SYSTEM_APP which requests different
18640            // semantics than normal for uninstalling system apps.
18641            markPackageUninstalledForUserLPw(ps, user);
18642
18643            if (!isSystemApp(ps)) {
18644                // Do not uninstall the APK if an app should be cached
18645                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18646                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18647                    // Other user 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, "Still installed by other users");
18651                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18652                        return false;
18653                    }
18654                    scheduleWritePackageRestrictionsLocked(user);
18655                    return true;
18656                } else {
18657                    // We need to set it back to 'installed' so the uninstall
18658                    // broadcasts will be sent correctly.
18659                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18660                    ps.setInstalled(true, user.getIdentifier());
18661                    mSettings.writeKernelMappingLPr(ps);
18662                }
18663            } else {
18664                // This is a system app, so we assume that the
18665                // other users still have this package installed, so all
18666                // we need to do is clear this user's data and save that
18667                // it is uninstalled.
18668                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18669                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18670                    return false;
18671                }
18672                scheduleWritePackageRestrictionsLocked(user);
18673                return true;
18674            }
18675        }
18676
18677        // If we are deleting a composite package for all users, keep track
18678        // of result for each child.
18679        if (ps.childPackageNames != null && outInfo != null) {
18680            synchronized (mPackages) {
18681                final int childCount = ps.childPackageNames.size();
18682                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18683                for (int i = 0; i < childCount; i++) {
18684                    String childPackageName = ps.childPackageNames.get(i);
18685                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18686                    childInfo.removedPackage = childPackageName;
18687                    childInfo.installerPackageName = ps.installerPackageName;
18688                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18689                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18690                    if (childPs != null) {
18691                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18692                    }
18693                }
18694            }
18695        }
18696
18697        boolean ret = false;
18698        if (isSystemApp(ps)) {
18699            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18700            // When an updated system application is deleted we delete the existing resources
18701            // as well and fall back to existing code in system partition
18702            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18703        } else {
18704            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18705            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18706                    outInfo, writeSettings, replacingPackage);
18707        }
18708
18709        // Take a note whether we deleted the package for all users
18710        if (outInfo != null) {
18711            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18712            if (outInfo.removedChildPackages != null) {
18713                synchronized (mPackages) {
18714                    final int childCount = outInfo.removedChildPackages.size();
18715                    for (int i = 0; i < childCount; i++) {
18716                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18717                        if (childInfo != null) {
18718                            childInfo.removedForAllUsers = mPackages.get(
18719                                    childInfo.removedPackage) == null;
18720                        }
18721                    }
18722                }
18723            }
18724            // If we uninstalled an update to a system app there may be some
18725            // child packages that appeared as they are declared in the system
18726            // app but were not declared in the update.
18727            if (isSystemApp(ps)) {
18728                synchronized (mPackages) {
18729                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18730                    final int childCount = (updatedPs.childPackageNames != null)
18731                            ? updatedPs.childPackageNames.size() : 0;
18732                    for (int i = 0; i < childCount; i++) {
18733                        String childPackageName = updatedPs.childPackageNames.get(i);
18734                        if (outInfo.removedChildPackages == null
18735                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18736                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18737                            if (childPs == null) {
18738                                continue;
18739                            }
18740                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18741                            installRes.name = childPackageName;
18742                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18743                            installRes.pkg = mPackages.get(childPackageName);
18744                            installRes.uid = childPs.pkg.applicationInfo.uid;
18745                            if (outInfo.appearedChildPackages == null) {
18746                                outInfo.appearedChildPackages = new ArrayMap<>();
18747                            }
18748                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18749                        }
18750                    }
18751                }
18752            }
18753        }
18754
18755        return ret;
18756    }
18757
18758    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18759        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18760                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18761        for (int nextUserId : userIds) {
18762            if (DEBUG_REMOVE) {
18763                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18764            }
18765            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18766                    false /*installed*/,
18767                    true /*stopped*/,
18768                    true /*notLaunched*/,
18769                    false /*hidden*/,
18770                    false /*suspended*/,
18771                    false /*instantApp*/,
18772                    false /*virtualPreload*/,
18773                    null /*lastDisableAppCaller*/,
18774                    null /*enabledComponents*/,
18775                    null /*disabledComponents*/,
18776                    ps.readUserState(nextUserId).domainVerificationStatus,
18777                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18778                    null /*harmfulAppWarning*/);
18779        }
18780        mSettings.writeKernelMappingLPr(ps);
18781    }
18782
18783    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18784            PackageRemovedInfo outInfo) {
18785        final PackageParser.Package pkg;
18786        synchronized (mPackages) {
18787            pkg = mPackages.get(ps.name);
18788        }
18789
18790        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18791                : new int[] {userId};
18792        for (int nextUserId : userIds) {
18793            if (DEBUG_REMOVE) {
18794                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18795                        + nextUserId);
18796            }
18797
18798            destroyAppDataLIF(pkg, userId,
18799                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18800            destroyAppProfilesLIF(pkg, userId);
18801            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18802            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18803            schedulePackageCleaning(ps.name, nextUserId, false);
18804            synchronized (mPackages) {
18805                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18806                    scheduleWritePackageRestrictionsLocked(nextUserId);
18807                }
18808                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18809            }
18810        }
18811
18812        if (outInfo != null) {
18813            outInfo.removedPackage = ps.name;
18814            outInfo.installerPackageName = ps.installerPackageName;
18815            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18816            outInfo.removedAppId = ps.appId;
18817            outInfo.removedUsers = userIds;
18818            outInfo.broadcastUsers = userIds;
18819        }
18820
18821        return true;
18822    }
18823
18824    private final class ClearStorageConnection implements ServiceConnection {
18825        IMediaContainerService mContainerService;
18826
18827        @Override
18828        public void onServiceConnected(ComponentName name, IBinder service) {
18829            synchronized (this) {
18830                mContainerService = IMediaContainerService.Stub
18831                        .asInterface(Binder.allowBlocking(service));
18832                notifyAll();
18833            }
18834        }
18835
18836        @Override
18837        public void onServiceDisconnected(ComponentName name) {
18838        }
18839    }
18840
18841    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18842        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18843
18844        final boolean mounted;
18845        if (Environment.isExternalStorageEmulated()) {
18846            mounted = true;
18847        } else {
18848            final String status = Environment.getExternalStorageState();
18849
18850            mounted = status.equals(Environment.MEDIA_MOUNTED)
18851                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18852        }
18853
18854        if (!mounted) {
18855            return;
18856        }
18857
18858        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18859        int[] users;
18860        if (userId == UserHandle.USER_ALL) {
18861            users = sUserManager.getUserIds();
18862        } else {
18863            users = new int[] { userId };
18864        }
18865        final ClearStorageConnection conn = new ClearStorageConnection();
18866        if (mContext.bindServiceAsUser(
18867                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18868            try {
18869                for (int curUser : users) {
18870                    long timeout = SystemClock.uptimeMillis() + 5000;
18871                    synchronized (conn) {
18872                        long now;
18873                        while (conn.mContainerService == null &&
18874                                (now = SystemClock.uptimeMillis()) < timeout) {
18875                            try {
18876                                conn.wait(timeout - now);
18877                            } catch (InterruptedException e) {
18878                            }
18879                        }
18880                    }
18881                    if (conn.mContainerService == null) {
18882                        return;
18883                    }
18884
18885                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18886                    clearDirectory(conn.mContainerService,
18887                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18888                    if (allData) {
18889                        clearDirectory(conn.mContainerService,
18890                                userEnv.buildExternalStorageAppDataDirs(packageName));
18891                        clearDirectory(conn.mContainerService,
18892                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18893                    }
18894                }
18895            } finally {
18896                mContext.unbindService(conn);
18897            }
18898        }
18899    }
18900
18901    @Override
18902    public void clearApplicationProfileData(String packageName) {
18903        enforceSystemOrRoot("Only the system can clear all profile data");
18904
18905        final PackageParser.Package pkg;
18906        synchronized (mPackages) {
18907            pkg = mPackages.get(packageName);
18908        }
18909
18910        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18911            synchronized (mInstallLock) {
18912                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18913            }
18914        }
18915    }
18916
18917    @Override
18918    public void clearApplicationUserData(final String packageName,
18919            final IPackageDataObserver observer, final int userId) {
18920        mContext.enforceCallingOrSelfPermission(
18921                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18922
18923        final int callingUid = Binder.getCallingUid();
18924        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18925                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18926
18927        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18928        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18929        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18930            throw new SecurityException("Cannot clear data for a protected package: "
18931                    + packageName);
18932        }
18933        // Queue up an async operation since the package deletion may take a little while.
18934        mHandler.post(new Runnable() {
18935            public void run() {
18936                mHandler.removeCallbacks(this);
18937                final boolean succeeded;
18938                if (!filterApp) {
18939                    try (PackageFreezer freezer = freezePackage(packageName,
18940                            "clearApplicationUserData")) {
18941                        synchronized (mInstallLock) {
18942                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18943                        }
18944                        clearExternalStorageDataSync(packageName, userId, true);
18945                        synchronized (mPackages) {
18946                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18947                                    packageName, userId);
18948                        }
18949                    }
18950                    if (succeeded) {
18951                        // invoke DeviceStorageMonitor's update method to clear any notifications
18952                        DeviceStorageMonitorInternal dsm = LocalServices
18953                                .getService(DeviceStorageMonitorInternal.class);
18954                        if (dsm != null) {
18955                            dsm.checkMemory();
18956                        }
18957                    }
18958                } else {
18959                    succeeded = false;
18960                }
18961                if (observer != null) {
18962                    try {
18963                        observer.onRemoveCompleted(packageName, succeeded);
18964                    } catch (RemoteException e) {
18965                        Log.i(TAG, "Observer no longer exists.");
18966                    }
18967                } //end if observer
18968            } //end run
18969        });
18970    }
18971
18972    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18973        if (packageName == null) {
18974            Slog.w(TAG, "Attempt to delete null packageName.");
18975            return false;
18976        }
18977
18978        // Try finding details about the requested package
18979        PackageParser.Package pkg;
18980        synchronized (mPackages) {
18981            pkg = mPackages.get(packageName);
18982            if (pkg == null) {
18983                final PackageSetting ps = mSettings.mPackages.get(packageName);
18984                if (ps != null) {
18985                    pkg = ps.pkg;
18986                }
18987            }
18988
18989            if (pkg == null) {
18990                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18991                return false;
18992            }
18993
18994            PackageSetting ps = (PackageSetting) pkg.mExtras;
18995            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18996        }
18997
18998        clearAppDataLIF(pkg, userId,
18999                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19000
19001        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19002        removeKeystoreDataIfNeeded(userId, appId);
19003
19004        UserManagerInternal umInternal = getUserManagerInternal();
19005        final int flags;
19006        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19007            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19008        } else if (umInternal.isUserRunning(userId)) {
19009            flags = StorageManager.FLAG_STORAGE_DE;
19010        } else {
19011            flags = 0;
19012        }
19013        prepareAppDataContentsLIF(pkg, userId, flags);
19014
19015        return true;
19016    }
19017
19018    /**
19019     * Reverts user permission state changes (permissions and flags) in
19020     * all packages for a given user.
19021     *
19022     * @param userId The device user for which to do a reset.
19023     */
19024    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19025        final int packageCount = mPackages.size();
19026        for (int i = 0; i < packageCount; i++) {
19027            PackageParser.Package pkg = mPackages.valueAt(i);
19028            PackageSetting ps = (PackageSetting) pkg.mExtras;
19029            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19030        }
19031    }
19032
19033    private void resetNetworkPolicies(int userId) {
19034        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19035    }
19036
19037    /**
19038     * Reverts user permission state changes (permissions and flags).
19039     *
19040     * @param ps The package for which to reset.
19041     * @param userId The device user for which to do a reset.
19042     */
19043    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19044            final PackageSetting ps, final int userId) {
19045        if (ps.pkg == null) {
19046            return;
19047        }
19048
19049        // These are flags that can change base on user actions.
19050        final int userSettableMask = FLAG_PERMISSION_USER_SET
19051                | FLAG_PERMISSION_USER_FIXED
19052                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19053                | FLAG_PERMISSION_REVIEW_REQUIRED;
19054
19055        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19056                | FLAG_PERMISSION_POLICY_FIXED;
19057
19058        boolean writeInstallPermissions = false;
19059        boolean writeRuntimePermissions = false;
19060
19061        final int permissionCount = ps.pkg.requestedPermissions.size();
19062        for (int i = 0; i < permissionCount; i++) {
19063            final String permName = ps.pkg.requestedPermissions.get(i);
19064            final BasePermission bp =
19065                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19066            if (bp == null) {
19067                continue;
19068            }
19069
19070            // If shared user we just reset the state to which only this app contributed.
19071            if (ps.sharedUser != null) {
19072                boolean used = false;
19073                final int packageCount = ps.sharedUser.packages.size();
19074                for (int j = 0; j < packageCount; j++) {
19075                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19076                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19077                            && pkg.pkg.requestedPermissions.contains(permName)) {
19078                        used = true;
19079                        break;
19080                    }
19081                }
19082                if (used) {
19083                    continue;
19084                }
19085            }
19086
19087            final PermissionsState permissionsState = ps.getPermissionsState();
19088
19089            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19090
19091            // Always clear the user settable flags.
19092            final boolean hasInstallState =
19093                    permissionsState.getInstallPermissionState(permName) != null;
19094            // If permission review is enabled and this is a legacy app, mark the
19095            // permission as requiring a review as this is the initial state.
19096            int flags = 0;
19097            if (mSettings.mPermissions.mPermissionReviewRequired
19098                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19099                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19100            }
19101            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19102                if (hasInstallState) {
19103                    writeInstallPermissions = true;
19104                } else {
19105                    writeRuntimePermissions = true;
19106                }
19107            }
19108
19109            // Below is only runtime permission handling.
19110            if (!bp.isRuntime()) {
19111                continue;
19112            }
19113
19114            // Never clobber system or policy.
19115            if ((oldFlags & policyOrSystemFlags) != 0) {
19116                continue;
19117            }
19118
19119            // If this permission was granted by default, make sure it is.
19120            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19121                if (permissionsState.grantRuntimePermission(bp, userId)
19122                        != PERMISSION_OPERATION_FAILURE) {
19123                    writeRuntimePermissions = true;
19124                }
19125            // If permission review is enabled the permissions for a legacy apps
19126            // are represented as constantly granted runtime ones, so don't revoke.
19127            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19128                // Otherwise, reset the permission.
19129                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19130                switch (revokeResult) {
19131                    case PERMISSION_OPERATION_SUCCESS:
19132                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19133                        writeRuntimePermissions = true;
19134                        final int appId = ps.appId;
19135                        mHandler.post(new Runnable() {
19136                            @Override
19137                            public void run() {
19138                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19139                            }
19140                        });
19141                    } break;
19142                }
19143            }
19144        }
19145
19146        // Synchronously write as we are taking permissions away.
19147        if (writeRuntimePermissions) {
19148            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19149        }
19150
19151        // Synchronously write as we are taking permissions away.
19152        if (writeInstallPermissions) {
19153            mSettings.writeLPr();
19154        }
19155    }
19156
19157    /**
19158     * Remove entries from the keystore daemon. Will only remove it if the
19159     * {@code appId} is valid.
19160     */
19161    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19162        if (appId < 0) {
19163            return;
19164        }
19165
19166        final KeyStore keyStore = KeyStore.getInstance();
19167        if (keyStore != null) {
19168            if (userId == UserHandle.USER_ALL) {
19169                for (final int individual : sUserManager.getUserIds()) {
19170                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19171                }
19172            } else {
19173                keyStore.clearUid(UserHandle.getUid(userId, appId));
19174            }
19175        } else {
19176            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19177        }
19178    }
19179
19180    @Override
19181    public void deleteApplicationCacheFiles(final String packageName,
19182            final IPackageDataObserver observer) {
19183        final int userId = UserHandle.getCallingUserId();
19184        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19185    }
19186
19187    @Override
19188    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19189            final IPackageDataObserver observer) {
19190        final int callingUid = Binder.getCallingUid();
19191        mContext.enforceCallingOrSelfPermission(
19192                android.Manifest.permission.DELETE_CACHE_FILES, null);
19193        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19194                /* requireFullPermission= */ true, /* checkShell= */ false,
19195                "delete application cache files");
19196        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19197                android.Manifest.permission.ACCESS_INSTANT_APPS);
19198
19199        final PackageParser.Package pkg;
19200        synchronized (mPackages) {
19201            pkg = mPackages.get(packageName);
19202        }
19203
19204        // Queue up an async operation since the package deletion may take a little while.
19205        mHandler.post(new Runnable() {
19206            public void run() {
19207                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19208                boolean doClearData = true;
19209                if (ps != null) {
19210                    final boolean targetIsInstantApp =
19211                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19212                    doClearData = !targetIsInstantApp
19213                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19214                }
19215                if (doClearData) {
19216                    synchronized (mInstallLock) {
19217                        final int flags = StorageManager.FLAG_STORAGE_DE
19218                                | StorageManager.FLAG_STORAGE_CE;
19219                        // We're only clearing cache files, so we don't care if the
19220                        // app is unfrozen and still able to run
19221                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19222                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19223                    }
19224                    clearExternalStorageDataSync(packageName, userId, false);
19225                }
19226                if (observer != null) {
19227                    try {
19228                        observer.onRemoveCompleted(packageName, true);
19229                    } catch (RemoteException e) {
19230                        Log.i(TAG, "Observer no longer exists.");
19231                    }
19232                }
19233            }
19234        });
19235    }
19236
19237    @Override
19238    public void getPackageSizeInfo(final String packageName, int userHandle,
19239            final IPackageStatsObserver observer) {
19240        throw new UnsupportedOperationException(
19241                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19242    }
19243
19244    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19245        final PackageSetting ps;
19246        synchronized (mPackages) {
19247            ps = mSettings.mPackages.get(packageName);
19248            if (ps == null) {
19249                Slog.w(TAG, "Failed to find settings for " + packageName);
19250                return false;
19251            }
19252        }
19253
19254        final String[] packageNames = { packageName };
19255        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19256        final String[] codePaths = { ps.codePathString };
19257
19258        try {
19259            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19260                    ps.appId, ceDataInodes, codePaths, stats);
19261
19262            // For now, ignore code size of packages on system partition
19263            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19264                stats.codeSize = 0;
19265            }
19266
19267            // External clients expect these to be tracked separately
19268            stats.dataSize -= stats.cacheSize;
19269
19270        } catch (InstallerException e) {
19271            Slog.w(TAG, String.valueOf(e));
19272            return false;
19273        }
19274
19275        return true;
19276    }
19277
19278    private int getUidTargetSdkVersionLockedLPr(int uid) {
19279        Object obj = mSettings.getUserIdLPr(uid);
19280        if (obj instanceof SharedUserSetting) {
19281            final SharedUserSetting sus = (SharedUserSetting) obj;
19282            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19283            final Iterator<PackageSetting> it = sus.packages.iterator();
19284            while (it.hasNext()) {
19285                final PackageSetting ps = it.next();
19286                if (ps.pkg != null) {
19287                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19288                    if (v < vers) vers = v;
19289                }
19290            }
19291            return vers;
19292        } else if (obj instanceof PackageSetting) {
19293            final PackageSetting ps = (PackageSetting) obj;
19294            if (ps.pkg != null) {
19295                return ps.pkg.applicationInfo.targetSdkVersion;
19296            }
19297        }
19298        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19299    }
19300
19301    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19302        final PackageParser.Package p = mPackages.get(packageName);
19303        if (p != null) {
19304            return p.applicationInfo.targetSdkVersion;
19305        }
19306        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19307    }
19308
19309    @Override
19310    public void addPreferredActivity(IntentFilter filter, int match,
19311            ComponentName[] set, ComponentName activity, int userId) {
19312        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19313                "Adding preferred");
19314    }
19315
19316    private void addPreferredActivityInternal(IntentFilter filter, int match,
19317            ComponentName[] set, ComponentName activity, boolean always, int userId,
19318            String opname) {
19319        // writer
19320        int callingUid = Binder.getCallingUid();
19321        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19322                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19323        if (filter.countActions() == 0) {
19324            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19325            return;
19326        }
19327        synchronized (mPackages) {
19328            if (mContext.checkCallingOrSelfPermission(
19329                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19330                    != PackageManager.PERMISSION_GRANTED) {
19331                if (getUidTargetSdkVersionLockedLPr(callingUid)
19332                        < Build.VERSION_CODES.FROYO) {
19333                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19334                            + callingUid);
19335                    return;
19336                }
19337                mContext.enforceCallingOrSelfPermission(
19338                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19339            }
19340
19341            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19342            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19343                    + userId + ":");
19344            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19345            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19346            scheduleWritePackageRestrictionsLocked(userId);
19347            postPreferredActivityChangedBroadcast(userId);
19348        }
19349    }
19350
19351    private void postPreferredActivityChangedBroadcast(int userId) {
19352        mHandler.post(() -> {
19353            final IActivityManager am = ActivityManager.getService();
19354            if (am == null) {
19355                return;
19356            }
19357
19358            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19359            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19360            try {
19361                am.broadcastIntent(null, intent, null, null,
19362                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19363                        null, false, false, userId);
19364            } catch (RemoteException e) {
19365            }
19366        });
19367    }
19368
19369    @Override
19370    public void replacePreferredActivity(IntentFilter filter, int match,
19371            ComponentName[] set, ComponentName activity, int userId) {
19372        if (filter.countActions() != 1) {
19373            throw new IllegalArgumentException(
19374                    "replacePreferredActivity expects filter to have only 1 action.");
19375        }
19376        if (filter.countDataAuthorities() != 0
19377                || filter.countDataPaths() != 0
19378                || filter.countDataSchemes() > 1
19379                || filter.countDataTypes() != 0) {
19380            throw new IllegalArgumentException(
19381                    "replacePreferredActivity expects filter to have no data authorities, " +
19382                    "paths, or types; and at most one scheme.");
19383        }
19384
19385        final int callingUid = Binder.getCallingUid();
19386        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19387                true /* requireFullPermission */, false /* checkShell */,
19388                "replace preferred activity");
19389        synchronized (mPackages) {
19390            if (mContext.checkCallingOrSelfPermission(
19391                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19392                    != PackageManager.PERMISSION_GRANTED) {
19393                if (getUidTargetSdkVersionLockedLPr(callingUid)
19394                        < Build.VERSION_CODES.FROYO) {
19395                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19396                            + Binder.getCallingUid());
19397                    return;
19398                }
19399                mContext.enforceCallingOrSelfPermission(
19400                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19401            }
19402
19403            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19404            if (pir != null) {
19405                // Get all of the existing entries that exactly match this filter.
19406                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19407                if (existing != null && existing.size() == 1) {
19408                    PreferredActivity cur = existing.get(0);
19409                    if (DEBUG_PREFERRED) {
19410                        Slog.i(TAG, "Checking replace of preferred:");
19411                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19412                        if (!cur.mPref.mAlways) {
19413                            Slog.i(TAG, "  -- CUR; not mAlways!");
19414                        } else {
19415                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19416                            Slog.i(TAG, "  -- CUR: mSet="
19417                                    + Arrays.toString(cur.mPref.mSetComponents));
19418                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19419                            Slog.i(TAG, "  -- NEW: mMatch="
19420                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19421                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19422                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19423                        }
19424                    }
19425                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19426                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19427                            && cur.mPref.sameSet(set)) {
19428                        // Setting the preferred activity to what it happens to be already
19429                        if (DEBUG_PREFERRED) {
19430                            Slog.i(TAG, "Replacing with same preferred activity "
19431                                    + cur.mPref.mShortComponent + " for user "
19432                                    + userId + ":");
19433                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19434                        }
19435                        return;
19436                    }
19437                }
19438
19439                if (existing != null) {
19440                    if (DEBUG_PREFERRED) {
19441                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19442                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19443                    }
19444                    for (int i = 0; i < existing.size(); i++) {
19445                        PreferredActivity pa = existing.get(i);
19446                        if (DEBUG_PREFERRED) {
19447                            Slog.i(TAG, "Removing existing preferred activity "
19448                                    + pa.mPref.mComponent + ":");
19449                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19450                        }
19451                        pir.removeFilter(pa);
19452                    }
19453                }
19454            }
19455            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19456                    "Replacing preferred");
19457        }
19458    }
19459
19460    @Override
19461    public void clearPackagePreferredActivities(String packageName) {
19462        final int callingUid = Binder.getCallingUid();
19463        if (getInstantAppPackageName(callingUid) != null) {
19464            return;
19465        }
19466        // writer
19467        synchronized (mPackages) {
19468            PackageParser.Package pkg = mPackages.get(packageName);
19469            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19470                if (mContext.checkCallingOrSelfPermission(
19471                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19472                        != PackageManager.PERMISSION_GRANTED) {
19473                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19474                            < Build.VERSION_CODES.FROYO) {
19475                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19476                                + callingUid);
19477                        return;
19478                    }
19479                    mContext.enforceCallingOrSelfPermission(
19480                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19481                }
19482            }
19483            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19484            if (ps != null
19485                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19486                return;
19487            }
19488            int user = UserHandle.getCallingUserId();
19489            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19490                scheduleWritePackageRestrictionsLocked(user);
19491            }
19492        }
19493    }
19494
19495    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19496    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19497        ArrayList<PreferredActivity> removed = null;
19498        boolean changed = false;
19499        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19500            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19501            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19502            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19503                continue;
19504            }
19505            Iterator<PreferredActivity> it = pir.filterIterator();
19506            while (it.hasNext()) {
19507                PreferredActivity pa = it.next();
19508                // Mark entry for removal only if it matches the package name
19509                // and the entry is of type "always".
19510                if (packageName == null ||
19511                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19512                                && pa.mPref.mAlways)) {
19513                    if (removed == null) {
19514                        removed = new ArrayList<PreferredActivity>();
19515                    }
19516                    removed.add(pa);
19517                }
19518            }
19519            if (removed != null) {
19520                for (int j=0; j<removed.size(); j++) {
19521                    PreferredActivity pa = removed.get(j);
19522                    pir.removeFilter(pa);
19523                }
19524                changed = true;
19525            }
19526        }
19527        if (changed) {
19528            postPreferredActivityChangedBroadcast(userId);
19529        }
19530        return changed;
19531    }
19532
19533    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19534    private void clearIntentFilterVerificationsLPw(int userId) {
19535        final int packageCount = mPackages.size();
19536        for (int i = 0; i < packageCount; i++) {
19537            PackageParser.Package pkg = mPackages.valueAt(i);
19538            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19539        }
19540    }
19541
19542    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19543    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19544        if (userId == UserHandle.USER_ALL) {
19545            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19546                    sUserManager.getUserIds())) {
19547                for (int oneUserId : sUserManager.getUserIds()) {
19548                    scheduleWritePackageRestrictionsLocked(oneUserId);
19549                }
19550            }
19551        } else {
19552            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19553                scheduleWritePackageRestrictionsLocked(userId);
19554            }
19555        }
19556    }
19557
19558    /** Clears state for all users, and touches intent filter verification policy */
19559    void clearDefaultBrowserIfNeeded(String packageName) {
19560        for (int oneUserId : sUserManager.getUserIds()) {
19561            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19562        }
19563    }
19564
19565    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19566        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19567        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19568            if (packageName.equals(defaultBrowserPackageName)) {
19569                setDefaultBrowserPackageName(null, userId);
19570            }
19571        }
19572    }
19573
19574    @Override
19575    public void resetApplicationPreferences(int userId) {
19576        mContext.enforceCallingOrSelfPermission(
19577                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19578        final long identity = Binder.clearCallingIdentity();
19579        // writer
19580        try {
19581            synchronized (mPackages) {
19582                clearPackagePreferredActivitiesLPw(null, userId);
19583                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19584                // TODO: We have to reset the default SMS and Phone. This requires
19585                // significant refactoring to keep all default apps in the package
19586                // manager (cleaner but more work) or have the services provide
19587                // callbacks to the package manager to request a default app reset.
19588                applyFactoryDefaultBrowserLPw(userId);
19589                clearIntentFilterVerificationsLPw(userId);
19590                primeDomainVerificationsLPw(userId);
19591                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19592                scheduleWritePackageRestrictionsLocked(userId);
19593            }
19594            resetNetworkPolicies(userId);
19595        } finally {
19596            Binder.restoreCallingIdentity(identity);
19597        }
19598    }
19599
19600    @Override
19601    public int getPreferredActivities(List<IntentFilter> outFilters,
19602            List<ComponentName> outActivities, String packageName) {
19603        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19604            return 0;
19605        }
19606        int num = 0;
19607        final int userId = UserHandle.getCallingUserId();
19608        // reader
19609        synchronized (mPackages) {
19610            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19611            if (pir != null) {
19612                final Iterator<PreferredActivity> it = pir.filterIterator();
19613                while (it.hasNext()) {
19614                    final PreferredActivity pa = it.next();
19615                    if (packageName == null
19616                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19617                                    && pa.mPref.mAlways)) {
19618                        if (outFilters != null) {
19619                            outFilters.add(new IntentFilter(pa));
19620                        }
19621                        if (outActivities != null) {
19622                            outActivities.add(pa.mPref.mComponent);
19623                        }
19624                    }
19625                }
19626            }
19627        }
19628
19629        return num;
19630    }
19631
19632    @Override
19633    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19634            int userId) {
19635        int callingUid = Binder.getCallingUid();
19636        if (callingUid != Process.SYSTEM_UID) {
19637            throw new SecurityException(
19638                    "addPersistentPreferredActivity can only be run by the system");
19639        }
19640        if (filter.countActions() == 0) {
19641            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19642            return;
19643        }
19644        synchronized (mPackages) {
19645            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19646                    ":");
19647            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19648            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19649                    new PersistentPreferredActivity(filter, activity));
19650            scheduleWritePackageRestrictionsLocked(userId);
19651            postPreferredActivityChangedBroadcast(userId);
19652        }
19653    }
19654
19655    @Override
19656    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19657        int callingUid = Binder.getCallingUid();
19658        if (callingUid != Process.SYSTEM_UID) {
19659            throw new SecurityException(
19660                    "clearPackagePersistentPreferredActivities can only be run by the system");
19661        }
19662        ArrayList<PersistentPreferredActivity> removed = null;
19663        boolean changed = false;
19664        synchronized (mPackages) {
19665            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19666                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19667                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19668                        .valueAt(i);
19669                if (userId != thisUserId) {
19670                    continue;
19671                }
19672                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19673                while (it.hasNext()) {
19674                    PersistentPreferredActivity ppa = it.next();
19675                    // Mark entry for removal only if it matches the package name.
19676                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19677                        if (removed == null) {
19678                            removed = new ArrayList<PersistentPreferredActivity>();
19679                        }
19680                        removed.add(ppa);
19681                    }
19682                }
19683                if (removed != null) {
19684                    for (int j=0; j<removed.size(); j++) {
19685                        PersistentPreferredActivity ppa = removed.get(j);
19686                        ppir.removeFilter(ppa);
19687                    }
19688                    changed = true;
19689                }
19690            }
19691
19692            if (changed) {
19693                scheduleWritePackageRestrictionsLocked(userId);
19694                postPreferredActivityChangedBroadcast(userId);
19695            }
19696        }
19697    }
19698
19699    /**
19700     * Common machinery for picking apart a restored XML blob and passing
19701     * it to a caller-supplied functor to be applied to the running system.
19702     */
19703    private void restoreFromXml(XmlPullParser parser, int userId,
19704            String expectedStartTag, BlobXmlRestorer functor)
19705            throws IOException, XmlPullParserException {
19706        int type;
19707        while ((type = parser.next()) != XmlPullParser.START_TAG
19708                && type != XmlPullParser.END_DOCUMENT) {
19709        }
19710        if (type != XmlPullParser.START_TAG) {
19711            // oops didn't find a start tag?!
19712            if (DEBUG_BACKUP) {
19713                Slog.e(TAG, "Didn't find start tag during restore");
19714            }
19715            return;
19716        }
19717Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19718        // this is supposed to be TAG_PREFERRED_BACKUP
19719        if (!expectedStartTag.equals(parser.getName())) {
19720            if (DEBUG_BACKUP) {
19721                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19722            }
19723            return;
19724        }
19725
19726        // skip interfering stuff, then we're aligned with the backing implementation
19727        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19728Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19729        functor.apply(parser, userId);
19730    }
19731
19732    private interface BlobXmlRestorer {
19733        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19734    }
19735
19736    /**
19737     * Non-Binder method, support for the backup/restore mechanism: write the
19738     * full set of preferred activities in its canonical XML format.  Returns the
19739     * XML output as a byte array, or null if there is none.
19740     */
19741    @Override
19742    public byte[] getPreferredActivityBackup(int userId) {
19743        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19744            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19745        }
19746
19747        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19748        try {
19749            final XmlSerializer serializer = new FastXmlSerializer();
19750            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19751            serializer.startDocument(null, true);
19752            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19753
19754            synchronized (mPackages) {
19755                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19756            }
19757
19758            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19759            serializer.endDocument();
19760            serializer.flush();
19761        } catch (Exception e) {
19762            if (DEBUG_BACKUP) {
19763                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19764            }
19765            return null;
19766        }
19767
19768        return dataStream.toByteArray();
19769    }
19770
19771    @Override
19772    public void restorePreferredActivities(byte[] backup, int userId) {
19773        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19774            throw new SecurityException("Only the system may call restorePreferredActivities()");
19775        }
19776
19777        try {
19778            final XmlPullParser parser = Xml.newPullParser();
19779            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19780            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19781                    new BlobXmlRestorer() {
19782                        @Override
19783                        public void apply(XmlPullParser parser, int userId)
19784                                throws XmlPullParserException, IOException {
19785                            synchronized (mPackages) {
19786                                mSettings.readPreferredActivitiesLPw(parser, userId);
19787                            }
19788                        }
19789                    } );
19790        } catch (Exception e) {
19791            if (DEBUG_BACKUP) {
19792                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19793            }
19794        }
19795    }
19796
19797    /**
19798     * Non-Binder method, support for the backup/restore mechanism: write the
19799     * default browser (etc) settings in its canonical XML format.  Returns the default
19800     * browser XML representation as a byte array, or null if there is none.
19801     */
19802    @Override
19803    public byte[] getDefaultAppsBackup(int userId) {
19804        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19805            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19806        }
19807
19808        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19809        try {
19810            final XmlSerializer serializer = new FastXmlSerializer();
19811            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19812            serializer.startDocument(null, true);
19813            serializer.startTag(null, TAG_DEFAULT_APPS);
19814
19815            synchronized (mPackages) {
19816                mSettings.writeDefaultAppsLPr(serializer, userId);
19817            }
19818
19819            serializer.endTag(null, TAG_DEFAULT_APPS);
19820            serializer.endDocument();
19821            serializer.flush();
19822        } catch (Exception e) {
19823            if (DEBUG_BACKUP) {
19824                Slog.e(TAG, "Unable to write default apps for backup", e);
19825            }
19826            return null;
19827        }
19828
19829        return dataStream.toByteArray();
19830    }
19831
19832    @Override
19833    public void restoreDefaultApps(byte[] backup, int userId) {
19834        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19835            throw new SecurityException("Only the system may call restoreDefaultApps()");
19836        }
19837
19838        try {
19839            final XmlPullParser parser = Xml.newPullParser();
19840            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19841            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19842                    new BlobXmlRestorer() {
19843                        @Override
19844                        public void apply(XmlPullParser parser, int userId)
19845                                throws XmlPullParserException, IOException {
19846                            synchronized (mPackages) {
19847                                mSettings.readDefaultAppsLPw(parser, userId);
19848                            }
19849                        }
19850                    } );
19851        } catch (Exception e) {
19852            if (DEBUG_BACKUP) {
19853                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19854            }
19855        }
19856    }
19857
19858    @Override
19859    public byte[] getIntentFilterVerificationBackup(int userId) {
19860        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19861            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19862        }
19863
19864        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19865        try {
19866            final XmlSerializer serializer = new FastXmlSerializer();
19867            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19868            serializer.startDocument(null, true);
19869            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19870
19871            synchronized (mPackages) {
19872                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19873            }
19874
19875            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19876            serializer.endDocument();
19877            serializer.flush();
19878        } catch (Exception e) {
19879            if (DEBUG_BACKUP) {
19880                Slog.e(TAG, "Unable to write default apps for backup", e);
19881            }
19882            return null;
19883        }
19884
19885        return dataStream.toByteArray();
19886    }
19887
19888    @Override
19889    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19890        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19891            throw new SecurityException("Only the system may call restorePreferredActivities()");
19892        }
19893
19894        try {
19895            final XmlPullParser parser = Xml.newPullParser();
19896            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19897            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19898                    new BlobXmlRestorer() {
19899                        @Override
19900                        public void apply(XmlPullParser parser, int userId)
19901                                throws XmlPullParserException, IOException {
19902                            synchronized (mPackages) {
19903                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19904                                mSettings.writeLPr();
19905                            }
19906                        }
19907                    } );
19908        } catch (Exception e) {
19909            if (DEBUG_BACKUP) {
19910                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19911            }
19912        }
19913    }
19914
19915    @Override
19916    public byte[] getPermissionGrantBackup(int userId) {
19917        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19918            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19919        }
19920
19921        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19922        try {
19923            final XmlSerializer serializer = new FastXmlSerializer();
19924            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19925            serializer.startDocument(null, true);
19926            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19927
19928            synchronized (mPackages) {
19929                serializeRuntimePermissionGrantsLPr(serializer, userId);
19930            }
19931
19932            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19933            serializer.endDocument();
19934            serializer.flush();
19935        } catch (Exception e) {
19936            if (DEBUG_BACKUP) {
19937                Slog.e(TAG, "Unable to write default apps for backup", e);
19938            }
19939            return null;
19940        }
19941
19942        return dataStream.toByteArray();
19943    }
19944
19945    @Override
19946    public void restorePermissionGrants(byte[] backup, int userId) {
19947        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19948            throw new SecurityException("Only the system may call restorePermissionGrants()");
19949        }
19950
19951        try {
19952            final XmlPullParser parser = Xml.newPullParser();
19953            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19954            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19955                    new BlobXmlRestorer() {
19956                        @Override
19957                        public void apply(XmlPullParser parser, int userId)
19958                                throws XmlPullParserException, IOException {
19959                            synchronized (mPackages) {
19960                                processRestoredPermissionGrantsLPr(parser, userId);
19961                            }
19962                        }
19963                    } );
19964        } catch (Exception e) {
19965            if (DEBUG_BACKUP) {
19966                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19967            }
19968        }
19969    }
19970
19971    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19972            throws IOException {
19973        serializer.startTag(null, TAG_ALL_GRANTS);
19974
19975        final int N = mSettings.mPackages.size();
19976        for (int i = 0; i < N; i++) {
19977            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19978            boolean pkgGrantsKnown = false;
19979
19980            PermissionsState packagePerms = ps.getPermissionsState();
19981
19982            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19983                final int grantFlags = state.getFlags();
19984                // only look at grants that are not system/policy fixed
19985                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19986                    final boolean isGranted = state.isGranted();
19987                    // And only back up the user-twiddled state bits
19988                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19989                        final String packageName = mSettings.mPackages.keyAt(i);
19990                        if (!pkgGrantsKnown) {
19991                            serializer.startTag(null, TAG_GRANT);
19992                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19993                            pkgGrantsKnown = true;
19994                        }
19995
19996                        final boolean userSet =
19997                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19998                        final boolean userFixed =
19999                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20000                        final boolean revoke =
20001                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20002
20003                        serializer.startTag(null, TAG_PERMISSION);
20004                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20005                        if (isGranted) {
20006                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20007                        }
20008                        if (userSet) {
20009                            serializer.attribute(null, ATTR_USER_SET, "true");
20010                        }
20011                        if (userFixed) {
20012                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20013                        }
20014                        if (revoke) {
20015                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20016                        }
20017                        serializer.endTag(null, TAG_PERMISSION);
20018                    }
20019                }
20020            }
20021
20022            if (pkgGrantsKnown) {
20023                serializer.endTag(null, TAG_GRANT);
20024            }
20025        }
20026
20027        serializer.endTag(null, TAG_ALL_GRANTS);
20028    }
20029
20030    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20031            throws XmlPullParserException, IOException {
20032        String pkgName = null;
20033        int outerDepth = parser.getDepth();
20034        int type;
20035        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20036                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20037            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20038                continue;
20039            }
20040
20041            final String tagName = parser.getName();
20042            if (tagName.equals(TAG_GRANT)) {
20043                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20044                if (DEBUG_BACKUP) {
20045                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20046                }
20047            } else if (tagName.equals(TAG_PERMISSION)) {
20048
20049                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20050                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20051
20052                int newFlagSet = 0;
20053                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20054                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20055                }
20056                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20057                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20058                }
20059                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20060                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20061                }
20062                if (DEBUG_BACKUP) {
20063                    Slog.v(TAG, "  + Restoring grant:"
20064                            + " pkg=" + pkgName
20065                            + " perm=" + permName
20066                            + " granted=" + isGranted
20067                            + " bits=0x" + Integer.toHexString(newFlagSet));
20068                }
20069                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20070                if (ps != null) {
20071                    // Already installed so we apply the grant immediately
20072                    if (DEBUG_BACKUP) {
20073                        Slog.v(TAG, "        + already installed; applying");
20074                    }
20075                    PermissionsState perms = ps.getPermissionsState();
20076                    BasePermission bp =
20077                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20078                    if (bp != null) {
20079                        if (isGranted) {
20080                            perms.grantRuntimePermission(bp, userId);
20081                        }
20082                        if (newFlagSet != 0) {
20083                            perms.updatePermissionFlags(
20084                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20085                        }
20086                    }
20087                } else {
20088                    // Need to wait for post-restore install to apply the grant
20089                    if (DEBUG_BACKUP) {
20090                        Slog.v(TAG, "        - not yet installed; saving for later");
20091                    }
20092                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20093                            isGranted, newFlagSet, userId);
20094                }
20095            } else {
20096                PackageManagerService.reportSettingsProblem(Log.WARN,
20097                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20098                XmlUtils.skipCurrentTag(parser);
20099            }
20100        }
20101
20102        scheduleWriteSettingsLocked();
20103        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20104    }
20105
20106    @Override
20107    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20108            int sourceUserId, int targetUserId, int flags) {
20109        mContext.enforceCallingOrSelfPermission(
20110                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20111        int callingUid = Binder.getCallingUid();
20112        enforceOwnerRights(ownerPackage, callingUid);
20113        PackageManagerServiceUtils.enforceShellRestriction(
20114                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20115        if (intentFilter.countActions() == 0) {
20116            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20117            return;
20118        }
20119        synchronized (mPackages) {
20120            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20121                    ownerPackage, targetUserId, flags);
20122            CrossProfileIntentResolver resolver =
20123                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20124            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20125            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20126            if (existing != null) {
20127                int size = existing.size();
20128                for (int i = 0; i < size; i++) {
20129                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20130                        return;
20131                    }
20132                }
20133            }
20134            resolver.addFilter(newFilter);
20135            scheduleWritePackageRestrictionsLocked(sourceUserId);
20136        }
20137    }
20138
20139    @Override
20140    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20141        mContext.enforceCallingOrSelfPermission(
20142                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20143        final int callingUid = Binder.getCallingUid();
20144        enforceOwnerRights(ownerPackage, callingUid);
20145        PackageManagerServiceUtils.enforceShellRestriction(
20146                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20147        synchronized (mPackages) {
20148            CrossProfileIntentResolver resolver =
20149                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20150            ArraySet<CrossProfileIntentFilter> set =
20151                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20152            for (CrossProfileIntentFilter filter : set) {
20153                if (filter.getOwnerPackage().equals(ownerPackage)) {
20154                    resolver.removeFilter(filter);
20155                }
20156            }
20157            scheduleWritePackageRestrictionsLocked(sourceUserId);
20158        }
20159    }
20160
20161    // Enforcing that callingUid is owning pkg on userId
20162    private void enforceOwnerRights(String pkg, int callingUid) {
20163        // The system owns everything.
20164        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20165            return;
20166        }
20167        final int callingUserId = UserHandle.getUserId(callingUid);
20168        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20169        if (pi == null) {
20170            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20171                    + callingUserId);
20172        }
20173        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20174            throw new SecurityException("Calling uid " + callingUid
20175                    + " does not own package " + pkg);
20176        }
20177    }
20178
20179    @Override
20180    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20181        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20182            return null;
20183        }
20184        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20185    }
20186
20187    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20188        UserManagerService ums = UserManagerService.getInstance();
20189        if (ums != null) {
20190            final UserInfo parent = ums.getProfileParent(userId);
20191            final int launcherUid = (parent != null) ? parent.id : userId;
20192            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20193            if (launcherComponent != null) {
20194                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20195                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20196                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20197                        .setPackage(launcherComponent.getPackageName());
20198                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20199            }
20200        }
20201    }
20202
20203    /**
20204     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20205     * then reports the most likely home activity or null if there are more than one.
20206     */
20207    private ComponentName getDefaultHomeActivity(int userId) {
20208        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20209        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20210        if (cn != null) {
20211            return cn;
20212        }
20213
20214        // Find the launcher with the highest priority and return that component if there are no
20215        // other home activity with the same priority.
20216        int lastPriority = Integer.MIN_VALUE;
20217        ComponentName lastComponent = null;
20218        final int size = allHomeCandidates.size();
20219        for (int i = 0; i < size; i++) {
20220            final ResolveInfo ri = allHomeCandidates.get(i);
20221            if (ri.priority > lastPriority) {
20222                lastComponent = ri.activityInfo.getComponentName();
20223                lastPriority = ri.priority;
20224            } else if (ri.priority == lastPriority) {
20225                // Two components found with same priority.
20226                lastComponent = null;
20227            }
20228        }
20229        return lastComponent;
20230    }
20231
20232    private Intent getHomeIntent() {
20233        Intent intent = new Intent(Intent.ACTION_MAIN);
20234        intent.addCategory(Intent.CATEGORY_HOME);
20235        intent.addCategory(Intent.CATEGORY_DEFAULT);
20236        return intent;
20237    }
20238
20239    private IntentFilter getHomeFilter() {
20240        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20241        filter.addCategory(Intent.CATEGORY_HOME);
20242        filter.addCategory(Intent.CATEGORY_DEFAULT);
20243        return filter;
20244    }
20245
20246    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20247            int userId) {
20248        Intent intent  = getHomeIntent();
20249        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20250                PackageManager.GET_META_DATA, userId);
20251        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20252                true, false, false, userId);
20253
20254        allHomeCandidates.clear();
20255        if (list != null) {
20256            for (ResolveInfo ri : list) {
20257                allHomeCandidates.add(ri);
20258            }
20259        }
20260        return (preferred == null || preferred.activityInfo == null)
20261                ? null
20262                : new ComponentName(preferred.activityInfo.packageName,
20263                        preferred.activityInfo.name);
20264    }
20265
20266    @Override
20267    public void setHomeActivity(ComponentName comp, int userId) {
20268        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20269            return;
20270        }
20271        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20272        getHomeActivitiesAsUser(homeActivities, userId);
20273
20274        boolean found = false;
20275
20276        final int size = homeActivities.size();
20277        final ComponentName[] set = new ComponentName[size];
20278        for (int i = 0; i < size; i++) {
20279            final ResolveInfo candidate = homeActivities.get(i);
20280            final ActivityInfo info = candidate.activityInfo;
20281            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20282            set[i] = activityName;
20283            if (!found && activityName.equals(comp)) {
20284                found = true;
20285            }
20286        }
20287        if (!found) {
20288            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20289                    + userId);
20290        }
20291        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20292                set, comp, userId);
20293    }
20294
20295    private @Nullable String getSetupWizardPackageName() {
20296        final Intent intent = new Intent(Intent.ACTION_MAIN);
20297        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20298
20299        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20300                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20301                        | MATCH_DISABLED_COMPONENTS,
20302                UserHandle.myUserId());
20303        if (matches.size() == 1) {
20304            return matches.get(0).getComponentInfo().packageName;
20305        } else {
20306            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20307                    + ": matches=" + matches);
20308            return null;
20309        }
20310    }
20311
20312    private @Nullable String getStorageManagerPackageName() {
20313        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20314
20315        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20316                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20317                        | MATCH_DISABLED_COMPONENTS,
20318                UserHandle.myUserId());
20319        if (matches.size() == 1) {
20320            return matches.get(0).getComponentInfo().packageName;
20321        } else {
20322            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20323                    + matches.size() + ": matches=" + matches);
20324            return null;
20325        }
20326    }
20327
20328    @Override
20329    public void setApplicationEnabledSetting(String appPackageName,
20330            int newState, int flags, int userId, String callingPackage) {
20331        if (!sUserManager.exists(userId)) return;
20332        if (callingPackage == null) {
20333            callingPackage = Integer.toString(Binder.getCallingUid());
20334        }
20335        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20336    }
20337
20338    @Override
20339    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20340        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20341        synchronized (mPackages) {
20342            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20343            if (pkgSetting != null) {
20344                pkgSetting.setUpdateAvailable(updateAvailable);
20345            }
20346        }
20347    }
20348
20349    @Override
20350    public void setComponentEnabledSetting(ComponentName componentName,
20351            int newState, int flags, int userId) {
20352        if (!sUserManager.exists(userId)) return;
20353        setEnabledSetting(componentName.getPackageName(),
20354                componentName.getClassName(), newState, flags, userId, null);
20355    }
20356
20357    private void setEnabledSetting(final String packageName, String className, int newState,
20358            final int flags, int userId, String callingPackage) {
20359        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20360              || newState == COMPONENT_ENABLED_STATE_ENABLED
20361              || newState == COMPONENT_ENABLED_STATE_DISABLED
20362              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20363              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20364            throw new IllegalArgumentException("Invalid new component state: "
20365                    + newState);
20366        }
20367        PackageSetting pkgSetting;
20368        final int callingUid = Binder.getCallingUid();
20369        final int permission;
20370        if (callingUid == Process.SYSTEM_UID) {
20371            permission = PackageManager.PERMISSION_GRANTED;
20372        } else {
20373            permission = mContext.checkCallingOrSelfPermission(
20374                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20375        }
20376        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20377                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20378        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20379        boolean sendNow = false;
20380        boolean isApp = (className == null);
20381        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20382        String componentName = isApp ? packageName : className;
20383        int packageUid = -1;
20384        ArrayList<String> components;
20385
20386        // reader
20387        synchronized (mPackages) {
20388            pkgSetting = mSettings.mPackages.get(packageName);
20389            if (pkgSetting == null) {
20390                if (!isCallerInstantApp) {
20391                    if (className == null) {
20392                        throw new IllegalArgumentException("Unknown package: " + packageName);
20393                    }
20394                    throw new IllegalArgumentException(
20395                            "Unknown component: " + packageName + "/" + className);
20396                } else {
20397                    // throw SecurityException to prevent leaking package information
20398                    throw new SecurityException(
20399                            "Attempt to change component state; "
20400                            + "pid=" + Binder.getCallingPid()
20401                            + ", uid=" + callingUid
20402                            + (className == null
20403                                    ? ", package=" + packageName
20404                                    : ", component=" + packageName + "/" + className));
20405                }
20406            }
20407        }
20408
20409        // Limit who can change which apps
20410        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20411            // Don't allow apps that don't have permission to modify other apps
20412            if (!allowedByPermission
20413                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20414                throw new SecurityException(
20415                        "Attempt to change component state; "
20416                        + "pid=" + Binder.getCallingPid()
20417                        + ", uid=" + callingUid
20418                        + (className == null
20419                                ? ", package=" + packageName
20420                                : ", component=" + packageName + "/" + className));
20421            }
20422            // Don't allow changing protected packages.
20423            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20424                throw new SecurityException("Cannot disable a protected package: " + packageName);
20425            }
20426        }
20427
20428        synchronized (mPackages) {
20429            if (callingUid == Process.SHELL_UID
20430                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20431                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20432                // unless it is a test package.
20433                int oldState = pkgSetting.getEnabled(userId);
20434                if (className == null
20435                        &&
20436                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20437                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20438                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20439                        &&
20440                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20441                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20442                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20443                    // ok
20444                } else {
20445                    throw new SecurityException(
20446                            "Shell cannot change component state for " + packageName + "/"
20447                                    + className + " to " + newState);
20448                }
20449            }
20450        }
20451        if (className == null) {
20452            // We're dealing with an application/package level state change
20453            synchronized (mPackages) {
20454                if (pkgSetting.getEnabled(userId) == newState) {
20455                    // Nothing to do
20456                    return;
20457                }
20458            }
20459            // If we're enabling a system stub, there's a little more work to do.
20460            // Prior to enabling the package, we need to decompress the APK(s) to the
20461            // data partition and then replace the version on the system partition.
20462            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20463            final boolean isSystemStub = deletedPkg.isStub
20464                    && deletedPkg.isSystem();
20465            if (isSystemStub
20466                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20467                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20468                final File codePath = decompressPackage(deletedPkg);
20469                if (codePath == null) {
20470                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20471                    return;
20472                }
20473                // TODO remove direct parsing of the package object during internal cleanup
20474                // of scan package
20475                // We need to call parse directly here for no other reason than we need
20476                // the new package in order to disable the old one [we use the information
20477                // for some internal optimization to optionally create a new package setting
20478                // object on replace]. However, we can't get the package from the scan
20479                // because the scan modifies live structures and we need to remove the
20480                // old [system] package from the system before a scan can be attempted.
20481                // Once scan is indempotent we can remove this parse and use the package
20482                // object we scanned, prior to adding it to package settings.
20483                final PackageParser pp = new PackageParser();
20484                pp.setSeparateProcesses(mSeparateProcesses);
20485                pp.setDisplayMetrics(mMetrics);
20486                pp.setCallback(mPackageParserCallback);
20487                final PackageParser.Package tmpPkg;
20488                try {
20489                    final @ParseFlags int parseFlags = mDefParseFlags
20490                            | PackageParser.PARSE_MUST_BE_APK
20491                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20492                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20493                } catch (PackageParserException e) {
20494                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20495                    return;
20496                }
20497                synchronized (mInstallLock) {
20498                    // Disable the stub and remove any package entries
20499                    removePackageLI(deletedPkg, true);
20500                    synchronized (mPackages) {
20501                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20502                    }
20503                    final PackageParser.Package pkg;
20504                    try (PackageFreezer freezer =
20505                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20506                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20507                                | PackageParser.PARSE_ENFORCE_CODE;
20508                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20509                                0 /*currentTime*/, null /*user*/);
20510                        prepareAppDataAfterInstallLIF(pkg);
20511                        synchronized (mPackages) {
20512                            try {
20513                                updateSharedLibrariesLPr(pkg, null);
20514                            } catch (PackageManagerException e) {
20515                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20516                            }
20517                            mPermissionManager.updatePermissions(
20518                                    pkg.packageName, pkg, true, mPackages.values(),
20519                                    mPermissionCallback);
20520                            mSettings.writeLPr();
20521                        }
20522                    } catch (PackageManagerException e) {
20523                        // Whoops! Something went wrong; try to roll back to the stub
20524                        Slog.w(TAG, "Failed to install compressed system package:"
20525                                + pkgSetting.name, e);
20526                        // Remove the failed install
20527                        removeCodePathLI(codePath);
20528
20529                        // Install the system package
20530                        try (PackageFreezer freezer =
20531                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20532                            synchronized (mPackages) {
20533                                // NOTE: The system package always needs to be enabled; even
20534                                // if it's for a compressed stub. If we don't, installing the
20535                                // system package fails during scan [scanning checks the disabled
20536                                // packages]. We will reverse this later, after we've "installed"
20537                                // the stub.
20538                                // This leaves us in a fragile state; the stub should never be
20539                                // enabled, so, cross your fingers and hope nothing goes wrong
20540                                // until we can disable the package later.
20541                                enableSystemPackageLPw(deletedPkg);
20542                            }
20543                            installPackageFromSystemLIF(deletedPkg.codePath,
20544                                    false /*isPrivileged*/, null /*allUserHandles*/,
20545                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20546                                    true /*writeSettings*/);
20547                        } catch (PackageManagerException pme) {
20548                            Slog.w(TAG, "Failed to restore system package:"
20549                                    + deletedPkg.packageName, pme);
20550                        } finally {
20551                            synchronized (mPackages) {
20552                                mSettings.disableSystemPackageLPw(
20553                                        deletedPkg.packageName, true /*replaced*/);
20554                                mSettings.writeLPr();
20555                            }
20556                        }
20557                        return;
20558                    }
20559                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20560                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20561                    mDexManager.notifyPackageUpdated(pkg.packageName,
20562                            pkg.baseCodePath, pkg.splitCodePaths);
20563                }
20564            }
20565            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20566                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20567                // Don't care about who enables an app.
20568                callingPackage = null;
20569            }
20570            synchronized (mPackages) {
20571                pkgSetting.setEnabled(newState, userId, callingPackage);
20572            }
20573        } else {
20574            synchronized (mPackages) {
20575                // We're dealing with a component level state change
20576                // First, verify that this is a valid class name.
20577                PackageParser.Package pkg = pkgSetting.pkg;
20578                if (pkg == null || !pkg.hasComponentClassName(className)) {
20579                    if (pkg != null &&
20580                            pkg.applicationInfo.targetSdkVersion >=
20581                                    Build.VERSION_CODES.JELLY_BEAN) {
20582                        throw new IllegalArgumentException("Component class " + className
20583                                + " does not exist in " + packageName);
20584                    } else {
20585                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20586                                + className + " does not exist in " + packageName);
20587                    }
20588                }
20589                switch (newState) {
20590                    case COMPONENT_ENABLED_STATE_ENABLED:
20591                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20592                            return;
20593                        }
20594                        break;
20595                    case COMPONENT_ENABLED_STATE_DISABLED:
20596                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20597                            return;
20598                        }
20599                        break;
20600                    case COMPONENT_ENABLED_STATE_DEFAULT:
20601                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20602                            return;
20603                        }
20604                        break;
20605                    default:
20606                        Slog.e(TAG, "Invalid new component state: " + newState);
20607                        return;
20608                }
20609            }
20610        }
20611        synchronized (mPackages) {
20612            scheduleWritePackageRestrictionsLocked(userId);
20613            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20614            final long callingId = Binder.clearCallingIdentity();
20615            try {
20616                updateInstantAppInstallerLocked(packageName);
20617            } finally {
20618                Binder.restoreCallingIdentity(callingId);
20619            }
20620            components = mPendingBroadcasts.get(userId, packageName);
20621            final boolean newPackage = components == null;
20622            if (newPackage) {
20623                components = new ArrayList<String>();
20624            }
20625            if (!components.contains(componentName)) {
20626                components.add(componentName);
20627            }
20628            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20629                sendNow = true;
20630                // Purge entry from pending broadcast list if another one exists already
20631                // since we are sending one right away.
20632                mPendingBroadcasts.remove(userId, packageName);
20633            } else {
20634                if (newPackage) {
20635                    mPendingBroadcasts.put(userId, packageName, components);
20636                }
20637                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20638                    // Schedule a message
20639                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20640                }
20641            }
20642        }
20643
20644        long callingId = Binder.clearCallingIdentity();
20645        try {
20646            if (sendNow) {
20647                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20648                sendPackageChangedBroadcast(packageName,
20649                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20650            }
20651        } finally {
20652            Binder.restoreCallingIdentity(callingId);
20653        }
20654    }
20655
20656    @Override
20657    public void flushPackageRestrictionsAsUser(int userId) {
20658        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20659            return;
20660        }
20661        if (!sUserManager.exists(userId)) {
20662            return;
20663        }
20664        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20665                false /* checkShell */, "flushPackageRestrictions");
20666        synchronized (mPackages) {
20667            mSettings.writePackageRestrictionsLPr(userId);
20668            mDirtyUsers.remove(userId);
20669            if (mDirtyUsers.isEmpty()) {
20670                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20671            }
20672        }
20673    }
20674
20675    private void sendPackageChangedBroadcast(String packageName,
20676            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20677        if (DEBUG_INSTALL)
20678            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20679                    + componentNames);
20680        Bundle extras = new Bundle(4);
20681        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20682        String nameList[] = new String[componentNames.size()];
20683        componentNames.toArray(nameList);
20684        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20685        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20686        extras.putInt(Intent.EXTRA_UID, packageUid);
20687        // If this is not reporting a change of the overall package, then only send it
20688        // to registered receivers.  We don't want to launch a swath of apps for every
20689        // little component state change.
20690        final int flags = !componentNames.contains(packageName)
20691                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20692        final int userId = UserHandle.getUserId(packageUid);
20693        final boolean isInstantApp = isInstantApp(packageName, userId);
20694        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20695        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20696        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20697                userIds, instantUserIds);
20698    }
20699
20700    @Override
20701    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20702        if (!sUserManager.exists(userId)) return;
20703        final int callingUid = Binder.getCallingUid();
20704        if (getInstantAppPackageName(callingUid) != null) {
20705            return;
20706        }
20707        final int permission = mContext.checkCallingOrSelfPermission(
20708                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20709        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20710        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20711                true /* requireFullPermission */, true /* checkShell */, "stop package");
20712        // writer
20713        synchronized (mPackages) {
20714            final PackageSetting ps = mSettings.mPackages.get(packageName);
20715            if (!filterAppAccessLPr(ps, callingUid, userId)
20716                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20717                            allowedByPermission, callingUid, userId)) {
20718                scheduleWritePackageRestrictionsLocked(userId);
20719            }
20720        }
20721    }
20722
20723    @Override
20724    public String getInstallerPackageName(String packageName) {
20725        final int callingUid = Binder.getCallingUid();
20726        if (getInstantAppPackageName(callingUid) != null) {
20727            return null;
20728        }
20729        // reader
20730        synchronized (mPackages) {
20731            final PackageSetting ps = mSettings.mPackages.get(packageName);
20732            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20733                return null;
20734            }
20735            return mSettings.getInstallerPackageNameLPr(packageName);
20736        }
20737    }
20738
20739    public boolean isOrphaned(String packageName) {
20740        // reader
20741        synchronized (mPackages) {
20742            return mSettings.isOrphaned(packageName);
20743        }
20744    }
20745
20746    @Override
20747    public int getApplicationEnabledSetting(String packageName, int userId) {
20748        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20749        int callingUid = Binder.getCallingUid();
20750        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20751                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20752        // reader
20753        synchronized (mPackages) {
20754            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20755                return COMPONENT_ENABLED_STATE_DISABLED;
20756            }
20757            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20758        }
20759    }
20760
20761    @Override
20762    public int getComponentEnabledSetting(ComponentName component, int userId) {
20763        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20764        int callingUid = Binder.getCallingUid();
20765        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20766                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20767        synchronized (mPackages) {
20768            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20769                    component, TYPE_UNKNOWN, userId)) {
20770                return COMPONENT_ENABLED_STATE_DISABLED;
20771            }
20772            return mSettings.getComponentEnabledSettingLPr(component, userId);
20773        }
20774    }
20775
20776    @Override
20777    public void enterSafeMode() {
20778        enforceSystemOrRoot("Only the system can request entering safe mode");
20779
20780        if (!mSystemReady) {
20781            mSafeMode = true;
20782        }
20783    }
20784
20785    @Override
20786    public void systemReady() {
20787        enforceSystemOrRoot("Only the system can claim the system is ready");
20788
20789        mSystemReady = true;
20790        final ContentResolver resolver = mContext.getContentResolver();
20791        ContentObserver co = new ContentObserver(mHandler) {
20792            @Override
20793            public void onChange(boolean selfChange) {
20794                mEphemeralAppsDisabled =
20795                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20796                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20797            }
20798        };
20799        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20800                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20801                false, co, UserHandle.USER_SYSTEM);
20802        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20803                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20804        co.onChange(true);
20805
20806        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20807        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20808        // it is done.
20809        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20810            @Override
20811            public void onChange(boolean selfChange) {
20812                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20813                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20814                        oobEnabled == 1 ? "true" : "false");
20815            }
20816        };
20817        mContext.getContentResolver().registerContentObserver(
20818                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20819                UserHandle.USER_SYSTEM);
20820        // At boot, restore the value from the setting, which persists across reboot.
20821        privAppOobObserver.onChange(true);
20822
20823        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20824        // disabled after already being started.
20825        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20826                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20827
20828        // Read the compatibilty setting when the system is ready.
20829        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20830                mContext.getContentResolver(),
20831                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20832        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20833        if (DEBUG_SETTINGS) {
20834            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20835        }
20836
20837        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20838
20839        synchronized (mPackages) {
20840            // Verify that all of the preferred activity components actually
20841            // exist.  It is possible for applications to be updated and at
20842            // that point remove a previously declared activity component that
20843            // had been set as a preferred activity.  We try to clean this up
20844            // the next time we encounter that preferred activity, but it is
20845            // possible for the user flow to never be able to return to that
20846            // situation so here we do a sanity check to make sure we haven't
20847            // left any junk around.
20848            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20849            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20850                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20851                removed.clear();
20852                for (PreferredActivity pa : pir.filterSet()) {
20853                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20854                        removed.add(pa);
20855                    }
20856                }
20857                if (removed.size() > 0) {
20858                    for (int r=0; r<removed.size(); r++) {
20859                        PreferredActivity pa = removed.get(r);
20860                        Slog.w(TAG, "Removing dangling preferred activity: "
20861                                + pa.mPref.mComponent);
20862                        pir.removeFilter(pa);
20863                    }
20864                    mSettings.writePackageRestrictionsLPr(
20865                            mSettings.mPreferredActivities.keyAt(i));
20866                }
20867            }
20868
20869            for (int userId : UserManagerService.getInstance().getUserIds()) {
20870                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20871                    grantPermissionsUserIds = ArrayUtils.appendInt(
20872                            grantPermissionsUserIds, userId);
20873                }
20874            }
20875        }
20876        sUserManager.systemReady();
20877        // If we upgraded grant all default permissions before kicking off.
20878        for (int userId : grantPermissionsUserIds) {
20879            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20880        }
20881
20882        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20883            // If we did not grant default permissions, we preload from this the
20884            // default permission exceptions lazily to ensure we don't hit the
20885            // disk on a new user creation.
20886            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20887        }
20888
20889        // Now that we've scanned all packages, and granted any default
20890        // permissions, ensure permissions are updated. Beware of dragons if you
20891        // try optimizing this.
20892        synchronized (mPackages) {
20893            mPermissionManager.updateAllPermissions(
20894                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20895                    mPermissionCallback);
20896        }
20897
20898        // Kick off any messages waiting for system ready
20899        if (mPostSystemReadyMessages != null) {
20900            for (Message msg : mPostSystemReadyMessages) {
20901                msg.sendToTarget();
20902            }
20903            mPostSystemReadyMessages = null;
20904        }
20905
20906        // Watch for external volumes that come and go over time
20907        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20908        storage.registerListener(mStorageListener);
20909
20910        mInstallerService.systemReady();
20911        mPackageDexOptimizer.systemReady();
20912
20913        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20914                StorageManagerInternal.class);
20915        StorageManagerInternal.addExternalStoragePolicy(
20916                new StorageManagerInternal.ExternalStorageMountPolicy() {
20917            @Override
20918            public int getMountMode(int uid, String packageName) {
20919                if (Process.isIsolated(uid)) {
20920                    return Zygote.MOUNT_EXTERNAL_NONE;
20921                }
20922                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20923                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20924                }
20925                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20926                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20927                }
20928                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20929                    return Zygote.MOUNT_EXTERNAL_READ;
20930                }
20931                return Zygote.MOUNT_EXTERNAL_WRITE;
20932            }
20933
20934            @Override
20935            public boolean hasExternalStorage(int uid, String packageName) {
20936                return true;
20937            }
20938        });
20939
20940        // Now that we're mostly running, clean up stale users and apps
20941        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20942        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20943
20944        mPermissionManager.systemReady();
20945    }
20946
20947    public void waitForAppDataPrepared() {
20948        if (mPrepareAppDataFuture == null) {
20949            return;
20950        }
20951        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20952        mPrepareAppDataFuture = null;
20953    }
20954
20955    @Override
20956    public boolean isSafeMode() {
20957        // allow instant applications
20958        return mSafeMode;
20959    }
20960
20961    @Override
20962    public boolean hasSystemUidErrors() {
20963        // allow instant applications
20964        return mHasSystemUidErrors;
20965    }
20966
20967    static String arrayToString(int[] array) {
20968        StringBuffer buf = new StringBuffer(128);
20969        buf.append('[');
20970        if (array != null) {
20971            for (int i=0; i<array.length; i++) {
20972                if (i > 0) buf.append(", ");
20973                buf.append(array[i]);
20974            }
20975        }
20976        buf.append(']');
20977        return buf.toString();
20978    }
20979
20980    @Override
20981    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20982            FileDescriptor err, String[] args, ShellCallback callback,
20983            ResultReceiver resultReceiver) {
20984        (new PackageManagerShellCommand(this)).exec(
20985                this, in, out, err, args, callback, resultReceiver);
20986    }
20987
20988    @Override
20989    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20990        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20991
20992        DumpState dumpState = new DumpState();
20993        boolean fullPreferred = false;
20994        boolean checkin = false;
20995
20996        String packageName = null;
20997        ArraySet<String> permissionNames = null;
20998
20999        int opti = 0;
21000        while (opti < args.length) {
21001            String opt = args[opti];
21002            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21003                break;
21004            }
21005            opti++;
21006
21007            if ("-a".equals(opt)) {
21008                // Right now we only know how to print all.
21009            } else if ("-h".equals(opt)) {
21010                pw.println("Package manager dump options:");
21011                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21012                pw.println("    --checkin: dump for a checkin");
21013                pw.println("    -f: print details of intent filters");
21014                pw.println("    -h: print this help");
21015                pw.println("  cmd may be one of:");
21016                pw.println("    l[ibraries]: list known shared libraries");
21017                pw.println("    f[eatures]: list device features");
21018                pw.println("    k[eysets]: print known keysets");
21019                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21020                pw.println("    perm[issions]: dump permissions");
21021                pw.println("    permission [name ...]: dump declaration and use of given permission");
21022                pw.println("    pref[erred]: print preferred package settings");
21023                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21024                pw.println("    prov[iders]: dump content providers");
21025                pw.println("    p[ackages]: dump installed packages");
21026                pw.println("    s[hared-users]: dump shared user IDs");
21027                pw.println("    m[essages]: print collected runtime messages");
21028                pw.println("    v[erifiers]: print package verifier info");
21029                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21030                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21031                pw.println("    version: print database version info");
21032                pw.println("    write: write current settings now");
21033                pw.println("    installs: details about install sessions");
21034                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21035                pw.println("    dexopt: dump dexopt state");
21036                pw.println("    compiler-stats: dump compiler statistics");
21037                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21038                pw.println("    service-permissions: dump permissions required by services");
21039                pw.println("    <package.name>: info about given package");
21040                return;
21041            } else if ("--checkin".equals(opt)) {
21042                checkin = true;
21043            } else if ("-f".equals(opt)) {
21044                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21045            } else if ("--proto".equals(opt)) {
21046                dumpProto(fd);
21047                return;
21048            } else {
21049                pw.println("Unknown argument: " + opt + "; use -h for help");
21050            }
21051        }
21052
21053        // Is the caller requesting to dump a particular piece of data?
21054        if (opti < args.length) {
21055            String cmd = args[opti];
21056            opti++;
21057            // Is this a package name?
21058            if ("android".equals(cmd) || cmd.contains(".")) {
21059                packageName = cmd;
21060                // When dumping a single package, we always dump all of its
21061                // filter information since the amount of data will be reasonable.
21062                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21063            } else if ("check-permission".equals(cmd)) {
21064                if (opti >= args.length) {
21065                    pw.println("Error: check-permission missing permission argument");
21066                    return;
21067                }
21068                String perm = args[opti];
21069                opti++;
21070                if (opti >= args.length) {
21071                    pw.println("Error: check-permission missing package argument");
21072                    return;
21073                }
21074
21075                String pkg = args[opti];
21076                opti++;
21077                int user = UserHandle.getUserId(Binder.getCallingUid());
21078                if (opti < args.length) {
21079                    try {
21080                        user = Integer.parseInt(args[opti]);
21081                    } catch (NumberFormatException e) {
21082                        pw.println("Error: check-permission user argument is not a number: "
21083                                + args[opti]);
21084                        return;
21085                    }
21086                }
21087
21088                // Normalize package name to handle renamed packages and static libs
21089                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21090
21091                pw.println(checkPermission(perm, pkg, user));
21092                return;
21093            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21094                dumpState.setDump(DumpState.DUMP_LIBS);
21095            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21096                dumpState.setDump(DumpState.DUMP_FEATURES);
21097            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21098                if (opti >= args.length) {
21099                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21100                            | DumpState.DUMP_SERVICE_RESOLVERS
21101                            | DumpState.DUMP_RECEIVER_RESOLVERS
21102                            | DumpState.DUMP_CONTENT_RESOLVERS);
21103                } else {
21104                    while (opti < args.length) {
21105                        String name = args[opti];
21106                        if ("a".equals(name) || "activity".equals(name)) {
21107                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21108                        } else if ("s".equals(name) || "service".equals(name)) {
21109                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21110                        } else if ("r".equals(name) || "receiver".equals(name)) {
21111                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21112                        } else if ("c".equals(name) || "content".equals(name)) {
21113                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21114                        } else {
21115                            pw.println("Error: unknown resolver table type: " + name);
21116                            return;
21117                        }
21118                        opti++;
21119                    }
21120                }
21121            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21122                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21123            } else if ("permission".equals(cmd)) {
21124                if (opti >= args.length) {
21125                    pw.println("Error: permission requires permission name");
21126                    return;
21127                }
21128                permissionNames = new ArraySet<>();
21129                while (opti < args.length) {
21130                    permissionNames.add(args[opti]);
21131                    opti++;
21132                }
21133                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21134                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21135            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21136                dumpState.setDump(DumpState.DUMP_PREFERRED);
21137            } else if ("preferred-xml".equals(cmd)) {
21138                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21139                if (opti < args.length && "--full".equals(args[opti])) {
21140                    fullPreferred = true;
21141                    opti++;
21142                }
21143            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21144                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21145            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21146                dumpState.setDump(DumpState.DUMP_PACKAGES);
21147            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21148                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21149            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21150                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21151            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21152                dumpState.setDump(DumpState.DUMP_MESSAGES);
21153            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21154                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21155            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21156                    || "intent-filter-verifiers".equals(cmd)) {
21157                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21158            } else if ("version".equals(cmd)) {
21159                dumpState.setDump(DumpState.DUMP_VERSION);
21160            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21161                dumpState.setDump(DumpState.DUMP_KEYSETS);
21162            } else if ("installs".equals(cmd)) {
21163                dumpState.setDump(DumpState.DUMP_INSTALLS);
21164            } else if ("frozen".equals(cmd)) {
21165                dumpState.setDump(DumpState.DUMP_FROZEN);
21166            } else if ("volumes".equals(cmd)) {
21167                dumpState.setDump(DumpState.DUMP_VOLUMES);
21168            } else if ("dexopt".equals(cmd)) {
21169                dumpState.setDump(DumpState.DUMP_DEXOPT);
21170            } else if ("compiler-stats".equals(cmd)) {
21171                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21172            } else if ("changes".equals(cmd)) {
21173                dumpState.setDump(DumpState.DUMP_CHANGES);
21174            } else if ("service-permissions".equals(cmd)) {
21175                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21176            } else if ("write".equals(cmd)) {
21177                synchronized (mPackages) {
21178                    mSettings.writeLPr();
21179                    pw.println("Settings written.");
21180                    return;
21181                }
21182            }
21183        }
21184
21185        if (checkin) {
21186            pw.println("vers,1");
21187        }
21188
21189        // reader
21190        synchronized (mPackages) {
21191            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21192                if (!checkin) {
21193                    if (dumpState.onTitlePrinted())
21194                        pw.println();
21195                    pw.println("Database versions:");
21196                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21197                }
21198            }
21199
21200            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21201                if (!checkin) {
21202                    if (dumpState.onTitlePrinted())
21203                        pw.println();
21204                    pw.println("Verifiers:");
21205                    pw.print("  Required: ");
21206                    pw.print(mRequiredVerifierPackage);
21207                    pw.print(" (uid=");
21208                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21209                            UserHandle.USER_SYSTEM));
21210                    pw.println(")");
21211                } else if (mRequiredVerifierPackage != null) {
21212                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21213                    pw.print(",");
21214                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21215                            UserHandle.USER_SYSTEM));
21216                }
21217            }
21218
21219            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21220                    packageName == null) {
21221                if (mIntentFilterVerifierComponent != null) {
21222                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21223                    if (!checkin) {
21224                        if (dumpState.onTitlePrinted())
21225                            pw.println();
21226                        pw.println("Intent Filter Verifier:");
21227                        pw.print("  Using: ");
21228                        pw.print(verifierPackageName);
21229                        pw.print(" (uid=");
21230                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21231                                UserHandle.USER_SYSTEM));
21232                        pw.println(")");
21233                    } else if (verifierPackageName != null) {
21234                        pw.print("ifv,"); pw.print(verifierPackageName);
21235                        pw.print(",");
21236                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21237                                UserHandle.USER_SYSTEM));
21238                    }
21239                } else {
21240                    pw.println();
21241                    pw.println("No Intent Filter Verifier available!");
21242                }
21243            }
21244
21245            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21246                boolean printedHeader = false;
21247                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21248                while (it.hasNext()) {
21249                    String libName = it.next();
21250                    LongSparseArray<SharedLibraryEntry> versionedLib
21251                            = mSharedLibraries.get(libName);
21252                    if (versionedLib == null) {
21253                        continue;
21254                    }
21255                    final int versionCount = versionedLib.size();
21256                    for (int i = 0; i < versionCount; i++) {
21257                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21258                        if (!checkin) {
21259                            if (!printedHeader) {
21260                                if (dumpState.onTitlePrinted())
21261                                    pw.println();
21262                                pw.println("Libraries:");
21263                                printedHeader = true;
21264                            }
21265                            pw.print("  ");
21266                        } else {
21267                            pw.print("lib,");
21268                        }
21269                        pw.print(libEntry.info.getName());
21270                        if (libEntry.info.isStatic()) {
21271                            pw.print(" version=" + libEntry.info.getLongVersion());
21272                        }
21273                        if (!checkin) {
21274                            pw.print(" -> ");
21275                        }
21276                        if (libEntry.path != null) {
21277                            pw.print(" (jar) ");
21278                            pw.print(libEntry.path);
21279                        } else {
21280                            pw.print(" (apk) ");
21281                            pw.print(libEntry.apk);
21282                        }
21283                        pw.println();
21284                    }
21285                }
21286            }
21287
21288            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21289                if (dumpState.onTitlePrinted())
21290                    pw.println();
21291                if (!checkin) {
21292                    pw.println("Features:");
21293                }
21294
21295                synchronized (mAvailableFeatures) {
21296                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21297                        if (checkin) {
21298                            pw.print("feat,");
21299                            pw.print(feat.name);
21300                            pw.print(",");
21301                            pw.println(feat.version);
21302                        } else {
21303                            pw.print("  ");
21304                            pw.print(feat.name);
21305                            if (feat.version > 0) {
21306                                pw.print(" version=");
21307                                pw.print(feat.version);
21308                            }
21309                            pw.println();
21310                        }
21311                    }
21312                }
21313            }
21314
21315            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21316                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21317                        : "Activity Resolver Table:", "  ", packageName,
21318                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21319                    dumpState.setTitlePrinted(true);
21320                }
21321            }
21322            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21323                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21324                        : "Receiver Resolver Table:", "  ", packageName,
21325                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21326                    dumpState.setTitlePrinted(true);
21327                }
21328            }
21329            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21330                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21331                        : "Service Resolver Table:", "  ", packageName,
21332                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21333                    dumpState.setTitlePrinted(true);
21334                }
21335            }
21336            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21337                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21338                        : "Provider Resolver Table:", "  ", packageName,
21339                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21340                    dumpState.setTitlePrinted(true);
21341                }
21342            }
21343
21344            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21345                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21346                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21347                    int user = mSettings.mPreferredActivities.keyAt(i);
21348                    if (pir.dump(pw,
21349                            dumpState.getTitlePrinted()
21350                                ? "\nPreferred Activities User " + user + ":"
21351                                : "Preferred Activities User " + user + ":", "  ",
21352                            packageName, true, false)) {
21353                        dumpState.setTitlePrinted(true);
21354                    }
21355                }
21356            }
21357
21358            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21359                pw.flush();
21360                FileOutputStream fout = new FileOutputStream(fd);
21361                BufferedOutputStream str = new BufferedOutputStream(fout);
21362                XmlSerializer serializer = new FastXmlSerializer();
21363                try {
21364                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21365                    serializer.startDocument(null, true);
21366                    serializer.setFeature(
21367                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21368                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21369                    serializer.endDocument();
21370                    serializer.flush();
21371                } catch (IllegalArgumentException e) {
21372                    pw.println("Failed writing: " + e);
21373                } catch (IllegalStateException e) {
21374                    pw.println("Failed writing: " + e);
21375                } catch (IOException e) {
21376                    pw.println("Failed writing: " + e);
21377                }
21378            }
21379
21380            if (!checkin
21381                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21382                    && packageName == null) {
21383                pw.println();
21384                int count = mSettings.mPackages.size();
21385                if (count == 0) {
21386                    pw.println("No applications!");
21387                    pw.println();
21388                } else {
21389                    final String prefix = "  ";
21390                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21391                    if (allPackageSettings.size() == 0) {
21392                        pw.println("No domain preferred apps!");
21393                        pw.println();
21394                    } else {
21395                        pw.println("App verification status:");
21396                        pw.println();
21397                        count = 0;
21398                        for (PackageSetting ps : allPackageSettings) {
21399                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21400                            if (ivi == null || ivi.getPackageName() == null) continue;
21401                            pw.println(prefix + "Package: " + ivi.getPackageName());
21402                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21403                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21404                            pw.println();
21405                            count++;
21406                        }
21407                        if (count == 0) {
21408                            pw.println(prefix + "No app verification established.");
21409                            pw.println();
21410                        }
21411                        for (int userId : sUserManager.getUserIds()) {
21412                            pw.println("App linkages for user " + userId + ":");
21413                            pw.println();
21414                            count = 0;
21415                            for (PackageSetting ps : allPackageSettings) {
21416                                final long status = ps.getDomainVerificationStatusForUser(userId);
21417                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21418                                        && !DEBUG_DOMAIN_VERIFICATION) {
21419                                    continue;
21420                                }
21421                                pw.println(prefix + "Package: " + ps.name);
21422                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21423                                String statusStr = IntentFilterVerificationInfo.
21424                                        getStatusStringFromValue(status);
21425                                pw.println(prefix + "Status:  " + statusStr);
21426                                pw.println();
21427                                count++;
21428                            }
21429                            if (count == 0) {
21430                                pw.println(prefix + "No configured app linkages.");
21431                                pw.println();
21432                            }
21433                        }
21434                    }
21435                }
21436            }
21437
21438            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21439                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21440            }
21441
21442            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21443                boolean printedSomething = false;
21444                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21445                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21446                        continue;
21447                    }
21448                    if (!printedSomething) {
21449                        if (dumpState.onTitlePrinted())
21450                            pw.println();
21451                        pw.println("Registered ContentProviders:");
21452                        printedSomething = true;
21453                    }
21454                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21455                    pw.print("    "); pw.println(p.toString());
21456                }
21457                printedSomething = false;
21458                for (Map.Entry<String, PackageParser.Provider> entry :
21459                        mProvidersByAuthority.entrySet()) {
21460                    PackageParser.Provider p = entry.getValue();
21461                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21462                        continue;
21463                    }
21464                    if (!printedSomething) {
21465                        if (dumpState.onTitlePrinted())
21466                            pw.println();
21467                        pw.println("ContentProvider Authorities:");
21468                        printedSomething = true;
21469                    }
21470                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21471                    pw.print("    "); pw.println(p.toString());
21472                    if (p.info != null && p.info.applicationInfo != null) {
21473                        final String appInfo = p.info.applicationInfo.toString();
21474                        pw.print("      applicationInfo="); pw.println(appInfo);
21475                    }
21476                }
21477            }
21478
21479            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21480                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21481            }
21482
21483            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21484                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21485            }
21486
21487            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21488                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21489            }
21490
21491            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21492                if (dumpState.onTitlePrinted()) pw.println();
21493                pw.println("Package Changes:");
21494                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21495                final int K = mChangedPackages.size();
21496                for (int i = 0; i < K; i++) {
21497                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21498                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21499                    final int N = changes.size();
21500                    if (N == 0) {
21501                        pw.print("    "); pw.println("No packages changed");
21502                    } else {
21503                        for (int j = 0; j < N; j++) {
21504                            final String pkgName = changes.valueAt(j);
21505                            final int sequenceNumber = changes.keyAt(j);
21506                            pw.print("    ");
21507                            pw.print("seq=");
21508                            pw.print(sequenceNumber);
21509                            pw.print(", package=");
21510                            pw.println(pkgName);
21511                        }
21512                    }
21513                }
21514            }
21515
21516            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21517                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21518            }
21519
21520            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21521                // XXX should handle packageName != null by dumping only install data that
21522                // the given package is involved with.
21523                if (dumpState.onTitlePrinted()) pw.println();
21524
21525                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21526                ipw.println();
21527                ipw.println("Frozen packages:");
21528                ipw.increaseIndent();
21529                if (mFrozenPackages.size() == 0) {
21530                    ipw.println("(none)");
21531                } else {
21532                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21533                        ipw.println(mFrozenPackages.valueAt(i));
21534                    }
21535                }
21536                ipw.decreaseIndent();
21537            }
21538
21539            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21540                if (dumpState.onTitlePrinted()) pw.println();
21541
21542                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21543                ipw.println();
21544                ipw.println("Loaded volumes:");
21545                ipw.increaseIndent();
21546                if (mLoadedVolumes.size() == 0) {
21547                    ipw.println("(none)");
21548                } else {
21549                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21550                        ipw.println(mLoadedVolumes.valueAt(i));
21551                    }
21552                }
21553                ipw.decreaseIndent();
21554            }
21555
21556            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21557                    && packageName == null) {
21558                if (dumpState.onTitlePrinted()) pw.println();
21559                pw.println("Service permissions:");
21560
21561                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21562                while (filterIterator.hasNext()) {
21563                    final ServiceIntentInfo info = filterIterator.next();
21564                    final ServiceInfo serviceInfo = info.service.info;
21565                    final String permission = serviceInfo.permission;
21566                    if (permission != null) {
21567                        pw.print("    ");
21568                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21569                        pw.print(": ");
21570                        pw.println(permission);
21571                    }
21572                }
21573            }
21574
21575            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21576                if (dumpState.onTitlePrinted()) pw.println();
21577                dumpDexoptStateLPr(pw, packageName);
21578            }
21579
21580            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21581                if (dumpState.onTitlePrinted()) pw.println();
21582                dumpCompilerStatsLPr(pw, packageName);
21583            }
21584
21585            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21586                if (dumpState.onTitlePrinted()) pw.println();
21587                mSettings.dumpReadMessagesLPr(pw, dumpState);
21588
21589                pw.println();
21590                pw.println("Package warning messages:");
21591                dumpCriticalInfo(pw, null);
21592            }
21593
21594            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21595                dumpCriticalInfo(pw, "msg,");
21596            }
21597        }
21598
21599        // PackageInstaller should be called outside of mPackages lock
21600        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21601            // XXX should handle packageName != null by dumping only install data that
21602            // the given package is involved with.
21603            if (dumpState.onTitlePrinted()) pw.println();
21604            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21605        }
21606    }
21607
21608    private void dumpProto(FileDescriptor fd) {
21609        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21610
21611        synchronized (mPackages) {
21612            final long requiredVerifierPackageToken =
21613                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21614            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21615            proto.write(
21616                    PackageServiceDumpProto.PackageShortProto.UID,
21617                    getPackageUid(
21618                            mRequiredVerifierPackage,
21619                            MATCH_DEBUG_TRIAGED_MISSING,
21620                            UserHandle.USER_SYSTEM));
21621            proto.end(requiredVerifierPackageToken);
21622
21623            if (mIntentFilterVerifierComponent != null) {
21624                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21625                final long verifierPackageToken =
21626                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21627                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21628                proto.write(
21629                        PackageServiceDumpProto.PackageShortProto.UID,
21630                        getPackageUid(
21631                                verifierPackageName,
21632                                MATCH_DEBUG_TRIAGED_MISSING,
21633                                UserHandle.USER_SYSTEM));
21634                proto.end(verifierPackageToken);
21635            }
21636
21637            dumpSharedLibrariesProto(proto);
21638            dumpFeaturesProto(proto);
21639            mSettings.dumpPackagesProto(proto);
21640            mSettings.dumpSharedUsersProto(proto);
21641            dumpCriticalInfo(proto);
21642        }
21643        proto.flush();
21644    }
21645
21646    private void dumpFeaturesProto(ProtoOutputStream proto) {
21647        synchronized (mAvailableFeatures) {
21648            final int count = mAvailableFeatures.size();
21649            for (int i = 0; i < count; i++) {
21650                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21651            }
21652        }
21653    }
21654
21655    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21656        final int count = mSharedLibraries.size();
21657        for (int i = 0; i < count; i++) {
21658            final String libName = mSharedLibraries.keyAt(i);
21659            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21660            if (versionedLib == null) {
21661                continue;
21662            }
21663            final int versionCount = versionedLib.size();
21664            for (int j = 0; j < versionCount; j++) {
21665                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21666                final long sharedLibraryToken =
21667                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21668                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21669                final boolean isJar = (libEntry.path != null);
21670                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21671                if (isJar) {
21672                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21673                } else {
21674                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21675                }
21676                proto.end(sharedLibraryToken);
21677            }
21678        }
21679    }
21680
21681    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21682        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21683        ipw.println();
21684        ipw.println("Dexopt state:");
21685        ipw.increaseIndent();
21686        Collection<PackageParser.Package> packages = null;
21687        if (packageName != null) {
21688            PackageParser.Package targetPackage = mPackages.get(packageName);
21689            if (targetPackage != null) {
21690                packages = Collections.singletonList(targetPackage);
21691            } else {
21692                ipw.println("Unable to find package: " + packageName);
21693                return;
21694            }
21695        } else {
21696            packages = mPackages.values();
21697        }
21698
21699        for (PackageParser.Package pkg : packages) {
21700            ipw.println("[" + pkg.packageName + "]");
21701            ipw.increaseIndent();
21702            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21703                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21704            ipw.decreaseIndent();
21705        }
21706    }
21707
21708    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21709        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21710        ipw.println();
21711        ipw.println("Compiler stats:");
21712        ipw.increaseIndent();
21713        Collection<PackageParser.Package> packages = null;
21714        if (packageName != null) {
21715            PackageParser.Package targetPackage = mPackages.get(packageName);
21716            if (targetPackage != null) {
21717                packages = Collections.singletonList(targetPackage);
21718            } else {
21719                ipw.println("Unable to find package: " + packageName);
21720                return;
21721            }
21722        } else {
21723            packages = mPackages.values();
21724        }
21725
21726        for (PackageParser.Package pkg : packages) {
21727            ipw.println("[" + pkg.packageName + "]");
21728            ipw.increaseIndent();
21729
21730            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21731            if (stats == null) {
21732                ipw.println("(No recorded stats)");
21733            } else {
21734                stats.dump(ipw);
21735            }
21736            ipw.decreaseIndent();
21737        }
21738    }
21739
21740    private String dumpDomainString(String packageName) {
21741        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21742                .getList();
21743        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21744
21745        ArraySet<String> result = new ArraySet<>();
21746        if (iviList.size() > 0) {
21747            for (IntentFilterVerificationInfo ivi : iviList) {
21748                for (String host : ivi.getDomains()) {
21749                    result.add(host);
21750                }
21751            }
21752        }
21753        if (filters != null && filters.size() > 0) {
21754            for (IntentFilter filter : filters) {
21755                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21756                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21757                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21758                    result.addAll(filter.getHostsList());
21759                }
21760            }
21761        }
21762
21763        StringBuilder sb = new StringBuilder(result.size() * 16);
21764        for (String domain : result) {
21765            if (sb.length() > 0) sb.append(" ");
21766            sb.append(domain);
21767        }
21768        return sb.toString();
21769    }
21770
21771    // ------- apps on sdcard specific code -------
21772    static final boolean DEBUG_SD_INSTALL = false;
21773
21774    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21775
21776    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21777
21778    private boolean mMediaMounted = false;
21779
21780    static String getEncryptKey() {
21781        try {
21782            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21783                    SD_ENCRYPTION_KEYSTORE_NAME);
21784            if (sdEncKey == null) {
21785                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21786                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21787                if (sdEncKey == null) {
21788                    Slog.e(TAG, "Failed to create encryption keys");
21789                    return null;
21790                }
21791            }
21792            return sdEncKey;
21793        } catch (NoSuchAlgorithmException nsae) {
21794            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21795            return null;
21796        } catch (IOException ioe) {
21797            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21798            return null;
21799        }
21800    }
21801
21802    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21803            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21804        final int size = infos.size();
21805        final String[] packageNames = new String[size];
21806        final int[] packageUids = new int[size];
21807        for (int i = 0; i < size; i++) {
21808            final ApplicationInfo info = infos.get(i);
21809            packageNames[i] = info.packageName;
21810            packageUids[i] = info.uid;
21811        }
21812        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21813                finishedReceiver);
21814    }
21815
21816    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21817            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21818        sendResourcesChangedBroadcast(mediaStatus, replacing,
21819                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21820    }
21821
21822    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21823            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21824        int size = pkgList.length;
21825        if (size > 0) {
21826            // Send broadcasts here
21827            Bundle extras = new Bundle();
21828            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21829            if (uidArr != null) {
21830                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21831            }
21832            if (replacing) {
21833                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21834            }
21835            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21836                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21837            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21838        }
21839    }
21840
21841    private void loadPrivatePackages(final VolumeInfo vol) {
21842        mHandler.post(new Runnable() {
21843            @Override
21844            public void run() {
21845                loadPrivatePackagesInner(vol);
21846            }
21847        });
21848    }
21849
21850    private void loadPrivatePackagesInner(VolumeInfo vol) {
21851        final String volumeUuid = vol.fsUuid;
21852        if (TextUtils.isEmpty(volumeUuid)) {
21853            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21854            return;
21855        }
21856
21857        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21858        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21859        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21860
21861        final VersionInfo ver;
21862        final List<PackageSetting> packages;
21863        synchronized (mPackages) {
21864            ver = mSettings.findOrCreateVersion(volumeUuid);
21865            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21866        }
21867
21868        for (PackageSetting ps : packages) {
21869            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21870            synchronized (mInstallLock) {
21871                final PackageParser.Package pkg;
21872                try {
21873                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21874                    loaded.add(pkg.applicationInfo);
21875
21876                } catch (PackageManagerException e) {
21877                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21878                }
21879
21880                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21881                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21882                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21883                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21884                }
21885            }
21886        }
21887
21888        // Reconcile app data for all started/unlocked users
21889        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21890        final UserManager um = mContext.getSystemService(UserManager.class);
21891        UserManagerInternal umInternal = getUserManagerInternal();
21892        for (UserInfo user : um.getUsers()) {
21893            final int flags;
21894            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21895                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21896            } else if (umInternal.isUserRunning(user.id)) {
21897                flags = StorageManager.FLAG_STORAGE_DE;
21898            } else {
21899                continue;
21900            }
21901
21902            try {
21903                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21904                synchronized (mInstallLock) {
21905                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21906                }
21907            } catch (IllegalStateException e) {
21908                // Device was probably ejected, and we'll process that event momentarily
21909                Slog.w(TAG, "Failed to prepare storage: " + e);
21910            }
21911        }
21912
21913        synchronized (mPackages) {
21914            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21915            if (sdkUpdated) {
21916                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21917                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21918            }
21919            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21920                    mPermissionCallback);
21921
21922            // Yay, everything is now upgraded
21923            ver.forceCurrent();
21924
21925            mSettings.writeLPr();
21926        }
21927
21928        for (PackageFreezer freezer : freezers) {
21929            freezer.close();
21930        }
21931
21932        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21933        sendResourcesChangedBroadcast(true, false, loaded, null);
21934        mLoadedVolumes.add(vol.getId());
21935    }
21936
21937    private void unloadPrivatePackages(final VolumeInfo vol) {
21938        mHandler.post(new Runnable() {
21939            @Override
21940            public void run() {
21941                unloadPrivatePackagesInner(vol);
21942            }
21943        });
21944    }
21945
21946    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21947        final String volumeUuid = vol.fsUuid;
21948        if (TextUtils.isEmpty(volumeUuid)) {
21949            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21950            return;
21951        }
21952
21953        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21954        synchronized (mInstallLock) {
21955        synchronized (mPackages) {
21956            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21957            for (PackageSetting ps : packages) {
21958                if (ps.pkg == null) continue;
21959
21960                final ApplicationInfo info = ps.pkg.applicationInfo;
21961                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21962                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21963
21964                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21965                        "unloadPrivatePackagesInner")) {
21966                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21967                            false, null)) {
21968                        unloaded.add(info);
21969                    } else {
21970                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21971                    }
21972                }
21973
21974                // Try very hard to release any references to this package
21975                // so we don't risk the system server being killed due to
21976                // open FDs
21977                AttributeCache.instance().removePackage(ps.name);
21978            }
21979
21980            mSettings.writeLPr();
21981        }
21982        }
21983
21984        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21985        sendResourcesChangedBroadcast(false, false, unloaded, null);
21986        mLoadedVolumes.remove(vol.getId());
21987
21988        // Try very hard to release any references to this path so we don't risk
21989        // the system server being killed due to open FDs
21990        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21991
21992        for (int i = 0; i < 3; i++) {
21993            System.gc();
21994            System.runFinalization();
21995        }
21996    }
21997
21998    private void assertPackageKnown(String volumeUuid, String packageName)
21999            throws PackageManagerException {
22000        synchronized (mPackages) {
22001            // Normalize package name to handle renamed packages
22002            packageName = normalizePackageNameLPr(packageName);
22003
22004            final PackageSetting ps = mSettings.mPackages.get(packageName);
22005            if (ps == null) {
22006                throw new PackageManagerException("Package " + packageName + " is unknown");
22007            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22008                throw new PackageManagerException(
22009                        "Package " + packageName + " found on unknown volume " + volumeUuid
22010                                + "; expected volume " + ps.volumeUuid);
22011            }
22012        }
22013    }
22014
22015    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22016            throws PackageManagerException {
22017        synchronized (mPackages) {
22018            // Normalize package name to handle renamed packages
22019            packageName = normalizePackageNameLPr(packageName);
22020
22021            final PackageSetting ps = mSettings.mPackages.get(packageName);
22022            if (ps == null) {
22023                throw new PackageManagerException("Package " + packageName + " is unknown");
22024            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22025                throw new PackageManagerException(
22026                        "Package " + packageName + " found on unknown volume " + volumeUuid
22027                                + "; expected volume " + ps.volumeUuid);
22028            } else if (!ps.getInstalled(userId)) {
22029                throw new PackageManagerException(
22030                        "Package " + packageName + " not installed for user " + userId);
22031            }
22032        }
22033    }
22034
22035    private List<String> collectAbsoluteCodePaths() {
22036        synchronized (mPackages) {
22037            List<String> codePaths = new ArrayList<>();
22038            final int packageCount = mSettings.mPackages.size();
22039            for (int i = 0; i < packageCount; i++) {
22040                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22041                codePaths.add(ps.codePath.getAbsolutePath());
22042            }
22043            return codePaths;
22044        }
22045    }
22046
22047    /**
22048     * Examine all apps present on given mounted volume, and destroy apps that
22049     * aren't expected, either due to uninstallation or reinstallation on
22050     * another volume.
22051     */
22052    private void reconcileApps(String volumeUuid) {
22053        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22054        List<File> filesToDelete = null;
22055
22056        final File[] files = FileUtils.listFilesOrEmpty(
22057                Environment.getDataAppDirectory(volumeUuid));
22058        for (File file : files) {
22059            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22060                    && !PackageInstallerService.isStageName(file.getName());
22061            if (!isPackage) {
22062                // Ignore entries which are not packages
22063                continue;
22064            }
22065
22066            String absolutePath = file.getAbsolutePath();
22067
22068            boolean pathValid = false;
22069            final int absoluteCodePathCount = absoluteCodePaths.size();
22070            for (int i = 0; i < absoluteCodePathCount; i++) {
22071                String absoluteCodePath = absoluteCodePaths.get(i);
22072                if (absolutePath.startsWith(absoluteCodePath)) {
22073                    pathValid = true;
22074                    break;
22075                }
22076            }
22077
22078            if (!pathValid) {
22079                if (filesToDelete == null) {
22080                    filesToDelete = new ArrayList<>();
22081                }
22082                filesToDelete.add(file);
22083            }
22084        }
22085
22086        if (filesToDelete != null) {
22087            final int fileToDeleteCount = filesToDelete.size();
22088            for (int i = 0; i < fileToDeleteCount; i++) {
22089                File fileToDelete = filesToDelete.get(i);
22090                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22091                synchronized (mInstallLock) {
22092                    removeCodePathLI(fileToDelete);
22093                }
22094            }
22095        }
22096    }
22097
22098    /**
22099     * Reconcile all app data for the given user.
22100     * <p>
22101     * Verifies that directories exist and that ownership and labeling is
22102     * correct for all installed apps on all mounted volumes.
22103     */
22104    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22105        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22106        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22107            final String volumeUuid = vol.getFsUuid();
22108            synchronized (mInstallLock) {
22109                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22110            }
22111        }
22112    }
22113
22114    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22115            boolean migrateAppData) {
22116        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22117    }
22118
22119    /**
22120     * Reconcile all app data on given mounted volume.
22121     * <p>
22122     * Destroys app data that isn't expected, either due to uninstallation or
22123     * reinstallation on another volume.
22124     * <p>
22125     * Verifies that directories exist and that ownership and labeling is
22126     * correct for all installed apps.
22127     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22128     */
22129    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22130            boolean migrateAppData, boolean onlyCoreApps) {
22131        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22132                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22133        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22134
22135        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22136        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22137
22138        // First look for stale data that doesn't belong, and check if things
22139        // have changed since we did our last restorecon
22140        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22141            if (StorageManager.isFileEncryptedNativeOrEmulated()
22142                    && !StorageManager.isUserKeyUnlocked(userId)) {
22143                throw new RuntimeException(
22144                        "Yikes, someone asked us to reconcile CE storage while " + userId
22145                                + " was still locked; this would have caused massive data loss!");
22146            }
22147
22148            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22149            for (File file : files) {
22150                final String packageName = file.getName();
22151                try {
22152                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22153                } catch (PackageManagerException e) {
22154                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22155                    try {
22156                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22157                                StorageManager.FLAG_STORAGE_CE, 0);
22158                    } catch (InstallerException e2) {
22159                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22160                    }
22161                }
22162            }
22163        }
22164        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22165            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22166            for (File file : files) {
22167                final String packageName = file.getName();
22168                try {
22169                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22170                } catch (PackageManagerException e) {
22171                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22172                    try {
22173                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22174                                StorageManager.FLAG_STORAGE_DE, 0);
22175                    } catch (InstallerException e2) {
22176                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22177                    }
22178                }
22179            }
22180        }
22181
22182        // Ensure that data directories are ready to roll for all packages
22183        // installed for this volume and user
22184        final List<PackageSetting> packages;
22185        synchronized (mPackages) {
22186            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22187        }
22188        int preparedCount = 0;
22189        for (PackageSetting ps : packages) {
22190            final String packageName = ps.name;
22191            if (ps.pkg == null) {
22192                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22193                // TODO: might be due to legacy ASEC apps; we should circle back
22194                // and reconcile again once they're scanned
22195                continue;
22196            }
22197            // Skip non-core apps if requested
22198            if (onlyCoreApps && !ps.pkg.coreApp) {
22199                result.add(packageName);
22200                continue;
22201            }
22202
22203            if (ps.getInstalled(userId)) {
22204                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22205                preparedCount++;
22206            }
22207        }
22208
22209        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22210        return result;
22211    }
22212
22213    /**
22214     * Prepare app data for the given app just after it was installed or
22215     * upgraded. This method carefully only touches users that it's installed
22216     * for, and it forces a restorecon to handle any seinfo changes.
22217     * <p>
22218     * Verifies that directories exist and that ownership and labeling is
22219     * correct for all installed apps. If there is an ownership mismatch, it
22220     * will try recovering system apps by wiping data; third-party app data is
22221     * left intact.
22222     * <p>
22223     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22224     */
22225    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22226        final PackageSetting ps;
22227        synchronized (mPackages) {
22228            ps = mSettings.mPackages.get(pkg.packageName);
22229            mSettings.writeKernelMappingLPr(ps);
22230        }
22231
22232        final UserManager um = mContext.getSystemService(UserManager.class);
22233        UserManagerInternal umInternal = getUserManagerInternal();
22234        for (UserInfo user : um.getUsers()) {
22235            final int flags;
22236            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22237                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22238            } else if (umInternal.isUserRunning(user.id)) {
22239                flags = StorageManager.FLAG_STORAGE_DE;
22240            } else {
22241                continue;
22242            }
22243
22244            if (ps.getInstalled(user.id)) {
22245                // TODO: when user data is locked, mark that we're still dirty
22246                prepareAppDataLIF(pkg, user.id, flags);
22247            }
22248        }
22249    }
22250
22251    /**
22252     * Prepare app data for the given app.
22253     * <p>
22254     * Verifies that directories exist and that ownership and labeling is
22255     * correct for all installed apps. If there is an ownership mismatch, this
22256     * will try recovering system apps by wiping data; third-party app data is
22257     * left intact.
22258     */
22259    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22260        if (pkg == null) {
22261            Slog.wtf(TAG, "Package was null!", new Throwable());
22262            return;
22263        }
22264        prepareAppDataLeafLIF(pkg, userId, flags);
22265        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22266        for (int i = 0; i < childCount; i++) {
22267            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22268        }
22269    }
22270
22271    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22272            boolean maybeMigrateAppData) {
22273        prepareAppDataLIF(pkg, userId, flags);
22274
22275        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22276            // We may have just shuffled around app data directories, so
22277            // prepare them one more time
22278            prepareAppDataLIF(pkg, userId, flags);
22279        }
22280    }
22281
22282    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22283        if (DEBUG_APP_DATA) {
22284            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22285                    + Integer.toHexString(flags));
22286        }
22287
22288        final String volumeUuid = pkg.volumeUuid;
22289        final String packageName = pkg.packageName;
22290        final ApplicationInfo app = pkg.applicationInfo;
22291        final int appId = UserHandle.getAppId(app.uid);
22292
22293        Preconditions.checkNotNull(app.seInfo);
22294
22295        long ceDataInode = -1;
22296        try {
22297            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22298                    appId, app.seInfo, app.targetSdkVersion);
22299        } catch (InstallerException e) {
22300            if (app.isSystemApp()) {
22301                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22302                        + ", but trying to recover: " + e);
22303                destroyAppDataLeafLIF(pkg, userId, flags);
22304                try {
22305                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22306                            appId, app.seInfo, app.targetSdkVersion);
22307                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22308                } catch (InstallerException e2) {
22309                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22310                }
22311            } else {
22312                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22313            }
22314        }
22315        // Prepare the application profiles.
22316        mArtManagerService.prepareAppProfiles(pkg, userId);
22317
22318        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22319            // TODO: mark this structure as dirty so we persist it!
22320            synchronized (mPackages) {
22321                final PackageSetting ps = mSettings.mPackages.get(packageName);
22322                if (ps != null) {
22323                    ps.setCeDataInode(ceDataInode, userId);
22324                }
22325            }
22326        }
22327
22328        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22329    }
22330
22331    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22332        if (pkg == null) {
22333            Slog.wtf(TAG, "Package was null!", new Throwable());
22334            return;
22335        }
22336        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22337        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22338        for (int i = 0; i < childCount; i++) {
22339            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22340        }
22341    }
22342
22343    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22344        final String volumeUuid = pkg.volumeUuid;
22345        final String packageName = pkg.packageName;
22346        final ApplicationInfo app = pkg.applicationInfo;
22347
22348        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22349            // Create a native library symlink only if we have native libraries
22350            // and if the native libraries are 32 bit libraries. We do not provide
22351            // this symlink for 64 bit libraries.
22352            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22353                final String nativeLibPath = app.nativeLibraryDir;
22354                try {
22355                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22356                            nativeLibPath, userId);
22357                } catch (InstallerException e) {
22358                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22359                }
22360            }
22361        }
22362    }
22363
22364    /**
22365     * For system apps on non-FBE devices, this method migrates any existing
22366     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22367     * requested by the app.
22368     */
22369    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22370        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22371                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22372            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22373                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22374            try {
22375                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22376                        storageTarget);
22377            } catch (InstallerException e) {
22378                logCriticalInfo(Log.WARN,
22379                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22380            }
22381            return true;
22382        } else {
22383            return false;
22384        }
22385    }
22386
22387    public PackageFreezer freezePackage(String packageName, String killReason) {
22388        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22389    }
22390
22391    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22392        return new PackageFreezer(packageName, userId, killReason);
22393    }
22394
22395    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22396            String killReason) {
22397        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22398    }
22399
22400    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22401            String killReason) {
22402        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22403            return new PackageFreezer();
22404        } else {
22405            return freezePackage(packageName, userId, killReason);
22406        }
22407    }
22408
22409    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22410            String killReason) {
22411        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22412    }
22413
22414    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22415            String killReason) {
22416        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22417            return new PackageFreezer();
22418        } else {
22419            return freezePackage(packageName, userId, killReason);
22420        }
22421    }
22422
22423    /**
22424     * Class that freezes and kills the given package upon creation, and
22425     * unfreezes it upon closing. This is typically used when doing surgery on
22426     * app code/data to prevent the app from running while you're working.
22427     */
22428    private class PackageFreezer implements AutoCloseable {
22429        private final String mPackageName;
22430        private final PackageFreezer[] mChildren;
22431
22432        private final boolean mWeFroze;
22433
22434        private final AtomicBoolean mClosed = new AtomicBoolean();
22435        private final CloseGuard mCloseGuard = CloseGuard.get();
22436
22437        /**
22438         * Create and return a stub freezer that doesn't actually do anything,
22439         * typically used when someone requested
22440         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22441         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22442         */
22443        public PackageFreezer() {
22444            mPackageName = null;
22445            mChildren = null;
22446            mWeFroze = false;
22447            mCloseGuard.open("close");
22448        }
22449
22450        public PackageFreezer(String packageName, int userId, String killReason) {
22451            synchronized (mPackages) {
22452                mPackageName = packageName;
22453                mWeFroze = mFrozenPackages.add(mPackageName);
22454
22455                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22456                if (ps != null) {
22457                    killApplication(ps.name, ps.appId, userId, killReason);
22458                }
22459
22460                final PackageParser.Package p = mPackages.get(packageName);
22461                if (p != null && p.childPackages != null) {
22462                    final int N = p.childPackages.size();
22463                    mChildren = new PackageFreezer[N];
22464                    for (int i = 0; i < N; i++) {
22465                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22466                                userId, killReason);
22467                    }
22468                } else {
22469                    mChildren = null;
22470                }
22471            }
22472            mCloseGuard.open("close");
22473        }
22474
22475        @Override
22476        protected void finalize() throws Throwable {
22477            try {
22478                if (mCloseGuard != null) {
22479                    mCloseGuard.warnIfOpen();
22480                }
22481
22482                close();
22483            } finally {
22484                super.finalize();
22485            }
22486        }
22487
22488        @Override
22489        public void close() {
22490            mCloseGuard.close();
22491            if (mClosed.compareAndSet(false, true)) {
22492                synchronized (mPackages) {
22493                    if (mWeFroze) {
22494                        mFrozenPackages.remove(mPackageName);
22495                    }
22496
22497                    if (mChildren != null) {
22498                        for (PackageFreezer freezer : mChildren) {
22499                            freezer.close();
22500                        }
22501                    }
22502                }
22503            }
22504        }
22505    }
22506
22507    /**
22508     * Verify that given package is currently frozen.
22509     */
22510    private void checkPackageFrozen(String packageName) {
22511        synchronized (mPackages) {
22512            if (!mFrozenPackages.contains(packageName)) {
22513                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22514            }
22515        }
22516    }
22517
22518    @Override
22519    public int movePackage(final String packageName, final String volumeUuid) {
22520        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22521
22522        final int callingUid = Binder.getCallingUid();
22523        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22524        final int moveId = mNextMoveId.getAndIncrement();
22525        mHandler.post(new Runnable() {
22526            @Override
22527            public void run() {
22528                try {
22529                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22530                } catch (PackageManagerException e) {
22531                    Slog.w(TAG, "Failed to move " + packageName, e);
22532                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22533                }
22534            }
22535        });
22536        return moveId;
22537    }
22538
22539    private void movePackageInternal(final String packageName, final String volumeUuid,
22540            final int moveId, final int callingUid, UserHandle user)
22541                    throws PackageManagerException {
22542        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22543        final PackageManager pm = mContext.getPackageManager();
22544
22545        final boolean currentAsec;
22546        final String currentVolumeUuid;
22547        final File codeFile;
22548        final String installerPackageName;
22549        final String packageAbiOverride;
22550        final int appId;
22551        final String seinfo;
22552        final String label;
22553        final int targetSdkVersion;
22554        final PackageFreezer freezer;
22555        final int[] installedUserIds;
22556
22557        // reader
22558        synchronized (mPackages) {
22559            final PackageParser.Package pkg = mPackages.get(packageName);
22560            final PackageSetting ps = mSettings.mPackages.get(packageName);
22561            if (pkg == null
22562                    || ps == null
22563                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22564                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22565            }
22566            if (pkg.applicationInfo.isSystemApp()) {
22567                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22568                        "Cannot move system application");
22569            }
22570
22571            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22572            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22573                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22574            if (isInternalStorage && !allow3rdPartyOnInternal) {
22575                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22576                        "3rd party apps are not allowed on internal storage");
22577            }
22578
22579            if (pkg.applicationInfo.isExternalAsec()) {
22580                currentAsec = true;
22581                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22582            } else if (pkg.applicationInfo.isForwardLocked()) {
22583                currentAsec = true;
22584                currentVolumeUuid = "forward_locked";
22585            } else {
22586                currentAsec = false;
22587                currentVolumeUuid = ps.volumeUuid;
22588
22589                final File probe = new File(pkg.codePath);
22590                final File probeOat = new File(probe, "oat");
22591                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22592                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22593                            "Move only supported for modern cluster style installs");
22594                }
22595            }
22596
22597            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22598                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22599                        "Package already moved to " + volumeUuid);
22600            }
22601            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22602                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22603                        "Device admin cannot be moved");
22604            }
22605
22606            if (mFrozenPackages.contains(packageName)) {
22607                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22608                        "Failed to move already frozen package");
22609            }
22610
22611            codeFile = new File(pkg.codePath);
22612            installerPackageName = ps.installerPackageName;
22613            packageAbiOverride = ps.cpuAbiOverrideString;
22614            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22615            seinfo = pkg.applicationInfo.seInfo;
22616            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22617            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22618            freezer = freezePackage(packageName, "movePackageInternal");
22619            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22620        }
22621
22622        final Bundle extras = new Bundle();
22623        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22624        extras.putString(Intent.EXTRA_TITLE, label);
22625        mMoveCallbacks.notifyCreated(moveId, extras);
22626
22627        int installFlags;
22628        final boolean moveCompleteApp;
22629        final File measurePath;
22630
22631        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22632            installFlags = INSTALL_INTERNAL;
22633            moveCompleteApp = !currentAsec;
22634            measurePath = Environment.getDataAppDirectory(volumeUuid);
22635        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22636            installFlags = INSTALL_EXTERNAL;
22637            moveCompleteApp = false;
22638            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22639        } else {
22640            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22641            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22642                    || !volume.isMountedWritable()) {
22643                freezer.close();
22644                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22645                        "Move location not mounted private volume");
22646            }
22647
22648            Preconditions.checkState(!currentAsec);
22649
22650            installFlags = INSTALL_INTERNAL;
22651            moveCompleteApp = true;
22652            measurePath = Environment.getDataAppDirectory(volumeUuid);
22653        }
22654
22655        // If we're moving app data around, we need all the users unlocked
22656        if (moveCompleteApp) {
22657            for (int userId : installedUserIds) {
22658                if (StorageManager.isFileEncryptedNativeOrEmulated()
22659                        && !StorageManager.isUserKeyUnlocked(userId)) {
22660                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22661                            "User " + userId + " must be unlocked");
22662                }
22663            }
22664        }
22665
22666        final PackageStats stats = new PackageStats(null, -1);
22667        synchronized (mInstaller) {
22668            for (int userId : installedUserIds) {
22669                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22670                    freezer.close();
22671                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22672                            "Failed to measure package size");
22673                }
22674            }
22675        }
22676
22677        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22678                + stats.dataSize);
22679
22680        final long startFreeBytes = measurePath.getUsableSpace();
22681        final long sizeBytes;
22682        if (moveCompleteApp) {
22683            sizeBytes = stats.codeSize + stats.dataSize;
22684        } else {
22685            sizeBytes = stats.codeSize;
22686        }
22687
22688        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22689            freezer.close();
22690            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22691                    "Not enough free space to move");
22692        }
22693
22694        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22695
22696        final CountDownLatch installedLatch = new CountDownLatch(1);
22697        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22698            @Override
22699            public void onUserActionRequired(Intent intent) throws RemoteException {
22700                throw new IllegalStateException();
22701            }
22702
22703            @Override
22704            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22705                    Bundle extras) throws RemoteException {
22706                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22707                        + PackageManager.installStatusToString(returnCode, msg));
22708
22709                installedLatch.countDown();
22710                freezer.close();
22711
22712                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22713                switch (status) {
22714                    case PackageInstaller.STATUS_SUCCESS:
22715                        mMoveCallbacks.notifyStatusChanged(moveId,
22716                                PackageManager.MOVE_SUCCEEDED);
22717                        break;
22718                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22719                        mMoveCallbacks.notifyStatusChanged(moveId,
22720                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22721                        break;
22722                    default:
22723                        mMoveCallbacks.notifyStatusChanged(moveId,
22724                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22725                        break;
22726                }
22727            }
22728        };
22729
22730        final MoveInfo move;
22731        if (moveCompleteApp) {
22732            // Kick off a thread to report progress estimates
22733            new Thread() {
22734                @Override
22735                public void run() {
22736                    while (true) {
22737                        try {
22738                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22739                                break;
22740                            }
22741                        } catch (InterruptedException ignored) {
22742                        }
22743
22744                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22745                        final int progress = 10 + (int) MathUtils.constrain(
22746                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22747                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22748                    }
22749                }
22750            }.start();
22751
22752            final String dataAppName = codeFile.getName();
22753            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22754                    dataAppName, appId, seinfo, targetSdkVersion);
22755        } else {
22756            move = null;
22757        }
22758
22759        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22760
22761        final Message msg = mHandler.obtainMessage(INIT_COPY);
22762        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22763        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22764                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22765                packageAbiOverride, null /*grantedPermissions*/,
22766                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22767        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22768        msg.obj = params;
22769
22770        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22771                System.identityHashCode(msg.obj));
22772        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22773                System.identityHashCode(msg.obj));
22774
22775        mHandler.sendMessage(msg);
22776    }
22777
22778    @Override
22779    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22780        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22781
22782        final int realMoveId = mNextMoveId.getAndIncrement();
22783        final Bundle extras = new Bundle();
22784        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22785        mMoveCallbacks.notifyCreated(realMoveId, extras);
22786
22787        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22788            @Override
22789            public void onCreated(int moveId, Bundle extras) {
22790                // Ignored
22791            }
22792
22793            @Override
22794            public void onStatusChanged(int moveId, int status, long estMillis) {
22795                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22796            }
22797        };
22798
22799        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22800        storage.setPrimaryStorageUuid(volumeUuid, callback);
22801        return realMoveId;
22802    }
22803
22804    @Override
22805    public int getMoveStatus(int moveId) {
22806        mContext.enforceCallingOrSelfPermission(
22807                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22808        return mMoveCallbacks.mLastStatus.get(moveId);
22809    }
22810
22811    @Override
22812    public void registerMoveCallback(IPackageMoveObserver callback) {
22813        mContext.enforceCallingOrSelfPermission(
22814                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22815        mMoveCallbacks.register(callback);
22816    }
22817
22818    @Override
22819    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22820        mContext.enforceCallingOrSelfPermission(
22821                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22822        mMoveCallbacks.unregister(callback);
22823    }
22824
22825    @Override
22826    public boolean setInstallLocation(int loc) {
22827        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22828                null);
22829        if (getInstallLocation() == loc) {
22830            return true;
22831        }
22832        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22833                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22834            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22835                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22836            return true;
22837        }
22838        return false;
22839   }
22840
22841    @Override
22842    public int getInstallLocation() {
22843        // allow instant app access
22844        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22845                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22846                PackageHelper.APP_INSTALL_AUTO);
22847    }
22848
22849    /** Called by UserManagerService */
22850    void cleanUpUser(UserManagerService userManager, int userHandle) {
22851        synchronized (mPackages) {
22852            mDirtyUsers.remove(userHandle);
22853            mUserNeedsBadging.delete(userHandle);
22854            mSettings.removeUserLPw(userHandle);
22855            mPendingBroadcasts.remove(userHandle);
22856            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22857            removeUnusedPackagesLPw(userManager, userHandle);
22858        }
22859    }
22860
22861    /**
22862     * We're removing userHandle and would like to remove any downloaded packages
22863     * that are no longer in use by any other user.
22864     * @param userHandle the user being removed
22865     */
22866    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22867        final boolean DEBUG_CLEAN_APKS = false;
22868        int [] users = userManager.getUserIds();
22869        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22870        while (psit.hasNext()) {
22871            PackageSetting ps = psit.next();
22872            if (ps.pkg == null) {
22873                continue;
22874            }
22875            final String packageName = ps.pkg.packageName;
22876            // Skip over if system app
22877            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22878                continue;
22879            }
22880            if (DEBUG_CLEAN_APKS) {
22881                Slog.i(TAG, "Checking package " + packageName);
22882            }
22883            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22884            if (keep) {
22885                if (DEBUG_CLEAN_APKS) {
22886                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22887                }
22888            } else {
22889                for (int i = 0; i < users.length; i++) {
22890                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22891                        keep = true;
22892                        if (DEBUG_CLEAN_APKS) {
22893                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22894                                    + users[i]);
22895                        }
22896                        break;
22897                    }
22898                }
22899            }
22900            if (!keep) {
22901                if (DEBUG_CLEAN_APKS) {
22902                    Slog.i(TAG, "  Removing package " + packageName);
22903                }
22904                mHandler.post(new Runnable() {
22905                    public void run() {
22906                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22907                                userHandle, 0);
22908                    } //end run
22909                });
22910            }
22911        }
22912    }
22913
22914    /** Called by UserManagerService */
22915    void createNewUser(int userId, String[] disallowedPackages) {
22916        synchronized (mInstallLock) {
22917            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22918        }
22919        synchronized (mPackages) {
22920            scheduleWritePackageRestrictionsLocked(userId);
22921            scheduleWritePackageListLocked(userId);
22922            applyFactoryDefaultBrowserLPw(userId);
22923            primeDomainVerificationsLPw(userId);
22924        }
22925    }
22926
22927    void onNewUserCreated(final int userId) {
22928        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22929        synchronized(mPackages) {
22930            // If permission review for legacy apps is required, we represent
22931            // dagerous permissions for such apps as always granted runtime
22932            // permissions to keep per user flag state whether review is needed.
22933            // Hence, if a new user is added we have to propagate dangerous
22934            // permission grants for these legacy apps.
22935            if (mSettings.mPermissions.mPermissionReviewRequired) {
22936// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22937                mPermissionManager.updateAllPermissions(
22938                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22939                        mPermissionCallback);
22940            }
22941        }
22942    }
22943
22944    @Override
22945    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22946        mContext.enforceCallingOrSelfPermission(
22947                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22948                "Only package verification agents can read the verifier device identity");
22949
22950        synchronized (mPackages) {
22951            return mSettings.getVerifierDeviceIdentityLPw();
22952        }
22953    }
22954
22955    @Override
22956    public void setPermissionEnforced(String permission, boolean enforced) {
22957        // TODO: Now that we no longer change GID for storage, this should to away.
22958        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22959                "setPermissionEnforced");
22960        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22961            synchronized (mPackages) {
22962                if (mSettings.mReadExternalStorageEnforced == null
22963                        || mSettings.mReadExternalStorageEnforced != enforced) {
22964                    mSettings.mReadExternalStorageEnforced =
22965                            enforced ? Boolean.TRUE : Boolean.FALSE;
22966                    mSettings.writeLPr();
22967                }
22968            }
22969            // kill any non-foreground processes so we restart them and
22970            // grant/revoke the GID.
22971            final IActivityManager am = ActivityManager.getService();
22972            if (am != null) {
22973                final long token = Binder.clearCallingIdentity();
22974                try {
22975                    am.killProcessesBelowForeground("setPermissionEnforcement");
22976                } catch (RemoteException e) {
22977                } finally {
22978                    Binder.restoreCallingIdentity(token);
22979                }
22980            }
22981        } else {
22982            throw new IllegalArgumentException("No selective enforcement for " + permission);
22983        }
22984    }
22985
22986    @Override
22987    @Deprecated
22988    public boolean isPermissionEnforced(String permission) {
22989        // allow instant applications
22990        return true;
22991    }
22992
22993    @Override
22994    public boolean isStorageLow() {
22995        // allow instant applications
22996        final long token = Binder.clearCallingIdentity();
22997        try {
22998            final DeviceStorageMonitorInternal
22999                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23000            if (dsm != null) {
23001                return dsm.isMemoryLow();
23002            } else {
23003                return false;
23004            }
23005        } finally {
23006            Binder.restoreCallingIdentity(token);
23007        }
23008    }
23009
23010    @Override
23011    public IPackageInstaller getPackageInstaller() {
23012        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23013            return null;
23014        }
23015        return mInstallerService;
23016    }
23017
23018    @Override
23019    public IArtManager getArtManager() {
23020        return mArtManagerService;
23021    }
23022
23023    private boolean userNeedsBadging(int userId) {
23024        int index = mUserNeedsBadging.indexOfKey(userId);
23025        if (index < 0) {
23026            final UserInfo userInfo;
23027            final long token = Binder.clearCallingIdentity();
23028            try {
23029                userInfo = sUserManager.getUserInfo(userId);
23030            } finally {
23031                Binder.restoreCallingIdentity(token);
23032            }
23033            final boolean b;
23034            if (userInfo != null && userInfo.isManagedProfile()) {
23035                b = true;
23036            } else {
23037                b = false;
23038            }
23039            mUserNeedsBadging.put(userId, b);
23040            return b;
23041        }
23042        return mUserNeedsBadging.valueAt(index);
23043    }
23044
23045    @Override
23046    public KeySet getKeySetByAlias(String packageName, String alias) {
23047        if (packageName == null || alias == null) {
23048            return null;
23049        }
23050        synchronized(mPackages) {
23051            final PackageParser.Package pkg = mPackages.get(packageName);
23052            if (pkg == null) {
23053                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23054                throw new IllegalArgumentException("Unknown package: " + packageName);
23055            }
23056            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23057            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23058                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23059                throw new IllegalArgumentException("Unknown package: " + packageName);
23060            }
23061            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23062            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23063        }
23064    }
23065
23066    @Override
23067    public KeySet getSigningKeySet(String packageName) {
23068        if (packageName == null) {
23069            return null;
23070        }
23071        synchronized(mPackages) {
23072            final int callingUid = Binder.getCallingUid();
23073            final int callingUserId = UserHandle.getUserId(callingUid);
23074            final PackageParser.Package pkg = mPackages.get(packageName);
23075            if (pkg == null) {
23076                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23077                throw new IllegalArgumentException("Unknown package: " + packageName);
23078            }
23079            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23080            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23081                // filter and pretend the package doesn't exist
23082                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23083                        + ", uid:" + callingUid);
23084                throw new IllegalArgumentException("Unknown package: " + packageName);
23085            }
23086            if (pkg.applicationInfo.uid != callingUid
23087                    && Process.SYSTEM_UID != callingUid) {
23088                throw new SecurityException("May not access signing KeySet of other apps.");
23089            }
23090            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23091            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23092        }
23093    }
23094
23095    @Override
23096    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23097        final int callingUid = Binder.getCallingUid();
23098        if (getInstantAppPackageName(callingUid) != null) {
23099            return false;
23100        }
23101        if (packageName == null || ks == null) {
23102            return false;
23103        }
23104        synchronized(mPackages) {
23105            final PackageParser.Package pkg = mPackages.get(packageName);
23106            if (pkg == null
23107                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23108                            UserHandle.getUserId(callingUid))) {
23109                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23110                throw new IllegalArgumentException("Unknown package: " + packageName);
23111            }
23112            IBinder ksh = ks.getToken();
23113            if (ksh instanceof KeySetHandle) {
23114                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23115                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23116            }
23117            return false;
23118        }
23119    }
23120
23121    @Override
23122    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23123        final int callingUid = Binder.getCallingUid();
23124        if (getInstantAppPackageName(callingUid) != null) {
23125            return false;
23126        }
23127        if (packageName == null || ks == null) {
23128            return false;
23129        }
23130        synchronized(mPackages) {
23131            final PackageParser.Package pkg = mPackages.get(packageName);
23132            if (pkg == null
23133                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23134                            UserHandle.getUserId(callingUid))) {
23135                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23136                throw new IllegalArgumentException("Unknown package: " + packageName);
23137            }
23138            IBinder ksh = ks.getToken();
23139            if (ksh instanceof KeySetHandle) {
23140                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23141                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23142            }
23143            return false;
23144        }
23145    }
23146
23147    private void deletePackageIfUnusedLPr(final String packageName) {
23148        PackageSetting ps = mSettings.mPackages.get(packageName);
23149        if (ps == null) {
23150            return;
23151        }
23152        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23153            // TODO Implement atomic delete if package is unused
23154            // It is currently possible that the package will be deleted even if it is installed
23155            // after this method returns.
23156            mHandler.post(new Runnable() {
23157                public void run() {
23158                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23159                            0, PackageManager.DELETE_ALL_USERS);
23160                }
23161            });
23162        }
23163    }
23164
23165    /**
23166     * Check and throw if the given before/after packages would be considered a
23167     * downgrade.
23168     */
23169    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23170            throws PackageManagerException {
23171        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23172            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23173                    "Update version code " + after.versionCode + " is older than current "
23174                    + before.getLongVersionCode());
23175        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23176            if (after.baseRevisionCode < before.baseRevisionCode) {
23177                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23178                        "Update base revision code " + after.baseRevisionCode
23179                        + " is older than current " + before.baseRevisionCode);
23180            }
23181
23182            if (!ArrayUtils.isEmpty(after.splitNames)) {
23183                for (int i = 0; i < after.splitNames.length; i++) {
23184                    final String splitName = after.splitNames[i];
23185                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23186                    if (j != -1) {
23187                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23188                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23189                                    "Update split " + splitName + " revision code "
23190                                    + after.splitRevisionCodes[i] + " is older than current "
23191                                    + before.splitRevisionCodes[j]);
23192                        }
23193                    }
23194                }
23195            }
23196        }
23197    }
23198
23199    private static class MoveCallbacks extends Handler {
23200        private static final int MSG_CREATED = 1;
23201        private static final int MSG_STATUS_CHANGED = 2;
23202
23203        private final RemoteCallbackList<IPackageMoveObserver>
23204                mCallbacks = new RemoteCallbackList<>();
23205
23206        private final SparseIntArray mLastStatus = new SparseIntArray();
23207
23208        public MoveCallbacks(Looper looper) {
23209            super(looper);
23210        }
23211
23212        public void register(IPackageMoveObserver callback) {
23213            mCallbacks.register(callback);
23214        }
23215
23216        public void unregister(IPackageMoveObserver callback) {
23217            mCallbacks.unregister(callback);
23218        }
23219
23220        @Override
23221        public void handleMessage(Message msg) {
23222            final SomeArgs args = (SomeArgs) msg.obj;
23223            final int n = mCallbacks.beginBroadcast();
23224            for (int i = 0; i < n; i++) {
23225                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23226                try {
23227                    invokeCallback(callback, msg.what, args);
23228                } catch (RemoteException ignored) {
23229                }
23230            }
23231            mCallbacks.finishBroadcast();
23232            args.recycle();
23233        }
23234
23235        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23236                throws RemoteException {
23237            switch (what) {
23238                case MSG_CREATED: {
23239                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23240                    break;
23241                }
23242                case MSG_STATUS_CHANGED: {
23243                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23244                    break;
23245                }
23246            }
23247        }
23248
23249        private void notifyCreated(int moveId, Bundle extras) {
23250            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23251
23252            final SomeArgs args = SomeArgs.obtain();
23253            args.argi1 = moveId;
23254            args.arg2 = extras;
23255            obtainMessage(MSG_CREATED, args).sendToTarget();
23256        }
23257
23258        private void notifyStatusChanged(int moveId, int status) {
23259            notifyStatusChanged(moveId, status, -1);
23260        }
23261
23262        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23263            Slog.v(TAG, "Move " + moveId + " status " + status);
23264
23265            final SomeArgs args = SomeArgs.obtain();
23266            args.argi1 = moveId;
23267            args.argi2 = status;
23268            args.arg3 = estMillis;
23269            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23270
23271            synchronized (mLastStatus) {
23272                mLastStatus.put(moveId, status);
23273            }
23274        }
23275    }
23276
23277    private final static class OnPermissionChangeListeners extends Handler {
23278        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23279
23280        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23281                new RemoteCallbackList<>();
23282
23283        public OnPermissionChangeListeners(Looper looper) {
23284            super(looper);
23285        }
23286
23287        @Override
23288        public void handleMessage(Message msg) {
23289            switch (msg.what) {
23290                case MSG_ON_PERMISSIONS_CHANGED: {
23291                    final int uid = msg.arg1;
23292                    handleOnPermissionsChanged(uid);
23293                } break;
23294            }
23295        }
23296
23297        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23298            mPermissionListeners.register(listener);
23299
23300        }
23301
23302        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23303            mPermissionListeners.unregister(listener);
23304        }
23305
23306        public void onPermissionsChanged(int uid) {
23307            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23308                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23309            }
23310        }
23311
23312        private void handleOnPermissionsChanged(int uid) {
23313            final int count = mPermissionListeners.beginBroadcast();
23314            try {
23315                for (int i = 0; i < count; i++) {
23316                    IOnPermissionsChangeListener callback = mPermissionListeners
23317                            .getBroadcastItem(i);
23318                    try {
23319                        callback.onPermissionsChanged(uid);
23320                    } catch (RemoteException e) {
23321                        Log.e(TAG, "Permission listener is dead", e);
23322                    }
23323                }
23324            } finally {
23325                mPermissionListeners.finishBroadcast();
23326            }
23327        }
23328    }
23329
23330    private class PackageManagerNative extends IPackageManagerNative.Stub {
23331        @Override
23332        public String[] getNamesForUids(int[] uids) throws RemoteException {
23333            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23334            // massage results so they can be parsed by the native binder
23335            for (int i = results.length - 1; i >= 0; --i) {
23336                if (results[i] == null) {
23337                    results[i] = "";
23338                }
23339            }
23340            return results;
23341        }
23342
23343        // NB: this differentiates between preloads and sideloads
23344        @Override
23345        public String getInstallerForPackage(String packageName) throws RemoteException {
23346            final String installerName = getInstallerPackageName(packageName);
23347            if (!TextUtils.isEmpty(installerName)) {
23348                return installerName;
23349            }
23350            // differentiate between preload and sideload
23351            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23352            ApplicationInfo appInfo = getApplicationInfo(packageName,
23353                                    /*flags*/ 0,
23354                                    /*userId*/ callingUser);
23355            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23356                return "preload";
23357            }
23358            return "";
23359        }
23360
23361        @Override
23362        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23363            try {
23364                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23365                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23366                if (pInfo != null) {
23367                    return pInfo.getLongVersionCode();
23368                }
23369            } catch (Exception e) {
23370            }
23371            return 0;
23372        }
23373    }
23374
23375    private class PackageManagerInternalImpl extends PackageManagerInternal {
23376        @Override
23377        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23378                int flagValues, int userId) {
23379            PackageManagerService.this.updatePermissionFlags(
23380                    permName, packageName, flagMask, flagValues, userId);
23381        }
23382
23383        @Override
23384        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23385            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23386        }
23387
23388        @Override
23389        public boolean isInstantApp(String packageName, int userId) {
23390            return PackageManagerService.this.isInstantApp(packageName, userId);
23391        }
23392
23393        @Override
23394        public String getInstantAppPackageName(int uid) {
23395            return PackageManagerService.this.getInstantAppPackageName(uid);
23396        }
23397
23398        @Override
23399        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23400            synchronized (mPackages) {
23401                return PackageManagerService.this.filterAppAccessLPr(
23402                        (PackageSetting) pkg.mExtras, callingUid, userId);
23403            }
23404        }
23405
23406        @Override
23407        public PackageParser.Package getPackage(String packageName) {
23408            synchronized (mPackages) {
23409                packageName = resolveInternalPackageNameLPr(
23410                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23411                return mPackages.get(packageName);
23412            }
23413        }
23414
23415        @Override
23416        public PackageList getPackageList(PackageListObserver observer) {
23417            synchronized (mPackages) {
23418                final int N = mPackages.size();
23419                final ArrayList<String> list = new ArrayList<>(N);
23420                for (int i = 0; i < N; i++) {
23421                    list.add(mPackages.keyAt(i));
23422                }
23423                final PackageList packageList = new PackageList(list, observer);
23424                if (observer != null) {
23425                    mPackageListObservers.add(packageList);
23426                }
23427                return packageList;
23428            }
23429        }
23430
23431        @Override
23432        public void removePackageListObserver(PackageListObserver observer) {
23433            synchronized (mPackages) {
23434                mPackageListObservers.remove(observer);
23435            }
23436        }
23437
23438        @Override
23439        public PackageParser.Package getDisabledPackage(String packageName) {
23440            synchronized (mPackages) {
23441                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23442                return (ps != null) ? ps.pkg : null;
23443            }
23444        }
23445
23446        @Override
23447        public String getKnownPackageName(int knownPackage, int userId) {
23448            switch(knownPackage) {
23449                case PackageManagerInternal.PACKAGE_BROWSER:
23450                    return getDefaultBrowserPackageName(userId);
23451                case PackageManagerInternal.PACKAGE_INSTALLER:
23452                    return mRequiredInstallerPackage;
23453                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23454                    return mSetupWizardPackage;
23455                case PackageManagerInternal.PACKAGE_SYSTEM:
23456                    return "android";
23457                case PackageManagerInternal.PACKAGE_VERIFIER:
23458                    return mRequiredVerifierPackage;
23459            }
23460            return null;
23461        }
23462
23463        @Override
23464        public boolean isResolveActivityComponent(ComponentInfo component) {
23465            return mResolveActivity.packageName.equals(component.packageName)
23466                    && mResolveActivity.name.equals(component.name);
23467        }
23468
23469        @Override
23470        public void setLocationPackagesProvider(PackagesProvider provider) {
23471            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23472        }
23473
23474        @Override
23475        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23476            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23477        }
23478
23479        @Override
23480        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23481            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23482        }
23483
23484        @Override
23485        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23486            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23487        }
23488
23489        @Override
23490        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23491            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23492        }
23493
23494        @Override
23495        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23496            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23497        }
23498
23499        @Override
23500        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23501            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23502        }
23503
23504        @Override
23505        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23506            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23507        }
23508
23509        @Override
23510        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23511            synchronized (mPackages) {
23512                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23513            }
23514            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23515        }
23516
23517        @Override
23518        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23519            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23520                    packageName, userId);
23521        }
23522
23523        @Override
23524        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23525            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23526                    packageName, userId);
23527        }
23528
23529        @Override
23530        public void setKeepUninstalledPackages(final List<String> packageList) {
23531            Preconditions.checkNotNull(packageList);
23532            List<String> removedFromList = null;
23533            synchronized (mPackages) {
23534                if (mKeepUninstalledPackages != null) {
23535                    final int packagesCount = mKeepUninstalledPackages.size();
23536                    for (int i = 0; i < packagesCount; i++) {
23537                        String oldPackage = mKeepUninstalledPackages.get(i);
23538                        if (packageList != null && packageList.contains(oldPackage)) {
23539                            continue;
23540                        }
23541                        if (removedFromList == null) {
23542                            removedFromList = new ArrayList<>();
23543                        }
23544                        removedFromList.add(oldPackage);
23545                    }
23546                }
23547                mKeepUninstalledPackages = new ArrayList<>(packageList);
23548                if (removedFromList != null) {
23549                    final int removedCount = removedFromList.size();
23550                    for (int i = 0; i < removedCount; i++) {
23551                        deletePackageIfUnusedLPr(removedFromList.get(i));
23552                    }
23553                }
23554            }
23555        }
23556
23557        @Override
23558        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23559            synchronized (mPackages) {
23560                return mPermissionManager.isPermissionsReviewRequired(
23561                        mPackages.get(packageName), userId);
23562            }
23563        }
23564
23565        @Override
23566        public PackageInfo getPackageInfo(
23567                String packageName, int flags, int filterCallingUid, int userId) {
23568            return PackageManagerService.this
23569                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23570                            flags, filterCallingUid, userId);
23571        }
23572
23573        @Override
23574        public int getPackageUid(String packageName, int flags, int userId) {
23575            return PackageManagerService.this
23576                    .getPackageUid(packageName, flags, userId);
23577        }
23578
23579        @Override
23580        public ApplicationInfo getApplicationInfo(
23581                String packageName, int flags, int filterCallingUid, int userId) {
23582            return PackageManagerService.this
23583                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23584        }
23585
23586        @Override
23587        public ActivityInfo getActivityInfo(
23588                ComponentName component, int flags, int filterCallingUid, int userId) {
23589            return PackageManagerService.this
23590                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23591        }
23592
23593        @Override
23594        public List<ResolveInfo> queryIntentActivities(
23595                Intent intent, int flags, int filterCallingUid, int userId) {
23596            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23597            return PackageManagerService.this
23598                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23599                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23600        }
23601
23602        @Override
23603        public List<ResolveInfo> queryIntentServices(
23604                Intent intent, int flags, int callingUid, int userId) {
23605            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23606            return PackageManagerService.this
23607                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23608                            false);
23609        }
23610
23611        @Override
23612        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23613                int userId) {
23614            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23615        }
23616
23617        @Override
23618        public void setDeviceAndProfileOwnerPackages(
23619                int deviceOwnerUserId, String deviceOwnerPackage,
23620                SparseArray<String> profileOwnerPackages) {
23621            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23622                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23623        }
23624
23625        @Override
23626        public boolean isPackageDataProtected(int userId, String packageName) {
23627            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23628        }
23629
23630        @Override
23631        public boolean isPackageEphemeral(int userId, String packageName) {
23632            synchronized (mPackages) {
23633                final PackageSetting ps = mSettings.mPackages.get(packageName);
23634                return ps != null ? ps.getInstantApp(userId) : false;
23635            }
23636        }
23637
23638        @Override
23639        public boolean wasPackageEverLaunched(String packageName, int userId) {
23640            synchronized (mPackages) {
23641                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23642            }
23643        }
23644
23645        @Override
23646        public void grantRuntimePermission(String packageName, String permName, int userId,
23647                boolean overridePolicy) {
23648            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23649                    permName, packageName, overridePolicy, getCallingUid(), userId,
23650                    mPermissionCallback);
23651        }
23652
23653        @Override
23654        public void revokeRuntimePermission(String packageName, String permName, int userId,
23655                boolean overridePolicy) {
23656            mPermissionManager.revokeRuntimePermission(
23657                    permName, packageName, overridePolicy, getCallingUid(), userId,
23658                    mPermissionCallback);
23659        }
23660
23661        @Override
23662        public String getNameForUid(int uid) {
23663            return PackageManagerService.this.getNameForUid(uid);
23664        }
23665
23666        @Override
23667        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23668                Intent origIntent, String resolvedType, String callingPackage,
23669                Bundle verificationBundle, int userId) {
23670            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23671                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23672                    userId);
23673        }
23674
23675        @Override
23676        public void grantEphemeralAccess(int userId, Intent intent,
23677                int targetAppId, int ephemeralAppId) {
23678            synchronized (mPackages) {
23679                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23680                        targetAppId, ephemeralAppId);
23681            }
23682        }
23683
23684        @Override
23685        public boolean isInstantAppInstallerComponent(ComponentName component) {
23686            synchronized (mPackages) {
23687                return mInstantAppInstallerActivity != null
23688                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23689            }
23690        }
23691
23692        @Override
23693        public void pruneInstantApps() {
23694            mInstantAppRegistry.pruneInstantApps();
23695        }
23696
23697        @Override
23698        public String getSetupWizardPackageName() {
23699            return mSetupWizardPackage;
23700        }
23701
23702        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23703            if (policy != null) {
23704                mExternalSourcesPolicy = policy;
23705            }
23706        }
23707
23708        @Override
23709        public boolean isPackagePersistent(String packageName) {
23710            synchronized (mPackages) {
23711                PackageParser.Package pkg = mPackages.get(packageName);
23712                return pkg != null
23713                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23714                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23715                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23716                        : false;
23717            }
23718        }
23719
23720        @Override
23721        public boolean isLegacySystemApp(Package pkg) {
23722            synchronized (mPackages) {
23723                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23724                return mPromoteSystemApps
23725                        && ps.isSystem()
23726                        && mExistingSystemPackages.contains(ps.name);
23727            }
23728        }
23729
23730        @Override
23731        public List<PackageInfo> getOverlayPackages(int userId) {
23732            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23733            synchronized (mPackages) {
23734                for (PackageParser.Package p : mPackages.values()) {
23735                    if (p.mOverlayTarget != null) {
23736                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23737                        if (pkg != null) {
23738                            overlayPackages.add(pkg);
23739                        }
23740                    }
23741                }
23742            }
23743            return overlayPackages;
23744        }
23745
23746        @Override
23747        public List<String> getTargetPackageNames(int userId) {
23748            List<String> targetPackages = new ArrayList<>();
23749            synchronized (mPackages) {
23750                for (PackageParser.Package p : mPackages.values()) {
23751                    if (p.mOverlayTarget == null) {
23752                        targetPackages.add(p.packageName);
23753                    }
23754                }
23755            }
23756            return targetPackages;
23757        }
23758
23759        @Override
23760        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23761                @Nullable List<String> overlayPackageNames) {
23762            synchronized (mPackages) {
23763                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23764                    Slog.e(TAG, "failed to find package " + targetPackageName);
23765                    return false;
23766                }
23767                ArrayList<String> overlayPaths = null;
23768                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23769                    final int N = overlayPackageNames.size();
23770                    overlayPaths = new ArrayList<>(N);
23771                    for (int i = 0; i < N; i++) {
23772                        final String packageName = overlayPackageNames.get(i);
23773                        final PackageParser.Package pkg = mPackages.get(packageName);
23774                        if (pkg == null) {
23775                            Slog.e(TAG, "failed to find package " + packageName);
23776                            return false;
23777                        }
23778                        overlayPaths.add(pkg.baseCodePath);
23779                    }
23780                }
23781
23782                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23783                ps.setOverlayPaths(overlayPaths, userId);
23784                return true;
23785            }
23786        }
23787
23788        @Override
23789        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23790                int flags, int userId, boolean resolveForStart) {
23791            return resolveIntentInternal(
23792                    intent, resolvedType, flags, userId, resolveForStart);
23793        }
23794
23795        @Override
23796        public ResolveInfo resolveService(Intent intent, String resolvedType,
23797                int flags, int userId, int callingUid) {
23798            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23799        }
23800
23801        @Override
23802        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23803            return PackageManagerService.this.resolveContentProviderInternal(
23804                    name, flags, userId);
23805        }
23806
23807        @Override
23808        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23809            synchronized (mPackages) {
23810                mIsolatedOwners.put(isolatedUid, ownerUid);
23811            }
23812        }
23813
23814        @Override
23815        public void removeIsolatedUid(int isolatedUid) {
23816            synchronized (mPackages) {
23817                mIsolatedOwners.delete(isolatedUid);
23818            }
23819        }
23820
23821        @Override
23822        public int getUidTargetSdkVersion(int uid) {
23823            synchronized (mPackages) {
23824                return getUidTargetSdkVersionLockedLPr(uid);
23825            }
23826        }
23827
23828        @Override
23829        public int getPackageTargetSdkVersion(String packageName) {
23830            synchronized (mPackages) {
23831                return getPackageTargetSdkVersionLockedLPr(packageName);
23832            }
23833        }
23834
23835        @Override
23836        public boolean canAccessInstantApps(int callingUid, int userId) {
23837            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23838        }
23839
23840        @Override
23841        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23842            synchronized (mPackages) {
23843                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23844            }
23845        }
23846
23847        @Override
23848        public void notifyPackageUse(String packageName, int reason) {
23849            synchronized (mPackages) {
23850                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23851            }
23852        }
23853    }
23854
23855    @Override
23856    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23857        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23858        synchronized (mPackages) {
23859            final long identity = Binder.clearCallingIdentity();
23860            try {
23861                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23862                        packageNames, userId);
23863            } finally {
23864                Binder.restoreCallingIdentity(identity);
23865            }
23866        }
23867    }
23868
23869    @Override
23870    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23871        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23872        synchronized (mPackages) {
23873            final long identity = Binder.clearCallingIdentity();
23874            try {
23875                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23876                        packageNames, userId);
23877            } finally {
23878                Binder.restoreCallingIdentity(identity);
23879            }
23880        }
23881    }
23882
23883    private static void enforceSystemOrPhoneCaller(String tag) {
23884        int callingUid = Binder.getCallingUid();
23885        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23886            throw new SecurityException(
23887                    "Cannot call " + tag + " from UID " + callingUid);
23888        }
23889    }
23890
23891    boolean isHistoricalPackageUsageAvailable() {
23892        return mPackageUsage.isHistoricalPackageUsageAvailable();
23893    }
23894
23895    /**
23896     * Return a <b>copy</b> of the collection of packages known to the package manager.
23897     * @return A copy of the values of mPackages.
23898     */
23899    Collection<PackageParser.Package> getPackages() {
23900        synchronized (mPackages) {
23901            return new ArrayList<>(mPackages.values());
23902        }
23903    }
23904
23905    /**
23906     * Logs process start information (including base APK hash) to the security log.
23907     * @hide
23908     */
23909    @Override
23910    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23911            String apkFile, int pid) {
23912        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23913            return;
23914        }
23915        if (!SecurityLog.isLoggingEnabled()) {
23916            return;
23917        }
23918        Bundle data = new Bundle();
23919        data.putLong("startTimestamp", System.currentTimeMillis());
23920        data.putString("processName", processName);
23921        data.putInt("uid", uid);
23922        data.putString("seinfo", seinfo);
23923        data.putString("apkFile", apkFile);
23924        data.putInt("pid", pid);
23925        Message msg = mProcessLoggingHandler.obtainMessage(
23926                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23927        msg.setData(data);
23928        mProcessLoggingHandler.sendMessage(msg);
23929    }
23930
23931    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23932        return mCompilerStats.getPackageStats(pkgName);
23933    }
23934
23935    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23936        return getOrCreateCompilerPackageStats(pkg.packageName);
23937    }
23938
23939    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23940        return mCompilerStats.getOrCreatePackageStats(pkgName);
23941    }
23942
23943    public void deleteCompilerPackageStats(String pkgName) {
23944        mCompilerStats.deletePackageStats(pkgName);
23945    }
23946
23947    @Override
23948    public int getInstallReason(String packageName, int userId) {
23949        final int callingUid = Binder.getCallingUid();
23950        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23951                true /* requireFullPermission */, false /* checkShell */,
23952                "get install reason");
23953        synchronized (mPackages) {
23954            final PackageSetting ps = mSettings.mPackages.get(packageName);
23955            if (filterAppAccessLPr(ps, callingUid, userId)) {
23956                return PackageManager.INSTALL_REASON_UNKNOWN;
23957            }
23958            if (ps != null) {
23959                return ps.getInstallReason(userId);
23960            }
23961        }
23962        return PackageManager.INSTALL_REASON_UNKNOWN;
23963    }
23964
23965    @Override
23966    public boolean canRequestPackageInstalls(String packageName, int userId) {
23967        return canRequestPackageInstallsInternal(packageName, 0, userId,
23968                true /* throwIfPermNotDeclared*/);
23969    }
23970
23971    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23972            boolean throwIfPermNotDeclared) {
23973        int callingUid = Binder.getCallingUid();
23974        int uid = getPackageUid(packageName, 0, userId);
23975        if (callingUid != uid && callingUid != Process.ROOT_UID
23976                && callingUid != Process.SYSTEM_UID) {
23977            throw new SecurityException(
23978                    "Caller uid " + callingUid + " does not own package " + packageName);
23979        }
23980        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23981        if (info == null) {
23982            return false;
23983        }
23984        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23985            return false;
23986        }
23987        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23988        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23989        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23990            if (throwIfPermNotDeclared) {
23991                throw new SecurityException("Need to declare " + appOpPermission
23992                        + " to call this api");
23993            } else {
23994                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23995                return false;
23996            }
23997        }
23998        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23999            return false;
24000        }
24001        if (mExternalSourcesPolicy != null) {
24002            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24003            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24004                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24005            }
24006        }
24007        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24008    }
24009
24010    @Override
24011    public ComponentName getInstantAppResolverSettingsComponent() {
24012        return mInstantAppResolverSettingsComponent;
24013    }
24014
24015    @Override
24016    public ComponentName getInstantAppInstallerComponent() {
24017        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24018            return null;
24019        }
24020        return mInstantAppInstallerActivity == null
24021                ? null : mInstantAppInstallerActivity.getComponentName();
24022    }
24023
24024    @Override
24025    public String getInstantAppAndroidId(String packageName, int userId) {
24026        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24027                "getInstantAppAndroidId");
24028        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24029                true /* requireFullPermission */, false /* checkShell */,
24030                "getInstantAppAndroidId");
24031        // Make sure the target is an Instant App.
24032        if (!isInstantApp(packageName, userId)) {
24033            return null;
24034        }
24035        synchronized (mPackages) {
24036            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24037        }
24038    }
24039
24040    boolean canHaveOatDir(String packageName) {
24041        synchronized (mPackages) {
24042            PackageParser.Package p = mPackages.get(packageName);
24043            if (p == null) {
24044                return false;
24045            }
24046            return p.canHaveOatDir();
24047        }
24048    }
24049
24050    private String getOatDir(PackageParser.Package pkg) {
24051        if (!pkg.canHaveOatDir()) {
24052            return null;
24053        }
24054        File codePath = new File(pkg.codePath);
24055        if (codePath.isDirectory()) {
24056            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24057        }
24058        return null;
24059    }
24060
24061    void deleteOatArtifactsOfPackage(String packageName) {
24062        final String[] instructionSets;
24063        final List<String> codePaths;
24064        final String oatDir;
24065        final PackageParser.Package pkg;
24066        synchronized (mPackages) {
24067            pkg = mPackages.get(packageName);
24068        }
24069        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24070        codePaths = pkg.getAllCodePaths();
24071        oatDir = getOatDir(pkg);
24072
24073        for (String codePath : codePaths) {
24074            for (String isa : instructionSets) {
24075                try {
24076                    mInstaller.deleteOdex(codePath, isa, oatDir);
24077                } catch (InstallerException e) {
24078                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24079                }
24080            }
24081        }
24082    }
24083
24084    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24085        Set<String> unusedPackages = new HashSet<>();
24086        long currentTimeInMillis = System.currentTimeMillis();
24087        synchronized (mPackages) {
24088            for (PackageParser.Package pkg : mPackages.values()) {
24089                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24090                if (ps == null) {
24091                    continue;
24092                }
24093                PackageDexUsage.PackageUseInfo packageUseInfo =
24094                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24095                if (PackageManagerServiceUtils
24096                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24097                                downgradeTimeThresholdMillis, packageUseInfo,
24098                                pkg.getLatestPackageUseTimeInMills(),
24099                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24100                    unusedPackages.add(pkg.packageName);
24101                }
24102            }
24103        }
24104        return unusedPackages;
24105    }
24106
24107    @Override
24108    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24109            int userId) {
24110        final int callingUid = Binder.getCallingUid();
24111        final int callingAppId = UserHandle.getAppId(callingUid);
24112
24113        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24114                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24115
24116        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24117                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24118            throw new SecurityException("Caller must have the "
24119                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24120        }
24121
24122        synchronized(mPackages) {
24123            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24124            scheduleWritePackageRestrictionsLocked(userId);
24125        }
24126    }
24127
24128    @Nullable
24129    @Override
24130    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24131        final int callingUid = Binder.getCallingUid();
24132        final int callingAppId = UserHandle.getAppId(callingUid);
24133
24134        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24135                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24136
24137        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24138                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24139            throw new SecurityException("Caller must have the "
24140                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24141        }
24142
24143        synchronized(mPackages) {
24144            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24145        }
24146    }
24147}
24148
24149interface PackageSender {
24150    /**
24151     * @param userIds User IDs where the action occurred on a full application
24152     * @param instantUserIds User IDs where the action occurred on an instant application
24153     */
24154    void sendPackageBroadcast(final String action, final String pkg,
24155        final Bundle extras, final int flags, final String targetPkg,
24156        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24157    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24158        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24159    void notifyPackageAdded(String packageName);
24160    void notifyPackageRemoved(String packageName);
24161}
24162