PackageManagerService.java revision 6a0fac4affb2801f49ed97cc3de6cd12d40785b4
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.content.pm.PackageManager.CERT_INPUT_RAW_X509;
27import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
33import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
41import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
42import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
43import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
44import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
51import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
52import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
56import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
87import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
102import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
103import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
104import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
105import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
106import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
107import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
108import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
109import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
110import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
111import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
113
114import android.Manifest;
115import android.annotation.IntDef;
116import android.annotation.NonNull;
117import android.annotation.Nullable;
118import android.app.ActivityManager;
119import android.app.ActivityManagerInternal;
120import android.app.AppOpsManager;
121import android.app.IActivityManager;
122import android.app.ResourcesManager;
123import android.app.admin.IDevicePolicyManager;
124import android.app.admin.SecurityLog;
125import android.app.backup.IBackupManager;
126import android.content.BroadcastReceiver;
127import android.content.ComponentName;
128import android.content.ContentResolver;
129import android.content.Context;
130import android.content.IIntentReceiver;
131import android.content.Intent;
132import android.content.IntentFilter;
133import android.content.IntentSender;
134import android.content.IntentSender.SendIntentException;
135import android.content.ServiceConnection;
136import android.content.pm.ActivityInfo;
137import android.content.pm.ApplicationInfo;
138import android.content.pm.AppsQueryHelper;
139import android.content.pm.AuxiliaryResolveInfo;
140import android.content.pm.ChangedPackages;
141import android.content.pm.ComponentInfo;
142import android.content.pm.FallbackCategoryProvider;
143import android.content.pm.FeatureInfo;
144import android.content.pm.IDexModuleRegisterCallback;
145import android.content.pm.IOnPermissionsChangeListener;
146import android.content.pm.IPackageDataObserver;
147import android.content.pm.IPackageDeleteObserver;
148import android.content.pm.IPackageDeleteObserver2;
149import android.content.pm.IPackageInstallObserver2;
150import android.content.pm.IPackageInstaller;
151import android.content.pm.IPackageManager;
152import android.content.pm.IPackageManagerNative;
153import android.content.pm.IPackageMoveObserver;
154import android.content.pm.IPackageStatsObserver;
155import android.content.pm.InstantAppInfo;
156import android.content.pm.InstantAppRequest;
157import android.content.pm.InstantAppResolveInfo;
158import android.content.pm.InstrumentationInfo;
159import android.content.pm.IntentFilterVerificationInfo;
160import android.content.pm.KeySet;
161import android.content.pm.PackageCleanItem;
162import android.content.pm.PackageInfo;
163import android.content.pm.PackageInfoLite;
164import android.content.pm.PackageInstaller;
165import android.content.pm.PackageList;
166import android.content.pm.PackageManager;
167import android.content.pm.PackageManagerInternal;
168import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
169import android.content.pm.PackageManagerInternal.PackageListObserver;
170import android.content.pm.PackageParser;
171import android.content.pm.PackageParser.ActivityIntentInfo;
172import android.content.pm.PackageParser.Package;
173import android.content.pm.PackageParser.PackageLite;
174import android.content.pm.PackageParser.PackageParserException;
175import android.content.pm.PackageParser.ParseFlags;
176import android.content.pm.PackageParser.ServiceIntentInfo;
177import android.content.pm.PackageParser.SigningDetails;
178import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
179import android.content.pm.PackageStats;
180import android.content.pm.PackageUserState;
181import android.content.pm.ParceledListSlice;
182import android.content.pm.PermissionGroupInfo;
183import android.content.pm.PermissionInfo;
184import android.content.pm.ProviderInfo;
185import android.content.pm.ResolveInfo;
186import android.content.pm.ServiceInfo;
187import android.content.pm.SharedLibraryInfo;
188import android.content.pm.Signature;
189import android.content.pm.UserInfo;
190import android.content.pm.VerifierDeviceIdentity;
191import android.content.pm.VerifierInfo;
192import android.content.pm.VersionedPackage;
193import android.content.pm.dex.ArtManager;
194import android.content.pm.dex.DexMetadataHelper;
195import android.content.pm.dex.IArtManager;
196import android.content.res.Resources;
197import android.database.ContentObserver;
198import android.graphics.Bitmap;
199import android.hardware.display.DisplayManager;
200import android.net.Uri;
201import android.os.Binder;
202import android.os.Build;
203import android.os.Bundle;
204import android.os.Debug;
205import android.os.Environment;
206import android.os.Environment.UserEnvironment;
207import android.os.FileUtils;
208import android.os.Handler;
209import android.os.IBinder;
210import android.os.Looper;
211import android.os.Message;
212import android.os.Parcel;
213import android.os.ParcelFileDescriptor;
214import android.os.PatternMatcher;
215import android.os.PersistableBundle;
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 = true;
409    private static final boolean DEBUG_BROADCASTS = false;
410    private static final boolean DEBUG_SHOW_INFO = false;
411    private static final boolean DEBUG_PACKAGE_INFO = false;
412    private static final boolean DEBUG_INTENT_MATCHING = false;
413    public static final boolean DEBUG_PACKAGE_SCANNING = false;
414    private static final boolean DEBUG_VERIFY = false;
415    private static final boolean DEBUG_FILTERS = false;
416    public static final boolean DEBUG_PERMISSIONS = false;
417    private static final boolean DEBUG_SHARED_LIBRARIES = false;
418    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
419
420    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
421    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
422    // user, but by default initialize to this.
423    public static final boolean DEBUG_DEXOPT = false;
424
425    private static final boolean DEBUG_ABI_SELECTION = false;
426    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
427    private static final boolean DEBUG_TRIAGED_MISSING = false;
428    private static final boolean DEBUG_APP_DATA = false;
429
430    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
431    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
432
433    private static final boolean HIDE_EPHEMERAL_APIS = false;
434
435    private static final boolean ENABLE_FREE_CACHE_V2 =
436            SystemProperties.getBoolean("fw.free_cache_v2", true);
437
438    private static final int RADIO_UID = Process.PHONE_UID;
439    private static final int LOG_UID = Process.LOG_UID;
440    private static final int NFC_UID = Process.NFC_UID;
441    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
442    private static final int SHELL_UID = Process.SHELL_UID;
443    private static final int SE_UID = Process.SE_UID;
444
445    // Suffix used during package installation when copying/moving
446    // package apks to install directory.
447    private static final String INSTALL_PACKAGE_SUFFIX = "-";
448
449    static final int SCAN_NO_DEX = 1<<0;
450    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
451    static final int SCAN_NEW_INSTALL = 1<<2;
452    static final int SCAN_UPDATE_TIME = 1<<3;
453    static final int SCAN_BOOTING = 1<<4;
454    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
455    static final int SCAN_REQUIRE_KNOWN = 1<<7;
456    static final int SCAN_MOVE = 1<<8;
457    static final int SCAN_INITIAL = 1<<9;
458    static final int SCAN_CHECK_ONLY = 1<<10;
459    static final int SCAN_DONT_KILL_APP = 1<<11;
460    static final int SCAN_IGNORE_FROZEN = 1<<12;
461    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
462    static final int SCAN_AS_INSTANT_APP = 1<<14;
463    static final int SCAN_AS_FULL_APP = 1<<15;
464    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
465    static final int SCAN_AS_SYSTEM = 1<<17;
466    static final int SCAN_AS_PRIVILEGED = 1<<18;
467    static final int SCAN_AS_OEM = 1<<19;
468    static final int SCAN_AS_VENDOR = 1<<20;
469    static final int SCAN_AS_PRODUCT = 1<<21;
470
471    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
472            SCAN_NO_DEX,
473            SCAN_UPDATE_SIGNATURE,
474            SCAN_NEW_INSTALL,
475            SCAN_UPDATE_TIME,
476            SCAN_BOOTING,
477            SCAN_DELETE_DATA_ON_FAILURES,
478            SCAN_REQUIRE_KNOWN,
479            SCAN_MOVE,
480            SCAN_INITIAL,
481            SCAN_CHECK_ONLY,
482            SCAN_DONT_KILL_APP,
483            SCAN_IGNORE_FROZEN,
484            SCAN_FIRST_BOOT_OR_UPGRADE,
485            SCAN_AS_INSTANT_APP,
486            SCAN_AS_FULL_APP,
487            SCAN_AS_VIRTUAL_PRELOAD,
488    })
489    @Retention(RetentionPolicy.SOURCE)
490    public @interface ScanFlags {}
491
492    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
493    /** Extension of the compressed packages */
494    public final static String COMPRESSED_EXTENSION = ".gz";
495    /** Suffix of stub packages on the system partition */
496    public final static String STUB_SUFFIX = "-Stub";
497
498    private static final int[] EMPTY_INT_ARRAY = new int[0];
499
500    private static final int TYPE_UNKNOWN = 0;
501    private static final int TYPE_ACTIVITY = 1;
502    private static final int TYPE_RECEIVER = 2;
503    private static final int TYPE_SERVICE = 3;
504    private static final int TYPE_PROVIDER = 4;
505    @IntDef(prefix = { "TYPE_" }, value = {
506            TYPE_UNKNOWN,
507            TYPE_ACTIVITY,
508            TYPE_RECEIVER,
509            TYPE_SERVICE,
510            TYPE_PROVIDER,
511    })
512    @Retention(RetentionPolicy.SOURCE)
513    public @interface ComponentType {}
514
515    /**
516     * Timeout (in milliseconds) after which the watchdog should declare that
517     * our handler thread is wedged.  The usual default for such things is one
518     * minute but we sometimes do very lengthy I/O operations on this thread,
519     * such as installing multi-gigabyte applications, so ours needs to be longer.
520     */
521    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
522
523    /**
524     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
525     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
526     * settings entry if available, otherwise we use the hardcoded default.  If it's been
527     * more than this long since the last fstrim, we force one during the boot sequence.
528     *
529     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
530     * one gets run at the next available charging+idle time.  This final mandatory
531     * no-fstrim check kicks in only of the other scheduling criteria is never met.
532     */
533    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
534
535    /**
536     * Whether verification is enabled by default.
537     */
538    private static final boolean DEFAULT_VERIFY_ENABLE = true;
539
540    /**
541     * The default maximum time to wait for the verification agent to return in
542     * milliseconds.
543     */
544    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
545
546    /**
547     * The default response for package verification timeout.
548     *
549     * This can be either PackageManager.VERIFICATION_ALLOW or
550     * PackageManager.VERIFICATION_REJECT.
551     */
552    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
553
554    public static final String PLATFORM_PACKAGE_NAME = "android";
555
556    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
557
558    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
559            DEFAULT_CONTAINER_PACKAGE,
560            "com.android.defcontainer.DefaultContainerService");
561
562    private static final String KILL_APP_REASON_GIDS_CHANGED =
563            "permission grant or revoke changed gids";
564
565    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
566            "permissions revoked";
567
568    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
569
570    private static final String PACKAGE_SCHEME = "package";
571
572    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
573
574    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
575
576    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
577
578    /** Canonical intent used to identify what counts as a "web browser" app */
579    private static final Intent sBrowserIntent;
580    static {
581        sBrowserIntent = new Intent();
582        sBrowserIntent.setAction(Intent.ACTION_VIEW);
583        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
584        sBrowserIntent.setData(Uri.parse("http:"));
585        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
586    }
587
588    /**
589     * The set of all protected actions [i.e. those actions for which a high priority
590     * intent filter is disallowed].
591     */
592    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
593    static {
594        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
597        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
598    }
599
600    // Compilation reasons.
601    public static final int REASON_UNKNOWN = -1;
602    public static final int REASON_FIRST_BOOT = 0;
603    public static final int REASON_BOOT = 1;
604    public static final int REASON_INSTALL = 2;
605    public static final int REASON_BACKGROUND_DEXOPT = 3;
606    public static final int REASON_AB_OTA = 4;
607    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
608    public static final int REASON_SHARED = 6;
609
610    public static final int REASON_LAST = REASON_SHARED;
611
612    /**
613     * Version number for the package parser cache. Increment this whenever the format or
614     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
615     */
616    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
617
618    /**
619     * Whether the package parser cache is enabled.
620     */
621    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
622
623    /**
624     * Permissions required in order to receive instant application lifecycle broadcasts.
625     */
626    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
627            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
628
629    final ServiceThread mHandlerThread;
630
631    final PackageHandler mHandler;
632
633    private final ProcessLoggingHandler mProcessLoggingHandler;
634
635    /**
636     * Messages for {@link #mHandler} that need to wait for system ready before
637     * being dispatched.
638     */
639    private ArrayList<Message> mPostSystemReadyMessages;
640
641    final int mSdkVersion = Build.VERSION.SDK_INT;
642
643    final Context mContext;
644    final boolean mFactoryTest;
645    final boolean mOnlyCore;
646    final DisplayMetrics mMetrics;
647    final int mDefParseFlags;
648    final String[] mSeparateProcesses;
649    final boolean mIsUpgrade;
650    final boolean mIsPreNUpgrade;
651    final boolean mIsPreNMR1Upgrade;
652
653    // Have we told the Activity Manager to whitelist the default container service by uid yet?
654    @GuardedBy("mPackages")
655    boolean mDefaultContainerWhitelisted = false;
656
657    @GuardedBy("mPackages")
658    private boolean mDexOptDialogShown;
659
660    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
661    // LOCK HELD.  Can be called with mInstallLock held.
662    @GuardedBy("mInstallLock")
663    final Installer mInstaller;
664
665    /** Directory where installed applications are stored */
666    private static final File sAppInstallDir =
667            new File(Environment.getDataDirectory(), "app");
668    /** Directory where installed application's 32-bit native libraries are copied. */
669    private static final File sAppLib32InstallDir =
670            new File(Environment.getDataDirectory(), "app-lib");
671    /** Directory where code and non-resource assets of forward-locked applications are stored */
672    private static final File sDrmAppPrivateInstallDir =
673            new File(Environment.getDataDirectory(), "app-private");
674
675    // ----------------------------------------------------------------
676
677    // Lock for state used when installing and doing other long running
678    // operations.  Methods that must be called with this lock held have
679    // the suffix "LI".
680    final Object mInstallLock = new Object();
681
682    // ----------------------------------------------------------------
683
684    // Keys are String (package name), values are Package.  This also serves
685    // as the lock for the global state.  Methods that must be called with
686    // this lock held have the prefix "LP".
687    @GuardedBy("mPackages")
688    final ArrayMap<String, PackageParser.Package> mPackages =
689            new ArrayMap<String, PackageParser.Package>();
690
691    final ArrayMap<String, Set<String>> mKnownCodebase =
692            new ArrayMap<String, Set<String>>();
693
694    // Keys are isolated uids and values are the uid of the application
695    // that created the isolated proccess.
696    @GuardedBy("mPackages")
697    final SparseIntArray mIsolatedOwners = new SparseIntArray();
698
699    /**
700     * Tracks new system packages [received in an OTA] that we expect to
701     * find updated user-installed versions. Keys are package name, values
702     * are package location.
703     */
704    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
705    /**
706     * Tracks high priority intent filters for protected actions. During boot, certain
707     * filter actions are protected and should never be allowed to have a high priority
708     * intent filter for them. However, there is one, and only one exception -- the
709     * setup wizard. It must be able to define a high priority intent filter for these
710     * actions to ensure there are no escapes from the wizard. We need to delay processing
711     * of these during boot as we need to look at all of the system packages in order
712     * to know which component is the setup wizard.
713     */
714    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
715    /**
716     * Whether or not processing protected filters should be deferred.
717     */
718    private boolean mDeferProtectedFilters = true;
719
720    /**
721     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
722     */
723    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
724    /**
725     * Whether or not system app permissions should be promoted from install to runtime.
726     */
727    boolean mPromoteSystemApps;
728
729    @GuardedBy("mPackages")
730    final Settings mSettings;
731
732    /**
733     * Set of package names that are currently "frozen", which means active
734     * surgery is being done on the code/data for that package. The platform
735     * will refuse to launch frozen packages to avoid race conditions.
736     *
737     * @see PackageFreezer
738     */
739    @GuardedBy("mPackages")
740    final ArraySet<String> mFrozenPackages = new ArraySet<>();
741
742    final ProtectedPackages mProtectedPackages;
743
744    @GuardedBy("mLoadedVolumes")
745    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
746
747    boolean mFirstBoot;
748
749    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
750
751    @GuardedBy("mAvailableFeatures")
752    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
753
754    private final InstantAppRegistry mInstantAppRegistry;
755
756    @GuardedBy("mPackages")
757    int mChangedPackagesSequenceNumber;
758    /**
759     * List of changed [installed, removed or updated] packages.
760     * mapping from user id -> sequence number -> package name
761     */
762    @GuardedBy("mPackages")
763    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
764    /**
765     * The sequence number of the last change to a package.
766     * mapping from user id -> package name -> sequence number
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
770
771    @GuardedBy("mPackages")
772    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
773
774    class PackageParserCallback implements PackageParser.Callback {
775        @Override public final boolean hasFeature(String feature) {
776            return PackageManagerService.this.hasSystemFeature(feature, 0);
777        }
778
779        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
780                Collection<PackageParser.Package> allPackages, String targetPackageName) {
781            List<PackageParser.Package> overlayPackages = null;
782            for (PackageParser.Package p : allPackages) {
783                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
784                    if (overlayPackages == null) {
785                        overlayPackages = new ArrayList<PackageParser.Package>();
786                    }
787                    overlayPackages.add(p);
788                }
789            }
790            if (overlayPackages != null) {
791                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
792                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
793                        return p1.mOverlayPriority - p2.mOverlayPriority;
794                    }
795                };
796                Collections.sort(overlayPackages, cmp);
797            }
798            return overlayPackages;
799        }
800
801        @GuardedBy("mInstallLock")
802        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
803                String targetPackageName, String targetPath) {
804            if ("android".equals(targetPackageName)) {
805                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
806                // native AssetManager.
807                return null;
808            }
809            List<PackageParser.Package> overlayPackages =
810                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
811            if (overlayPackages == null || overlayPackages.isEmpty()) {
812                return null;
813            }
814            List<String> overlayPathList = null;
815            for (PackageParser.Package overlayPackage : overlayPackages) {
816                if (targetPath == null) {
817                    if (overlayPathList == null) {
818                        overlayPathList = new ArrayList<String>();
819                    }
820                    overlayPathList.add(overlayPackage.baseCodePath);
821                    continue;
822                }
823
824                try {
825                    // Creates idmaps for system to parse correctly the Android manifest of the
826                    // target package.
827                    //
828                    // OverlayManagerService will update each of them with a correct gid from its
829                    // target package app id.
830                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
831                            UserHandle.getSharedAppGid(
832                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
833                    if (overlayPathList == null) {
834                        overlayPathList = new ArrayList<String>();
835                    }
836                    overlayPathList.add(overlayPackage.baseCodePath);
837                } catch (InstallerException e) {
838                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
839                            overlayPackage.baseCodePath);
840                }
841            }
842            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
843        }
844
845        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
846            synchronized (mPackages) {
847                return getStaticOverlayPathsLocked(
848                        mPackages.values(), targetPackageName, targetPath);
849            }
850        }
851
852        @Override public final String[] getOverlayApks(String targetPackageName) {
853            return getStaticOverlayPaths(targetPackageName, null);
854        }
855
856        @Override public final String[] getOverlayPaths(String targetPackageName,
857                String targetPath) {
858            return getStaticOverlayPaths(targetPackageName, targetPath);
859        }
860    }
861
862    class ParallelPackageParserCallback extends PackageParserCallback {
863        List<PackageParser.Package> mOverlayPackages = null;
864
865        void findStaticOverlayPackages() {
866            synchronized (mPackages) {
867                for (PackageParser.Package p : mPackages.values()) {
868                    if (p.mOverlayIsStatic) {
869                        if (mOverlayPackages == null) {
870                            mOverlayPackages = new ArrayList<PackageParser.Package>();
871                        }
872                        mOverlayPackages.add(p);
873                    }
874                }
875            }
876        }
877
878        @Override
879        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
880            // We can trust mOverlayPackages without holding mPackages because package uninstall
881            // can't happen while running parallel parsing.
882            // Moreover holding mPackages on each parsing thread causes dead-lock.
883            return mOverlayPackages == null ? null :
884                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
885        }
886    }
887
888    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
889    final ParallelPackageParserCallback mParallelPackageParserCallback =
890            new ParallelPackageParserCallback();
891
892    public static final class SharedLibraryEntry {
893        public final @Nullable String path;
894        public final @Nullable String apk;
895        public final @NonNull SharedLibraryInfo info;
896
897        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
898                String declaringPackageName, long declaringPackageVersionCode) {
899            path = _path;
900            apk = _apk;
901            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
902                    declaringPackageName, declaringPackageVersionCode), null);
903        }
904    }
905
906    // Currently known shared libraries.
907    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
908    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
909            new ArrayMap<>();
910
911    // All available activities, for your resolving pleasure.
912    final ActivityIntentResolver mActivities =
913            new ActivityIntentResolver();
914
915    // All available receivers, for your resolving pleasure.
916    final ActivityIntentResolver mReceivers =
917            new ActivityIntentResolver();
918
919    // All available services, for your resolving pleasure.
920    final ServiceIntentResolver mServices = new ServiceIntentResolver();
921
922    // All available providers, for your resolving pleasure.
923    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
924
925    // Mapping from provider base names (first directory in content URI codePath)
926    // to the provider information.
927    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
928            new ArrayMap<String, PackageParser.Provider>();
929
930    // Mapping from instrumentation class names to info about them.
931    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
932            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
933
934    // Packages whose data we have transfered into another package, thus
935    // should no longer exist.
936    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
937
938    // Broadcast actions that are only available to the system.
939    @GuardedBy("mProtectedBroadcasts")
940    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
941
942    /** List of packages waiting for verification. */
943    final SparseArray<PackageVerificationState> mPendingVerification
944            = new SparseArray<PackageVerificationState>();
945
946    final PackageInstallerService mInstallerService;
947
948    final ArtManagerService mArtManagerService;
949
950    private final PackageDexOptimizer mPackageDexOptimizer;
951    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
952    // is used by other apps).
953    private final DexManager mDexManager;
954
955    private AtomicInteger mNextMoveId = new AtomicInteger();
956    private final MoveCallbacks mMoveCallbacks;
957
958    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
959
960    // Cache of users who need badging.
961    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
962
963    /** Token for keys in mPendingVerification. */
964    private int mPendingVerificationToken = 0;
965
966    volatile boolean mSystemReady;
967    volatile boolean mSafeMode;
968    volatile boolean mHasSystemUidErrors;
969    private volatile boolean mWebInstantAppsDisabled;
970
971    ApplicationInfo mAndroidApplication;
972    final ActivityInfo mResolveActivity = new ActivityInfo();
973    final ResolveInfo mResolveInfo = new ResolveInfo();
974    ComponentName mResolveComponentName;
975    PackageParser.Package mPlatformPackage;
976    ComponentName mCustomResolverComponentName;
977
978    boolean mResolverReplaced = false;
979
980    private final @Nullable ComponentName mIntentFilterVerifierComponent;
981    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
982
983    private int mIntentFilterVerificationToken = 0;
984
985    /** The service connection to the ephemeral resolver */
986    final InstantAppResolverConnection mInstantAppResolverConnection;
987    /** Component used to show resolver settings for Instant Apps */
988    final ComponentName mInstantAppResolverSettingsComponent;
989
990    /** Activity used to install instant applications */
991    ActivityInfo mInstantAppInstallerActivity;
992    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
993
994    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
995            = new SparseArray<IntentFilterVerificationState>();
996
997    // TODO remove this and go through mPermissonManager directly
998    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
999    private final PermissionManagerInternal mPermissionManager;
1000
1001    // List of packages names to keep cached, even if they are uninstalled for all users
1002    private List<String> mKeepUninstalledPackages;
1003
1004    private UserManagerInternal mUserManagerInternal;
1005    private ActivityManagerInternal mActivityManagerInternal;
1006
1007    private DeviceIdleController.LocalService mDeviceIdleController;
1008
1009    private File mCacheDir;
1010
1011    private Future<?> mPrepareAppDataFuture;
1012
1013    private static class IFVerificationParams {
1014        PackageParser.Package pkg;
1015        boolean replacing;
1016        int userId;
1017        int verifierUid;
1018
1019        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1020                int _userId, int _verifierUid) {
1021            pkg = _pkg;
1022            replacing = _replacing;
1023            userId = _userId;
1024            replacing = _replacing;
1025            verifierUid = _verifierUid;
1026        }
1027    }
1028
1029    private interface IntentFilterVerifier<T extends IntentFilter> {
1030        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1031                                               T filter, String packageName);
1032        void startVerifications(int userId);
1033        void receiveVerificationResponse(int verificationId);
1034    }
1035
1036    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1037        private Context mContext;
1038        private ComponentName mIntentFilterVerifierComponent;
1039        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1040
1041        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1042            mContext = context;
1043            mIntentFilterVerifierComponent = verifierComponent;
1044        }
1045
1046        private String getDefaultScheme() {
1047            return IntentFilter.SCHEME_HTTPS;
1048        }
1049
1050        @Override
1051        public void startVerifications(int userId) {
1052            // Launch verifications requests
1053            int count = mCurrentIntentFilterVerifications.size();
1054            for (int n=0; n<count; n++) {
1055                int verificationId = mCurrentIntentFilterVerifications.get(n);
1056                final IntentFilterVerificationState ivs =
1057                        mIntentFilterVerificationStates.get(verificationId);
1058
1059                String packageName = ivs.getPackageName();
1060
1061                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1062                final int filterCount = filters.size();
1063                ArraySet<String> domainsSet = new ArraySet<>();
1064                for (int m=0; m<filterCount; m++) {
1065                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1066                    domainsSet.addAll(filter.getHostsList());
1067                }
1068                synchronized (mPackages) {
1069                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1070                            packageName, domainsSet) != null) {
1071                        scheduleWriteSettingsLocked();
1072                    }
1073                }
1074                sendVerificationRequest(verificationId, ivs);
1075            }
1076            mCurrentIntentFilterVerifications.clear();
1077        }
1078
1079        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1080            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1081            verificationIntent.putExtra(
1082                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1083                    verificationId);
1084            verificationIntent.putExtra(
1085                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1086                    getDefaultScheme());
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1089                    ivs.getHostsString());
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1092                    ivs.getPackageName());
1093            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1094            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1095
1096            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1097            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1098                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1099                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1100
1101            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1102            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1103                    "Sending IntentFilter verification broadcast");
1104        }
1105
1106        public void receiveVerificationResponse(int verificationId) {
1107            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1108
1109            final boolean verified = ivs.isVerified();
1110
1111            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1112            final int count = filters.size();
1113            if (DEBUG_DOMAIN_VERIFICATION) {
1114                Slog.i(TAG, "Received verification response " + verificationId
1115                        + " for " + count + " filters, verified=" + verified);
1116            }
1117            for (int n=0; n<count; n++) {
1118                PackageParser.ActivityIntentInfo filter = filters.get(n);
1119                filter.setVerified(verified);
1120
1121                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1122                        + " verified with result:" + verified + " and hosts:"
1123                        + ivs.getHostsString());
1124            }
1125
1126            mIntentFilterVerificationStates.remove(verificationId);
1127
1128            final String packageName = ivs.getPackageName();
1129            IntentFilterVerificationInfo ivi = null;
1130
1131            synchronized (mPackages) {
1132                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1133            }
1134            if (ivi == null) {
1135                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1136                        + verificationId + " packageName:" + packageName);
1137                return;
1138            }
1139            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1140                    "Updating IntentFilterVerificationInfo for package " + packageName
1141                            +" verificationId:" + verificationId);
1142
1143            synchronized (mPackages) {
1144                if (verified) {
1145                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1146                } else {
1147                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1148                }
1149                scheduleWriteSettingsLocked();
1150
1151                final int userId = ivs.getUserId();
1152                if (userId != UserHandle.USER_ALL) {
1153                    final int userStatus =
1154                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1155
1156                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1157                    boolean needUpdate = false;
1158
1159                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1160                    // already been set by the User thru the Disambiguation dialog
1161                    switch (userStatus) {
1162                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1163                            if (verified) {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1165                            } else {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1167                            }
1168                            needUpdate = true;
1169                            break;
1170
1171                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1172                            if (verified) {
1173                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1174                                needUpdate = true;
1175                            }
1176                            break;
1177
1178                        default:
1179                            // Nothing to do
1180                    }
1181
1182                    if (needUpdate) {
1183                        mSettings.updateIntentFilterVerificationStatusLPw(
1184                                packageName, updatedStatus, userId);
1185                        scheduleWritePackageRestrictionsLocked(userId);
1186                    }
1187                }
1188            }
1189        }
1190
1191        @Override
1192        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1193                    ActivityIntentInfo filter, String packageName) {
1194            if (!hasValidDomains(filter)) {
1195                return false;
1196            }
1197            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1198            if (ivs == null) {
1199                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1200                        packageName);
1201            }
1202            if (DEBUG_DOMAIN_VERIFICATION) {
1203                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1204            }
1205            ivs.addFilter(filter);
1206            return true;
1207        }
1208
1209        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1210                int userId, int verificationId, String packageName) {
1211            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1212                    verifierUid, userId, packageName);
1213            ivs.setPendingState();
1214            synchronized (mPackages) {
1215                mIntentFilterVerificationStates.append(verificationId, ivs);
1216                mCurrentIntentFilterVerifications.add(verificationId);
1217            }
1218            return ivs;
1219        }
1220    }
1221
1222    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1223        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1224                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1225                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1226    }
1227
1228    // Set of pending broadcasts for aggregating enable/disable of components.
1229    static class PendingPackageBroadcasts {
1230        // for each user id, a map of <package name -> components within that package>
1231        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1232
1233        public PendingPackageBroadcasts() {
1234            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1235        }
1236
1237        public ArrayList<String> get(int userId, String packageName) {
1238            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1239            return packages.get(packageName);
1240        }
1241
1242        public void put(int userId, String packageName, ArrayList<String> components) {
1243            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1244            packages.put(packageName, components);
1245        }
1246
1247        public void remove(int userId, String packageName) {
1248            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1249            if (packages != null) {
1250                packages.remove(packageName);
1251            }
1252        }
1253
1254        public void remove(int userId) {
1255            mUidMap.remove(userId);
1256        }
1257
1258        public int userIdCount() {
1259            return mUidMap.size();
1260        }
1261
1262        public int userIdAt(int n) {
1263            return mUidMap.keyAt(n);
1264        }
1265
1266        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1267            return mUidMap.get(userId);
1268        }
1269
1270        public int size() {
1271            // total number of pending broadcast entries across all userIds
1272            int num = 0;
1273            for (int i = 0; i< mUidMap.size(); i++) {
1274                num += mUidMap.valueAt(i).size();
1275            }
1276            return num;
1277        }
1278
1279        public void clear() {
1280            mUidMap.clear();
1281        }
1282
1283        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1284            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1285            if (map == null) {
1286                map = new ArrayMap<String, ArrayList<String>>();
1287                mUidMap.put(userId, map);
1288            }
1289            return map;
1290        }
1291    }
1292    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1293
1294    // Service Connection to remote media container service to copy
1295    // package uri's from external media onto secure containers
1296    // or internal storage.
1297    private IMediaContainerService mContainerService = null;
1298
1299    static final int SEND_PENDING_BROADCAST = 1;
1300    static final int MCS_BOUND = 3;
1301    static final int END_COPY = 4;
1302    static final int INIT_COPY = 5;
1303    static final int MCS_UNBIND = 6;
1304    static final int START_CLEANING_PACKAGE = 7;
1305    static final int FIND_INSTALL_LOC = 8;
1306    static final int POST_INSTALL = 9;
1307    static final int MCS_RECONNECT = 10;
1308    static final int MCS_GIVE_UP = 11;
1309    static final int WRITE_SETTINGS = 13;
1310    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1311    static final int PACKAGE_VERIFIED = 15;
1312    static final int CHECK_PENDING_VERIFICATION = 16;
1313    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1314    static final int INTENT_FILTER_VERIFIED = 18;
1315    static final int WRITE_PACKAGE_LIST = 19;
1316    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1317
1318    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1319
1320    // Delay time in millisecs
1321    static final int BROADCAST_DELAY = 10 * 1000;
1322
1323    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1324            2 * 60 * 60 * 1000L; /* two hours */
1325
1326    static UserManagerService sUserManager;
1327
1328    // Stores a list of users whose package restrictions file needs to be updated
1329    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1330
1331    final private DefaultContainerConnection mDefContainerConn =
1332            new DefaultContainerConnection();
1333    class DefaultContainerConnection implements ServiceConnection {
1334        public void onServiceConnected(ComponentName name, IBinder service) {
1335            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1336            final IMediaContainerService imcs = IMediaContainerService.Stub
1337                    .asInterface(Binder.allowBlocking(service));
1338            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1339        }
1340
1341        public void onServiceDisconnected(ComponentName name) {
1342            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1343        }
1344    }
1345
1346    // Recordkeeping of restore-after-install operations that are currently in flight
1347    // between the Package Manager and the Backup Manager
1348    static class PostInstallData {
1349        public InstallArgs args;
1350        public PackageInstalledInfo res;
1351
1352        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1353            args = _a;
1354            res = _r;
1355        }
1356    }
1357
1358    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1359    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1360
1361    // XML tags for backup/restore of various bits of state
1362    private static final String TAG_PREFERRED_BACKUP = "pa";
1363    private static final String TAG_DEFAULT_APPS = "da";
1364    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1365
1366    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1367    private static final String TAG_ALL_GRANTS = "rt-grants";
1368    private static final String TAG_GRANT = "grant";
1369    private static final String ATTR_PACKAGE_NAME = "pkg";
1370
1371    private static final String TAG_PERMISSION = "perm";
1372    private static final String ATTR_PERMISSION_NAME = "name";
1373    private static final String ATTR_IS_GRANTED = "g";
1374    private static final String ATTR_USER_SET = "set";
1375    private static final String ATTR_USER_FIXED = "fixed";
1376    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1377
1378    // System/policy permission grants are not backed up
1379    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1380            FLAG_PERMISSION_POLICY_FIXED
1381            | FLAG_PERMISSION_SYSTEM_FIXED
1382            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1383
1384    // And we back up these user-adjusted states
1385    private static final int USER_RUNTIME_GRANT_MASK =
1386            FLAG_PERMISSION_USER_SET
1387            | FLAG_PERMISSION_USER_FIXED
1388            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1389
1390    final @Nullable String mRequiredVerifierPackage;
1391    final @NonNull String mRequiredInstallerPackage;
1392    final @NonNull String mRequiredUninstallerPackage;
1393    final @Nullable String mSetupWizardPackage;
1394    final @Nullable String mStorageManagerPackage;
1395    final @Nullable String mSystemTextClassifierPackage;
1396    final @NonNull String mServicesSystemSharedLibraryPackageName;
1397    final @NonNull String mSharedSystemSharedLibraryPackageName;
1398
1399    private final PackageUsage mPackageUsage = new PackageUsage();
1400    private final CompilerStats mCompilerStats = new CompilerStats();
1401
1402    class PackageHandler extends Handler {
1403        private boolean mBound = false;
1404        final ArrayList<HandlerParams> mPendingInstalls =
1405            new ArrayList<HandlerParams>();
1406
1407        private boolean connectToService() {
1408            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1409                    " DefaultContainerService");
1410            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1411            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1412            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1413                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1414                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415                mBound = true;
1416                return true;
1417            }
1418            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419            return false;
1420        }
1421
1422        private void disconnectService() {
1423            mContainerService = null;
1424            mBound = false;
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1426            mContext.unbindService(mDefContainerConn);
1427            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428        }
1429
1430        PackageHandler(Looper looper) {
1431            super(looper);
1432        }
1433
1434        public void handleMessage(Message msg) {
1435            try {
1436                doHandleMessage(msg);
1437            } finally {
1438                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1439            }
1440        }
1441
1442        void doHandleMessage(Message msg) {
1443            switch (msg.what) {
1444                case INIT_COPY: {
1445                    HandlerParams params = (HandlerParams) msg.obj;
1446                    int idx = mPendingInstalls.size();
1447                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1448                    // If a bind was already initiated we dont really
1449                    // need to do anything. The pending install
1450                    // will be processed later on.
1451                    if (!mBound) {
1452                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1453                                System.identityHashCode(mHandler));
1454                        // If this is the only one pending we might
1455                        // have to bind to the service again.
1456                        if (!connectToService()) {
1457                            Slog.e(TAG, "Failed to bind to media container service");
1458                            params.serviceError();
1459                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1460                                    System.identityHashCode(mHandler));
1461                            if (params.traceMethod != null) {
1462                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1463                                        params.traceCookie);
1464                            }
1465                            return;
1466                        } else {
1467                            // Once we bind to the service, the first
1468                            // pending request will be processed.
1469                            mPendingInstalls.add(idx, params);
1470                        }
1471                    } else {
1472                        mPendingInstalls.add(idx, params);
1473                        // Already bound to the service. Just make
1474                        // sure we trigger off processing the first request.
1475                        if (idx == 0) {
1476                            mHandler.sendEmptyMessage(MCS_BOUND);
1477                        }
1478                    }
1479                    break;
1480                }
1481                case MCS_BOUND: {
1482                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1483                    if (msg.obj != null) {
1484                        mContainerService = (IMediaContainerService) msg.obj;
1485                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1486                                System.identityHashCode(mHandler));
1487                    }
1488                    if (mContainerService == null) {
1489                        if (!mBound) {
1490                            // Something seriously wrong since we are not bound and we are not
1491                            // waiting for connection. Bail out.
1492                            Slog.e(TAG, "Cannot bind to media container service");
1493                            for (HandlerParams params : mPendingInstalls) {
1494                                // Indicate service bind error
1495                                params.serviceError();
1496                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1497                                        System.identityHashCode(params));
1498                                if (params.traceMethod != null) {
1499                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1500                                            params.traceMethod, params.traceCookie);
1501                                }
1502                                return;
1503                            }
1504                            mPendingInstalls.clear();
1505                        } else {
1506                            Slog.w(TAG, "Waiting to connect to media container service");
1507                        }
1508                    } else if (mPendingInstalls.size() > 0) {
1509                        HandlerParams params = mPendingInstalls.get(0);
1510                        if (params != null) {
1511                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1512                                    System.identityHashCode(params));
1513                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1514                            if (params.startCopy()) {
1515                                // We are done...  look for more work or to
1516                                // go idle.
1517                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1518                                        "Checking for more work or unbind...");
1519                                // Delete pending install
1520                                if (mPendingInstalls.size() > 0) {
1521                                    mPendingInstalls.remove(0);
1522                                }
1523                                if (mPendingInstalls.size() == 0) {
1524                                    if (mBound) {
1525                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1526                                                "Posting delayed MCS_UNBIND");
1527                                        removeMessages(MCS_UNBIND);
1528                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1529                                        // Unbind after a little delay, to avoid
1530                                        // continual thrashing.
1531                                        sendMessageDelayed(ubmsg, 10000);
1532                                    }
1533                                } else {
1534                                    // There are more pending requests in queue.
1535                                    // Just post MCS_BOUND message to trigger processing
1536                                    // of next pending install.
1537                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1538                                            "Posting MCS_BOUND for next work");
1539                                    mHandler.sendEmptyMessage(MCS_BOUND);
1540                                }
1541                            }
1542                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1543                        }
1544                    } else {
1545                        // Should never happen ideally.
1546                        Slog.w(TAG, "Empty queue");
1547                    }
1548                    break;
1549                }
1550                case MCS_RECONNECT: {
1551                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1552                    if (mPendingInstalls.size() > 0) {
1553                        if (mBound) {
1554                            disconnectService();
1555                        }
1556                        if (!connectToService()) {
1557                            Slog.e(TAG, "Failed to bind to media container service");
1558                            for (HandlerParams params : mPendingInstalls) {
1559                                // Indicate service bind error
1560                                params.serviceError();
1561                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1562                                        System.identityHashCode(params));
1563                            }
1564                            mPendingInstalls.clear();
1565                        }
1566                    }
1567                    break;
1568                }
1569                case MCS_UNBIND: {
1570                    // If there is no actual work left, then time to unbind.
1571                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1572
1573                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1574                        if (mBound) {
1575                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1576
1577                            disconnectService();
1578                        }
1579                    } else if (mPendingInstalls.size() > 0) {
1580                        // There are more pending requests in queue.
1581                        // Just post MCS_BOUND message to trigger processing
1582                        // of next pending install.
1583                        mHandler.sendEmptyMessage(MCS_BOUND);
1584                    }
1585
1586                    break;
1587                }
1588                case MCS_GIVE_UP: {
1589                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1590                    HandlerParams params = mPendingInstalls.remove(0);
1591                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1592                            System.identityHashCode(params));
1593                    break;
1594                }
1595                case SEND_PENDING_BROADCAST: {
1596                    String packages[];
1597                    ArrayList<String> components[];
1598                    int size = 0;
1599                    int uids[];
1600                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1601                    synchronized (mPackages) {
1602                        if (mPendingBroadcasts == null) {
1603                            return;
1604                        }
1605                        size = mPendingBroadcasts.size();
1606                        if (size <= 0) {
1607                            // Nothing to be done. Just return
1608                            return;
1609                        }
1610                        packages = new String[size];
1611                        components = new ArrayList[size];
1612                        uids = new int[size];
1613                        int i = 0;  // filling out the above arrays
1614
1615                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1616                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1617                            Iterator<Map.Entry<String, ArrayList<String>>> it
1618                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1619                                            .entrySet().iterator();
1620                            while (it.hasNext() && i < size) {
1621                                Map.Entry<String, ArrayList<String>> ent = it.next();
1622                                packages[i] = ent.getKey();
1623                                components[i] = ent.getValue();
1624                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1625                                uids[i] = (ps != null)
1626                                        ? UserHandle.getUid(packageUserId, ps.appId)
1627                                        : -1;
1628                                i++;
1629                            }
1630                        }
1631                        size = i;
1632                        mPendingBroadcasts.clear();
1633                    }
1634                    // Send broadcasts
1635                    for (int i = 0; i < size; i++) {
1636                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1637                    }
1638                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1639                    break;
1640                }
1641                case START_CLEANING_PACKAGE: {
1642                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1643                    final String packageName = (String)msg.obj;
1644                    final int userId = msg.arg1;
1645                    final boolean andCode = msg.arg2 != 0;
1646                    synchronized (mPackages) {
1647                        if (userId == UserHandle.USER_ALL) {
1648                            int[] users = sUserManager.getUserIds();
1649                            for (int user : users) {
1650                                mSettings.addPackageToCleanLPw(
1651                                        new PackageCleanItem(user, packageName, andCode));
1652                            }
1653                        } else {
1654                            mSettings.addPackageToCleanLPw(
1655                                    new PackageCleanItem(userId, packageName, andCode));
1656                        }
1657                    }
1658                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1659                    startCleaningPackages();
1660                } break;
1661                case POST_INSTALL: {
1662                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1663
1664                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1665                    final boolean didRestore = (msg.arg2 != 0);
1666                    mRunningInstalls.delete(msg.arg1);
1667
1668                    if (data != null) {
1669                        InstallArgs args = data.args;
1670                        PackageInstalledInfo parentRes = data.res;
1671
1672                        final boolean grantPermissions = (args.installFlags
1673                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1674                        final boolean killApp = (args.installFlags
1675                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1676                        final boolean virtualPreload = ((args.installFlags
1677                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1678                        final String[] grantedPermissions = args.installGrantPermissions;
1679
1680                        // Handle the parent package
1681                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1682                                virtualPreload, grantedPermissions, didRestore,
1683                                args.installerPackageName, args.observer);
1684
1685                        // Handle the child packages
1686                        final int childCount = (parentRes.addedChildPackages != null)
1687                                ? parentRes.addedChildPackages.size() : 0;
1688                        for (int i = 0; i < childCount; i++) {
1689                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1690                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1691                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1692                                    args.installerPackageName, args.observer);
1693                        }
1694
1695                        // Log tracing if needed
1696                        if (args.traceMethod != null) {
1697                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1698                                    args.traceCookie);
1699                        }
1700                    } else {
1701                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1702                    }
1703
1704                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1705                } break;
1706                case WRITE_SETTINGS: {
1707                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1708                    synchronized (mPackages) {
1709                        removeMessages(WRITE_SETTINGS);
1710                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1711                        mSettings.writeLPr();
1712                        mDirtyUsers.clear();
1713                    }
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1715                } break;
1716                case WRITE_PACKAGE_RESTRICTIONS: {
1717                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1718                    synchronized (mPackages) {
1719                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1720                        for (int userId : mDirtyUsers) {
1721                            mSettings.writePackageRestrictionsLPr(userId);
1722                        }
1723                        mDirtyUsers.clear();
1724                    }
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1726                } break;
1727                case WRITE_PACKAGE_LIST: {
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1729                    synchronized (mPackages) {
1730                        removeMessages(WRITE_PACKAGE_LIST);
1731                        mSettings.writePackageListLPr(msg.arg1);
1732                    }
1733                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1734                } break;
1735                case CHECK_PENDING_VERIFICATION: {
1736                    final int verificationId = msg.arg1;
1737                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1738
1739                    if ((state != null) && !state.timeoutExtended()) {
1740                        final InstallArgs args = state.getInstallArgs();
1741                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1742
1743                        Slog.i(TAG, "Verification timed out for " + originUri);
1744                        mPendingVerification.remove(verificationId);
1745
1746                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1747
1748                        final UserHandle user = args.getUser();
1749                        if (getDefaultVerificationResponse(user)
1750                                == PackageManager.VERIFICATION_ALLOW) {
1751                            Slog.i(TAG, "Continuing with installation of " + originUri);
1752                            state.setVerifierResponse(Binder.getCallingUid(),
1753                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1754                            broadcastPackageVerified(verificationId, originUri,
1755                                    PackageManager.VERIFICATION_ALLOW, user);
1756                            try {
1757                                ret = args.copyApk(mContainerService, true);
1758                            } catch (RemoteException e) {
1759                                Slog.e(TAG, "Could not contact the ContainerService");
1760                            }
1761                        } else {
1762                            broadcastPackageVerified(verificationId, originUri,
1763                                    PackageManager.VERIFICATION_REJECT, user);
1764                        }
1765
1766                        Trace.asyncTraceEnd(
1767                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1768
1769                        processPendingInstall(args, ret);
1770                        mHandler.sendEmptyMessage(MCS_UNBIND);
1771                    }
1772                    break;
1773                }
1774                case PACKAGE_VERIFIED: {
1775                    final int verificationId = msg.arg1;
1776
1777                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1778                    if (state == null) {
1779                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1780                        break;
1781                    }
1782
1783                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1784
1785                    state.setVerifierResponse(response.callerUid, response.code);
1786
1787                    if (state.isVerificationComplete()) {
1788                        mPendingVerification.remove(verificationId);
1789
1790                        final InstallArgs args = state.getInstallArgs();
1791                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1792
1793                        int ret;
1794                        if (state.isInstallAllowed()) {
1795                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1796                            broadcastPackageVerified(verificationId, originUri,
1797                                    response.code, state.getInstallArgs().getUser());
1798                            try {
1799                                ret = args.copyApk(mContainerService, true);
1800                            } catch (RemoteException e) {
1801                                Slog.e(TAG, "Could not contact the ContainerService");
1802                            }
1803                        } else {
1804                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1805                        }
1806
1807                        Trace.asyncTraceEnd(
1808                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1809
1810                        processPendingInstall(args, ret);
1811                        mHandler.sendEmptyMessage(MCS_UNBIND);
1812                    }
1813
1814                    break;
1815                }
1816                case START_INTENT_FILTER_VERIFICATIONS: {
1817                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1818                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1819                            params.replacing, params.pkg);
1820                    break;
1821                }
1822                case INTENT_FILTER_VERIFIED: {
1823                    final int verificationId = msg.arg1;
1824
1825                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1826                            verificationId);
1827                    if (state == null) {
1828                        Slog.w(TAG, "Invalid IntentFilter verification token "
1829                                + verificationId + " received");
1830                        break;
1831                    }
1832
1833                    final int userId = state.getUserId();
1834
1835                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1836                            "Processing IntentFilter verification with token:"
1837                            + verificationId + " and userId:" + userId);
1838
1839                    final IntentFilterVerificationResponse response =
1840                            (IntentFilterVerificationResponse) msg.obj;
1841
1842                    state.setVerifierResponse(response.callerUid, response.code);
1843
1844                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1845                            "IntentFilter verification with token:" + verificationId
1846                            + " and userId:" + userId
1847                            + " is settings verifier response with response code:"
1848                            + response.code);
1849
1850                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1851                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1852                                + response.getFailedDomainsString());
1853                    }
1854
1855                    if (state.isVerificationComplete()) {
1856                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1857                    } else {
1858                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1859                                "IntentFilter verification with token:" + verificationId
1860                                + " was not said to be complete");
1861                    }
1862
1863                    break;
1864                }
1865                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1866                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1867                            mInstantAppResolverConnection,
1868                            (InstantAppRequest) msg.obj,
1869                            mInstantAppInstallerActivity,
1870                            mHandler);
1871                }
1872            }
1873        }
1874    }
1875
1876    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1877        @Override
1878        public void onGidsChanged(int appId, int userId) {
1879            mHandler.post(new Runnable() {
1880                @Override
1881                public void run() {
1882                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1883                }
1884            });
1885        }
1886        @Override
1887        public void onPermissionGranted(int uid, int userId) {
1888            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1889
1890            // Not critical; if this is lost, the application has to request again.
1891            synchronized (mPackages) {
1892                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1893            }
1894        }
1895        @Override
1896        public void onInstallPermissionGranted() {
1897            synchronized (mPackages) {
1898                scheduleWriteSettingsLocked();
1899            }
1900        }
1901        @Override
1902        public void onPermissionRevoked(int uid, int userId) {
1903            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1904
1905            synchronized (mPackages) {
1906                // Critical; after this call the application should never have the permission
1907                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1908            }
1909
1910            final int appId = UserHandle.getAppId(uid);
1911            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1912        }
1913        @Override
1914        public void onInstallPermissionRevoked() {
1915            synchronized (mPackages) {
1916                scheduleWriteSettingsLocked();
1917            }
1918        }
1919        @Override
1920        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1921            synchronized (mPackages) {
1922                for (int userId : updatedUserIds) {
1923                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1924                }
1925            }
1926        }
1927        @Override
1928        public void onInstallPermissionUpdated() {
1929            synchronized (mPackages) {
1930                scheduleWriteSettingsLocked();
1931            }
1932        }
1933        @Override
1934        public void onPermissionRemoved() {
1935            synchronized (mPackages) {
1936                mSettings.writeLPr();
1937            }
1938        }
1939    };
1940
1941    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1942            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1943            boolean launchedForRestore, String installerPackage,
1944            IPackageInstallObserver2 installObserver) {
1945        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1946            // Send the removed broadcasts
1947            if (res.removedInfo != null) {
1948                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1949            }
1950
1951            // Now that we successfully installed the package, grant runtime
1952            // permissions if requested before broadcasting the install. Also
1953            // for legacy apps in permission review mode we clear the permission
1954            // review flag which is used to emulate runtime permissions for
1955            // legacy apps.
1956            if (grantPermissions) {
1957                final int callingUid = Binder.getCallingUid();
1958                mPermissionManager.grantRequestedRuntimePermissions(
1959                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1960                        mPermissionCallback);
1961            }
1962
1963            final boolean update = res.removedInfo != null
1964                    && res.removedInfo.removedPackage != null;
1965            final String installerPackageName =
1966                    res.installerPackageName != null
1967                            ? res.installerPackageName
1968                            : res.removedInfo != null
1969                                    ? res.removedInfo.installerPackageName
1970                                    : null;
1971
1972            // If this is the first time we have child packages for a disabled privileged
1973            // app that had no children, we grant requested runtime permissions to the new
1974            // children if the parent on the system image had them already granted.
1975            if (res.pkg.parentPackage != null) {
1976                final int callingUid = Binder.getCallingUid();
1977                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1978                        res.pkg, callingUid, mPermissionCallback);
1979            }
1980
1981            synchronized (mPackages) {
1982                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1983            }
1984
1985            final String packageName = res.pkg.applicationInfo.packageName;
1986
1987            // Determine the set of users who are adding this package for
1988            // the first time vs. those who are seeing an update.
1989            int[] firstUserIds = EMPTY_INT_ARRAY;
1990            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1991            int[] updateUserIds = EMPTY_INT_ARRAY;
1992            int[] instantUserIds = EMPTY_INT_ARRAY;
1993            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1994            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1995            for (int newUser : res.newUsers) {
1996                final boolean isInstantApp = ps.getInstantApp(newUser);
1997                if (allNewUsers) {
1998                    if (isInstantApp) {
1999                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2000                    } else {
2001                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2002                    }
2003                    continue;
2004                }
2005                boolean isNew = true;
2006                for (int origUser : res.origUsers) {
2007                    if (origUser == newUser) {
2008                        isNew = false;
2009                        break;
2010                    }
2011                }
2012                if (isNew) {
2013                    if (isInstantApp) {
2014                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2015                    } else {
2016                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2017                    }
2018                } else {
2019                    if (isInstantApp) {
2020                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2021                    } else {
2022                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2023                    }
2024                }
2025            }
2026
2027            // Send installed broadcasts if the package is not a static shared lib.
2028            if (res.pkg.staticSharedLibName == null) {
2029                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2030
2031                // Send added for users that see the package for the first time
2032                // sendPackageAddedForNewUsers also deals with system apps
2033                int appId = UserHandle.getAppId(res.uid);
2034                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2035                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2036                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2037
2038                // Send added for users that don't see the package for the first time
2039                Bundle extras = new Bundle(1);
2040                extras.putInt(Intent.EXTRA_UID, res.uid);
2041                if (update) {
2042                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2043                }
2044                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2045                        extras, 0 /*flags*/,
2046                        null /*targetPackage*/, null /*finishedReceiver*/,
2047                        updateUserIds, instantUserIds);
2048                if (installerPackageName != null) {
2049                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2050                            extras, 0 /*flags*/,
2051                            installerPackageName, null /*finishedReceiver*/,
2052                            updateUserIds, instantUserIds);
2053                }
2054
2055                // Send replaced for users that don't see the package for the first time
2056                if (update) {
2057                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2058                            packageName, extras, 0 /*flags*/,
2059                            null /*targetPackage*/, null /*finishedReceiver*/,
2060                            updateUserIds, instantUserIds);
2061                    if (installerPackageName != null) {
2062                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2063                                extras, 0 /*flags*/,
2064                                installerPackageName, null /*finishedReceiver*/,
2065                                updateUserIds, instantUserIds);
2066                    }
2067                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2068                            null /*package*/, null /*extras*/, 0 /*flags*/,
2069                            packageName /*targetPackage*/,
2070                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2071                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2072                    // First-install and we did a restore, so we're responsible for the
2073                    // first-launch broadcast.
2074                    if (DEBUG_BACKUP) {
2075                        Slog.i(TAG, "Post-restore of " + packageName
2076                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2077                    }
2078                    sendFirstLaunchBroadcast(packageName, installerPackage,
2079                            firstUserIds, firstInstantUserIds);
2080                }
2081
2082                // Send broadcast package appeared if forward locked/external for all users
2083                // treat asec-hosted packages like removable media on upgrade
2084                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2085                    if (DEBUG_INSTALL) {
2086                        Slog.i(TAG, "upgrading pkg " + res.pkg
2087                                + " is ASEC-hosted -> AVAILABLE");
2088                    }
2089                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2090                    ArrayList<String> pkgList = new ArrayList<>(1);
2091                    pkgList.add(packageName);
2092                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2093                }
2094            }
2095
2096            // Work that needs to happen on first install within each user
2097            if (firstUserIds != null && firstUserIds.length > 0) {
2098                synchronized (mPackages) {
2099                    for (int userId : firstUserIds) {
2100                        // If this app is a browser and it's newly-installed for some
2101                        // users, clear any default-browser state in those users. The
2102                        // app's nature doesn't depend on the user, so we can just check
2103                        // its browser nature in any user and generalize.
2104                        if (packageIsBrowser(packageName, userId)) {
2105                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2106                        }
2107
2108                        // We may also need to apply pending (restored) runtime
2109                        // permission grants within these users.
2110                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2111                    }
2112                }
2113            }
2114
2115            if (allNewUsers && !update) {
2116                notifyPackageAdded(packageName);
2117            }
2118
2119            // Log current value of "unknown sources" setting
2120            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2121                    getUnknownSourcesSettings());
2122
2123            // Remove the replaced package's older resources safely now
2124            // We delete after a gc for applications  on sdcard.
2125            if (res.removedInfo != null && res.removedInfo.args != null) {
2126                Runtime.getRuntime().gc();
2127                synchronized (mInstallLock) {
2128                    res.removedInfo.args.doPostDeleteLI(true);
2129                }
2130            } else {
2131                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2132                // and not block here.
2133                VMRuntime.getRuntime().requestConcurrentGC();
2134            }
2135
2136            // Notify DexManager that the package was installed for new users.
2137            // The updated users should already be indexed and the package code paths
2138            // should not change.
2139            // Don't notify the manager for ephemeral apps as they are not expected to
2140            // survive long enough to benefit of background optimizations.
2141            for (int userId : firstUserIds) {
2142                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2143                // There's a race currently where some install events may interleave with an uninstall.
2144                // This can lead to package info being null (b/36642664).
2145                if (info != null) {
2146                    mDexManager.notifyPackageInstalled(info, userId);
2147                }
2148            }
2149        }
2150
2151        // If someone is watching installs - notify them
2152        if (installObserver != null) {
2153            try {
2154                Bundle extras = extrasForInstallResult(res);
2155                installObserver.onPackageInstalled(res.name, res.returnCode,
2156                        res.returnMsg, extras);
2157            } catch (RemoteException e) {
2158                Slog.i(TAG, "Observer no longer exists.");
2159            }
2160        }
2161    }
2162
2163    private StorageEventListener mStorageListener = new StorageEventListener() {
2164        @Override
2165        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2166            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2167                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2168                    final String volumeUuid = vol.getFsUuid();
2169
2170                    // Clean up any users or apps that were removed or recreated
2171                    // while this volume was missing
2172                    sUserManager.reconcileUsers(volumeUuid);
2173                    reconcileApps(volumeUuid);
2174
2175                    // Clean up any install sessions that expired or were
2176                    // cancelled while this volume was missing
2177                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2178
2179                    loadPrivatePackages(vol);
2180
2181                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2182                    unloadPrivatePackages(vol);
2183                }
2184            }
2185        }
2186
2187        @Override
2188        public void onVolumeForgotten(String fsUuid) {
2189            if (TextUtils.isEmpty(fsUuid)) {
2190                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2191                return;
2192            }
2193
2194            // Remove any apps installed on the forgotten volume
2195            synchronized (mPackages) {
2196                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2197                for (PackageSetting ps : packages) {
2198                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2199                    deletePackageVersioned(new VersionedPackage(ps.name,
2200                            PackageManager.VERSION_CODE_HIGHEST),
2201                            new LegacyPackageDeleteObserver(null).getBinder(),
2202                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2203                    // Try very hard to release any references to this package
2204                    // so we don't risk the system server being killed due to
2205                    // open FDs
2206                    AttributeCache.instance().removePackage(ps.name);
2207                }
2208
2209                mSettings.onVolumeForgotten(fsUuid);
2210                mSettings.writeLPr();
2211            }
2212        }
2213    };
2214
2215    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2216        Bundle extras = null;
2217        switch (res.returnCode) {
2218            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2219                extras = new Bundle();
2220                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2221                        res.origPermission);
2222                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2223                        res.origPackage);
2224                break;
2225            }
2226            case PackageManager.INSTALL_SUCCEEDED: {
2227                extras = new Bundle();
2228                extras.putBoolean(Intent.EXTRA_REPLACING,
2229                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2230                break;
2231            }
2232        }
2233        return extras;
2234    }
2235
2236    void scheduleWriteSettingsLocked() {
2237        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2238            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2239        }
2240    }
2241
2242    void scheduleWritePackageListLocked(int userId) {
2243        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2244            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2245            msg.arg1 = userId;
2246            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2247        }
2248    }
2249
2250    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2251        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2252        scheduleWritePackageRestrictionsLocked(userId);
2253    }
2254
2255    void scheduleWritePackageRestrictionsLocked(int userId) {
2256        final int[] userIds = (userId == UserHandle.USER_ALL)
2257                ? sUserManager.getUserIds() : new int[]{userId};
2258        for (int nextUserId : userIds) {
2259            if (!sUserManager.exists(nextUserId)) return;
2260            mDirtyUsers.add(nextUserId);
2261            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2262                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2263            }
2264        }
2265    }
2266
2267    public static PackageManagerService main(Context context, Installer installer,
2268            boolean factoryTest, boolean onlyCore) {
2269        // Self-check for initial settings.
2270        PackageManagerServiceCompilerMapping.checkProperties();
2271
2272        PackageManagerService m = new PackageManagerService(context, installer,
2273                factoryTest, onlyCore);
2274        m.enableSystemUserPackages();
2275        ServiceManager.addService("package", m);
2276        final PackageManagerNative pmn = m.new PackageManagerNative();
2277        ServiceManager.addService("package_native", pmn);
2278        return m;
2279    }
2280
2281    private void enableSystemUserPackages() {
2282        if (!UserManager.isSplitSystemUser()) {
2283            return;
2284        }
2285        // For system user, enable apps based on the following conditions:
2286        // - app is whitelisted or belong to one of these groups:
2287        //   -- system app which has no launcher icons
2288        //   -- system app which has INTERACT_ACROSS_USERS permission
2289        //   -- system IME app
2290        // - app is not in the blacklist
2291        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2292        Set<String> enableApps = new ArraySet<>();
2293        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2294                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2295                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2296        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2297        enableApps.addAll(wlApps);
2298        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2299                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2300        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2301        enableApps.removeAll(blApps);
2302        Log.i(TAG, "Applications installed for system user: " + enableApps);
2303        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2304                UserHandle.SYSTEM);
2305        final int allAppsSize = allAps.size();
2306        synchronized (mPackages) {
2307            for (int i = 0; i < allAppsSize; i++) {
2308                String pName = allAps.get(i);
2309                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2310                // Should not happen, but we shouldn't be failing if it does
2311                if (pkgSetting == null) {
2312                    continue;
2313                }
2314                boolean install = enableApps.contains(pName);
2315                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2316                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2317                            + " for system user");
2318                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2319                }
2320            }
2321            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2322        }
2323    }
2324
2325    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2326        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2327                Context.DISPLAY_SERVICE);
2328        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2329    }
2330
2331    /**
2332     * Requests that files preopted on a secondary system partition be copied to the data partition
2333     * if possible.  Note that the actual copying of the files is accomplished by init for security
2334     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2335     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2336     */
2337    private static void requestCopyPreoptedFiles() {
2338        final int WAIT_TIME_MS = 100;
2339        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2340        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2341            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2342            // We will wait for up to 100 seconds.
2343            final long timeStart = SystemClock.uptimeMillis();
2344            final long timeEnd = timeStart + 100 * 1000;
2345            long timeNow = timeStart;
2346            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2347                try {
2348                    Thread.sleep(WAIT_TIME_MS);
2349                } catch (InterruptedException e) {
2350                    // Do nothing
2351                }
2352                timeNow = SystemClock.uptimeMillis();
2353                if (timeNow > timeEnd) {
2354                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2355                    Slog.wtf(TAG, "cppreopt did not finish!");
2356                    break;
2357                }
2358            }
2359
2360            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2361        }
2362    }
2363
2364    public PackageManagerService(Context context, Installer installer,
2365            boolean factoryTest, boolean onlyCore) {
2366        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2367        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2368        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2369                SystemClock.uptimeMillis());
2370
2371        if (mSdkVersion <= 0) {
2372            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2373        }
2374
2375        mContext = context;
2376
2377        mFactoryTest = factoryTest;
2378        mOnlyCore = onlyCore;
2379        mMetrics = new DisplayMetrics();
2380        mInstaller = installer;
2381
2382        // Create sub-components that provide services / data. Order here is important.
2383        synchronized (mInstallLock) {
2384        synchronized (mPackages) {
2385            // Expose private service for system components to use.
2386            LocalServices.addService(
2387                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2388            sUserManager = new UserManagerService(context, this,
2389                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2390            mPermissionManager = PermissionManagerService.create(context,
2391                    new DefaultPermissionGrantedCallback() {
2392                        @Override
2393                        public void onDefaultRuntimePermissionsGranted(int userId) {
2394                            synchronized(mPackages) {
2395                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2396                            }
2397                        }
2398                    }, mPackages /*externalLock*/);
2399            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2400            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2401        }
2402        }
2403        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2416                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2417
2418        String separateProcesses = SystemProperties.get("debug.separate_processes");
2419        if (separateProcesses != null && separateProcesses.length() > 0) {
2420            if ("*".equals(separateProcesses)) {
2421                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2422                mSeparateProcesses = null;
2423                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2424            } else {
2425                mDefParseFlags = 0;
2426                mSeparateProcesses = separateProcesses.split(",");
2427                Slog.w(TAG, "Running with debug.separate_processes: "
2428                        + separateProcesses);
2429            }
2430        } else {
2431            mDefParseFlags = 0;
2432            mSeparateProcesses = null;
2433        }
2434
2435        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2436                "*dexopt*");
2437        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2438                installer, mInstallLock);
2439        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2440                dexManagerListener);
2441        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2442        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2443
2444        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2445                FgThread.get().getLooper());
2446
2447        getDefaultDisplayMetrics(context, mMetrics);
2448
2449        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2450        SystemConfig systemConfig = SystemConfig.getInstance();
2451        mAvailableFeatures = systemConfig.getAvailableFeatures();
2452        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2453
2454        mProtectedPackages = new ProtectedPackages(mContext);
2455
2456        synchronized (mInstallLock) {
2457        // writer
2458        synchronized (mPackages) {
2459            mHandlerThread = new ServiceThread(TAG,
2460                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2461            mHandlerThread.start();
2462            mHandler = new PackageHandler(mHandlerThread.getLooper());
2463            mProcessLoggingHandler = new ProcessLoggingHandler();
2464            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2465            mInstantAppRegistry = new InstantAppRegistry(this);
2466
2467            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2468            final int builtInLibCount = libConfig.size();
2469            for (int i = 0; i < builtInLibCount; i++) {
2470                String name = libConfig.keyAt(i);
2471                String path = libConfig.valueAt(i);
2472                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2473                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2474            }
2475
2476            SELinuxMMAC.readInstallPolicy();
2477
2478            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2479            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2480            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2481
2482            // Clean up orphaned packages for which the code path doesn't exist
2483            // and they are an update to a system app - caused by bug/32321269
2484            final int packageSettingCount = mSettings.mPackages.size();
2485            for (int i = packageSettingCount - 1; i >= 0; i--) {
2486                PackageSetting ps = mSettings.mPackages.valueAt(i);
2487                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2488                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2489                    mSettings.mPackages.removeAt(i);
2490                    mSettings.enableSystemPackageLPw(ps.name);
2491                }
2492            }
2493
2494            if (mFirstBoot) {
2495                requestCopyPreoptedFiles();
2496            }
2497
2498            String customResolverActivity = Resources.getSystem().getString(
2499                    R.string.config_customResolverActivity);
2500            if (TextUtils.isEmpty(customResolverActivity)) {
2501                customResolverActivity = null;
2502            } else {
2503                mCustomResolverComponentName = ComponentName.unflattenFromString(
2504                        customResolverActivity);
2505            }
2506
2507            long startTime = SystemClock.uptimeMillis();
2508
2509            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2510                    startTime);
2511
2512            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2513            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2514
2515            if (bootClassPath == null) {
2516                Slog.w(TAG, "No BOOTCLASSPATH found!");
2517            }
2518
2519            if (systemServerClassPath == null) {
2520                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2521            }
2522
2523            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2524
2525            final VersionInfo ver = mSettings.getInternalVersion();
2526            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2527            if (mIsUpgrade) {
2528                logCriticalInfo(Log.INFO,
2529                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2530            }
2531
2532            // when upgrading from pre-M, promote system app permissions from install to runtime
2533            mPromoteSystemApps =
2534                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2535
2536            // When upgrading from pre-N, we need to handle package extraction like first boot,
2537            // as there is no profiling data available.
2538            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2539
2540            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2541
2542            // save off the names of pre-existing system packages prior to scanning; we don't
2543            // want to automatically grant runtime permissions for new system apps
2544            if (mPromoteSystemApps) {
2545                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2546                while (pkgSettingIter.hasNext()) {
2547                    PackageSetting ps = pkgSettingIter.next();
2548                    if (isSystemApp(ps)) {
2549                        mExistingSystemPackages.add(ps.name);
2550                    }
2551                }
2552            }
2553
2554            mCacheDir = preparePackageParserCache(mIsUpgrade);
2555
2556            // Set flag to monitor and not change apk file paths when
2557            // scanning install directories.
2558            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2559
2560            if (mIsUpgrade || mFirstBoot) {
2561                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2562            }
2563
2564            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2565            // For security and version matching reason, only consider
2566            // overlay packages if they reside in the right directory.
2567            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2568                    mDefParseFlags
2569                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2570                    scanFlags
2571                    | SCAN_AS_SYSTEM
2572                    | SCAN_AS_VENDOR,
2573                    0);
2574            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2575                    mDefParseFlags
2576                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2577                    scanFlags
2578                    | SCAN_AS_SYSTEM
2579                    | SCAN_AS_PRODUCT,
2580                    0);
2581
2582            mParallelPackageParserCallback.findStaticOverlayPackages();
2583
2584            // Find base frameworks (resource packages without code).
2585            scanDirTracedLI(frameworkDir,
2586                    mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2588                    scanFlags
2589                    | SCAN_NO_DEX
2590                    | SCAN_AS_SYSTEM
2591                    | SCAN_AS_PRIVILEGED,
2592                    0);
2593
2594            // Collect privileged system packages.
2595            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2596            scanDirTracedLI(privilegedAppDir,
2597                    mDefParseFlags
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2599                    scanFlags
2600                    | SCAN_AS_SYSTEM
2601                    | SCAN_AS_PRIVILEGED,
2602                    0);
2603
2604            // Collect ordinary system packages.
2605            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2606            scanDirTracedLI(systemAppDir,
2607                    mDefParseFlags
2608                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2609                    scanFlags
2610                    | SCAN_AS_SYSTEM,
2611                    0);
2612
2613            // Collect privileged vendor packages.
2614            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2615            try {
2616                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2617            } catch (IOException e) {
2618                // failed to look up canonical path, continue with original one
2619            }
2620            scanDirTracedLI(privilegedVendorAppDir,
2621                    mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2623                    scanFlags
2624                    | SCAN_AS_SYSTEM
2625                    | SCAN_AS_VENDOR
2626                    | SCAN_AS_PRIVILEGED,
2627                    0);
2628
2629            // Collect ordinary vendor packages.
2630            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2631            try {
2632                vendorAppDir = vendorAppDir.getCanonicalFile();
2633            } catch (IOException e) {
2634                // failed to look up canonical path, continue with original one
2635            }
2636            scanDirTracedLI(vendorAppDir,
2637                    mDefParseFlags
2638                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2639                    scanFlags
2640                    | SCAN_AS_SYSTEM
2641                    | SCAN_AS_VENDOR,
2642                    0);
2643
2644            // Collect privileged odm packages. /odm is another vendor partition
2645            // other than /vendor.
2646            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2647                        "priv-app");
2648            try {
2649                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2650            } catch (IOException e) {
2651                // failed to look up canonical path, continue with original one
2652            }
2653            scanDirTracedLI(privilegedOdmAppDir,
2654                    mDefParseFlags
2655                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2656                    scanFlags
2657                    | SCAN_AS_SYSTEM
2658                    | SCAN_AS_VENDOR
2659                    | SCAN_AS_PRIVILEGED,
2660                    0);
2661
2662            // Collect ordinary odm packages. /odm is another vendor partition
2663            // other than /vendor.
2664            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2665            try {
2666                odmAppDir = odmAppDir.getCanonicalFile();
2667            } catch (IOException e) {
2668                // failed to look up canonical path, continue with original one
2669            }
2670            scanDirTracedLI(odmAppDir,
2671                    mDefParseFlags
2672                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2673                    scanFlags
2674                    | SCAN_AS_SYSTEM
2675                    | SCAN_AS_VENDOR,
2676                    0);
2677
2678            // Collect all OEM packages.
2679            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2680            scanDirTracedLI(oemAppDir,
2681                    mDefParseFlags
2682                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2683                    scanFlags
2684                    | SCAN_AS_SYSTEM
2685                    | SCAN_AS_OEM,
2686                    0);
2687
2688            // Collected privileged product packages.
2689            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2690            try {
2691                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2692            } catch (IOException e) {
2693                // failed to look up canonical path, continue with original one
2694            }
2695            scanDirTracedLI(privilegedProductAppDir,
2696                    mDefParseFlags
2697                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2698                    scanFlags
2699                    | SCAN_AS_SYSTEM
2700                    | SCAN_AS_PRODUCT
2701                    | SCAN_AS_PRIVILEGED,
2702                    0);
2703
2704            // Collect ordinary product packages.
2705            File productAppDir = new File(Environment.getProductDirectory(), "app");
2706            try {
2707                productAppDir = productAppDir.getCanonicalFile();
2708            } catch (IOException e) {
2709                // failed to look up canonical path, continue with original one
2710            }
2711            scanDirTracedLI(productAppDir,
2712                    mDefParseFlags
2713                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2714                    scanFlags
2715                    | SCAN_AS_SYSTEM
2716                    | SCAN_AS_PRODUCT,
2717                    0);
2718
2719            // Prune any system packages that no longer exist.
2720            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2721            // Stub packages must either be replaced with full versions in the /data
2722            // partition or be disabled.
2723            final List<String> stubSystemApps = new ArrayList<>();
2724            if (!mOnlyCore) {
2725                // do this first before mucking with mPackages for the "expecting better" case
2726                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2727                while (pkgIterator.hasNext()) {
2728                    final PackageParser.Package pkg = pkgIterator.next();
2729                    if (pkg.isStub) {
2730                        stubSystemApps.add(pkg.packageName);
2731                    }
2732                }
2733
2734                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2735                while (psit.hasNext()) {
2736                    PackageSetting ps = psit.next();
2737
2738                    /*
2739                     * If this is not a system app, it can't be a
2740                     * disable system app.
2741                     */
2742                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2743                        continue;
2744                    }
2745
2746                    /*
2747                     * If the package is scanned, it's not erased.
2748                     */
2749                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2750                    if (scannedPkg != null) {
2751                        /*
2752                         * If the system app is both scanned and in the
2753                         * disabled packages list, then it must have been
2754                         * added via OTA. Remove it from the currently
2755                         * scanned package so the previously user-installed
2756                         * application can be scanned.
2757                         */
2758                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2759                            logCriticalInfo(Log.WARN,
2760                                    "Expecting better updated system app for " + ps.name
2761                                    + "; removing system app.  Last known"
2762                                    + " codePath=" + ps.codePathString
2763                                    + ", versionCode=" + ps.versionCode
2764                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2765                            removePackageLI(scannedPkg, true);
2766                            mExpectingBetter.put(ps.name, ps.codePath);
2767                        }
2768
2769                        continue;
2770                    }
2771
2772                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2773                        psit.remove();
2774                        logCriticalInfo(Log.WARN, "System package " + ps.name
2775                                + " no longer exists; it's data will be wiped");
2776                        // Actual deletion of code and data will be handled by later
2777                        // reconciliation step
2778                    } else {
2779                        // we still have a disabled system package, but, it still might have
2780                        // been removed. check the code path still exists and check there's
2781                        // still a package. the latter can happen if an OTA keeps the same
2782                        // code path, but, changes the package name.
2783                        final PackageSetting disabledPs =
2784                                mSettings.getDisabledSystemPkgLPr(ps.name);
2785                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2786                                || disabledPs.pkg == null) {
2787                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2788                        }
2789                    }
2790                }
2791            }
2792
2793            //delete tmp files
2794            deleteTempPackageFiles();
2795
2796            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2797
2798            // Remove any shared userIDs that have no associated packages
2799            mSettings.pruneSharedUsersLPw();
2800            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2801            final int systemPackagesCount = mPackages.size();
2802            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2803                    + " ms, packageCount: " + systemPackagesCount
2804                    + " , timePerPackage: "
2805                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2806                    + " , cached: " + cachedSystemApps);
2807            if (mIsUpgrade && systemPackagesCount > 0) {
2808                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2809                        ((int) systemScanTime) / systemPackagesCount);
2810            }
2811            if (!mOnlyCore) {
2812                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2813                        SystemClock.uptimeMillis());
2814                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2815
2816                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2817                        | PackageParser.PARSE_FORWARD_LOCK,
2818                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2819
2820                // Remove disable package settings for updated system apps that were
2821                // removed via an OTA. If the update is no longer present, remove the
2822                // app completely. Otherwise, revoke their system privileges.
2823                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2824                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2825                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2826                    final String msg;
2827                    if (deletedPkg == null) {
2828                        // should have found an update, but, we didn't; remove everything
2829                        msg = "Updated system package " + deletedAppName
2830                                + " no longer exists; removing its data";
2831                        // Actual deletion of code and data will be handled by later
2832                        // reconciliation step
2833                    } else {
2834                        // found an update; revoke system privileges
2835                        msg = "Updated system package + " + deletedAppName
2836                                + " no longer exists; revoking system privileges";
2837
2838                        // Don't do anything if a stub is removed from the system image. If
2839                        // we were to remove the uncompressed version from the /data partition,
2840                        // this is where it'd be done.
2841
2842                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2843                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2844                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2845                    }
2846                    logCriticalInfo(Log.WARN, msg);
2847                }
2848
2849                /*
2850                 * Make sure all system apps that we expected to appear on
2851                 * the userdata partition actually showed up. If they never
2852                 * appeared, crawl back and revive the system version.
2853                 */
2854                for (int i = 0; i < mExpectingBetter.size(); i++) {
2855                    final String packageName = mExpectingBetter.keyAt(i);
2856                    if (!mPackages.containsKey(packageName)) {
2857                        final File scanFile = mExpectingBetter.valueAt(i);
2858
2859                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2860                                + " but never showed up; reverting to system");
2861
2862                        final @ParseFlags int reparseFlags;
2863                        final @ScanFlags int rescanFlags;
2864                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2865                            reparseFlags =
2866                                    mDefParseFlags |
2867                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2868                            rescanFlags =
2869                                    scanFlags
2870                                    | SCAN_AS_SYSTEM
2871                                    | SCAN_AS_PRIVILEGED;
2872                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2873                            reparseFlags =
2874                                    mDefParseFlags |
2875                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2876                            rescanFlags =
2877                                    scanFlags
2878                                    | SCAN_AS_SYSTEM;
2879                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2880                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2881                            reparseFlags =
2882                                    mDefParseFlags |
2883                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2884                            rescanFlags =
2885                                    scanFlags
2886                                    | SCAN_AS_SYSTEM
2887                                    | SCAN_AS_VENDOR
2888                                    | SCAN_AS_PRIVILEGED;
2889                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2890                                || FileUtils.contains(odmAppDir, scanFile)) {
2891                            reparseFlags =
2892                                    mDefParseFlags |
2893                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2894                            rescanFlags =
2895                                    scanFlags
2896                                    | SCAN_AS_SYSTEM
2897                                    | SCAN_AS_VENDOR;
2898                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2899                            reparseFlags =
2900                                    mDefParseFlags |
2901                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2902                            rescanFlags =
2903                                    scanFlags
2904                                    | SCAN_AS_SYSTEM
2905                                    | SCAN_AS_OEM;
2906                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2907                            reparseFlags =
2908                                    mDefParseFlags |
2909                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2910                            rescanFlags =
2911                                    scanFlags
2912                                    | SCAN_AS_SYSTEM
2913                                    | SCAN_AS_PRODUCT
2914                                    | SCAN_AS_PRIVILEGED;
2915                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2916                            reparseFlags =
2917                                    mDefParseFlags |
2918                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2919                            rescanFlags =
2920                                    scanFlags
2921                                    | SCAN_AS_SYSTEM
2922                                    | SCAN_AS_PRODUCT;
2923                        } else {
2924                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2925                            continue;
2926                        }
2927
2928                        mSettings.enableSystemPackageLPw(packageName);
2929
2930                        try {
2931                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2932                        } catch (PackageManagerException e) {
2933                            Slog.e(TAG, "Failed to parse original system package: "
2934                                    + e.getMessage());
2935                        }
2936                    }
2937                }
2938
2939                // Uncompress and install any stubbed system applications.
2940                // This must be done last to ensure all stubs are replaced or disabled.
2941                decompressSystemApplications(stubSystemApps, scanFlags);
2942
2943                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2944                                - cachedSystemApps;
2945
2946                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2947                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2948                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2949                        + " ms, packageCount: " + dataPackagesCount
2950                        + " , timePerPackage: "
2951                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2952                        + " , cached: " + cachedNonSystemApps);
2953                if (mIsUpgrade && dataPackagesCount > 0) {
2954                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2955                            ((int) dataScanTime) / dataPackagesCount);
2956                }
2957            }
2958            mExpectingBetter.clear();
2959
2960            // Resolve the storage manager.
2961            mStorageManagerPackage = getStorageManagerPackageName();
2962
2963            // Resolve protected action filters. Only the setup wizard is allowed to
2964            // have a high priority filter for these actions.
2965            mSetupWizardPackage = getSetupWizardPackageName();
2966            if (mProtectedFilters.size() > 0) {
2967                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2968                    Slog.i(TAG, "No setup wizard;"
2969                        + " All protected intents capped to priority 0");
2970                }
2971                for (ActivityIntentInfo filter : mProtectedFilters) {
2972                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2973                        if (DEBUG_FILTERS) {
2974                            Slog.i(TAG, "Found setup wizard;"
2975                                + " allow priority " + filter.getPriority() + ";"
2976                                + " package: " + filter.activity.info.packageName
2977                                + " activity: " + filter.activity.className
2978                                + " priority: " + filter.getPriority());
2979                        }
2980                        // skip setup wizard; allow it to keep the high priority filter
2981                        continue;
2982                    }
2983                    if (DEBUG_FILTERS) {
2984                        Slog.i(TAG, "Protected action; cap priority to 0;"
2985                                + " package: " + filter.activity.info.packageName
2986                                + " activity: " + filter.activity.className
2987                                + " origPrio: " + filter.getPriority());
2988                    }
2989                    filter.setPriority(0);
2990                }
2991            }
2992
2993            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
2994
2995            mDeferProtectedFilters = false;
2996            mProtectedFilters.clear();
2997
2998            // Now that we know all of the shared libraries, update all clients to have
2999            // the correct library paths.
3000            updateAllSharedLibrariesLPw(null);
3001
3002            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3003                // NOTE: We ignore potential failures here during a system scan (like
3004                // the rest of the commands above) because there's precious little we
3005                // can do about it. A settings error is reported, though.
3006                final List<String> changedAbiCodePath =
3007                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3008                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3009                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3010                        final String codePathString = changedAbiCodePath.get(i);
3011                        try {
3012                            mInstaller.rmdex(codePathString,
3013                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3014                        } catch (InstallerException ignored) {
3015                        }
3016                    }
3017                }
3018                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3019                // SELinux domain.
3020                setting.fixSeInfoLocked();
3021            }
3022
3023            // Now that we know all the packages we are keeping,
3024            // read and update their last usage times.
3025            mPackageUsage.read(mPackages);
3026            mCompilerStats.read();
3027
3028            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3029                    SystemClock.uptimeMillis());
3030            Slog.i(TAG, "Time to scan packages: "
3031                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3032                    + " seconds");
3033
3034            // If the platform SDK has changed since the last time we booted,
3035            // we need to re-grant app permission to catch any new ones that
3036            // appear.  This is really a hack, and means that apps can in some
3037            // cases get permissions that the user didn't initially explicitly
3038            // allow...  it would be nice to have some better way to handle
3039            // this situation.
3040            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3041            if (sdkUpdated) {
3042                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3043                        + mSdkVersion + "; regranting permissions for internal storage");
3044            }
3045            mPermissionManager.updateAllPermissions(
3046                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3047                    mPermissionCallback);
3048            ver.sdkVersion = mSdkVersion;
3049
3050            // If this is the first boot or an update from pre-M, and it is a normal
3051            // boot, then we need to initialize the default preferred apps across
3052            // all defined users.
3053            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3054                for (UserInfo user : sUserManager.getUsers(true)) {
3055                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3056                    applyFactoryDefaultBrowserLPw(user.id);
3057                    primeDomainVerificationsLPw(user.id);
3058                }
3059            }
3060
3061            // Prepare storage for system user really early during boot,
3062            // since core system apps like SettingsProvider and SystemUI
3063            // can't wait for user to start
3064            final int storageFlags;
3065            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3066                storageFlags = StorageManager.FLAG_STORAGE_DE;
3067            } else {
3068                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3069            }
3070            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3071                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3072                    true /* onlyCoreApps */);
3073            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3074                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3075                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3076                traceLog.traceBegin("AppDataFixup");
3077                try {
3078                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3079                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3080                } catch (InstallerException e) {
3081                    Slog.w(TAG, "Trouble fixing GIDs", e);
3082                }
3083                traceLog.traceEnd();
3084
3085                traceLog.traceBegin("AppDataPrepare");
3086                if (deferPackages == null || deferPackages.isEmpty()) {
3087                    return;
3088                }
3089                int count = 0;
3090                for (String pkgName : deferPackages) {
3091                    PackageParser.Package pkg = null;
3092                    synchronized (mPackages) {
3093                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3094                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3095                            pkg = ps.pkg;
3096                        }
3097                    }
3098                    if (pkg != null) {
3099                        synchronized (mInstallLock) {
3100                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3101                                    true /* maybeMigrateAppData */);
3102                        }
3103                        count++;
3104                    }
3105                }
3106                traceLog.traceEnd();
3107                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3108            }, "prepareAppData");
3109
3110            // If this is first boot after an OTA, and a normal boot, then
3111            // we need to clear code cache directories.
3112            // Note that we do *not* clear the application profiles. These remain valid
3113            // across OTAs and are used to drive profile verification (post OTA) and
3114            // profile compilation (without waiting to collect a fresh set of profiles).
3115            if (mIsUpgrade && !onlyCore) {
3116                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3117                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3118                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3119                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3120                        // No apps are running this early, so no need to freeze
3121                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3122                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3123                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3124                    }
3125                }
3126                ver.fingerprint = Build.FINGERPRINT;
3127            }
3128
3129            checkDefaultBrowser();
3130
3131            // clear only after permissions and other defaults have been updated
3132            mExistingSystemPackages.clear();
3133            mPromoteSystemApps = false;
3134
3135            // All the changes are done during package scanning.
3136            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3137
3138            // can downgrade to reader
3139            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3140            mSettings.writeLPr();
3141            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3142            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3143                    SystemClock.uptimeMillis());
3144
3145            if (!mOnlyCore) {
3146                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3147                mRequiredInstallerPackage = getRequiredInstallerLPr();
3148                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3149                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3150                if (mIntentFilterVerifierComponent != null) {
3151                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3152                            mIntentFilterVerifierComponent);
3153                } else {
3154                    mIntentFilterVerifier = null;
3155                }
3156                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3157                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3158                        SharedLibraryInfo.VERSION_UNDEFINED);
3159                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3160                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3161                        SharedLibraryInfo.VERSION_UNDEFINED);
3162            } else {
3163                mRequiredVerifierPackage = null;
3164                mRequiredInstallerPackage = null;
3165                mRequiredUninstallerPackage = null;
3166                mIntentFilterVerifierComponent = null;
3167                mIntentFilterVerifier = null;
3168                mServicesSystemSharedLibraryPackageName = null;
3169                mSharedSystemSharedLibraryPackageName = null;
3170            }
3171
3172            mInstallerService = new PackageInstallerService(context, this);
3173            final Pair<ComponentName, String> instantAppResolverComponent =
3174                    getInstantAppResolverLPr();
3175            if (instantAppResolverComponent != null) {
3176                if (DEBUG_INSTANT) {
3177                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3178                }
3179                mInstantAppResolverConnection = new InstantAppResolverConnection(
3180                        mContext, instantAppResolverComponent.first,
3181                        instantAppResolverComponent.second);
3182                mInstantAppResolverSettingsComponent =
3183                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3184            } else {
3185                mInstantAppResolverConnection = null;
3186                mInstantAppResolverSettingsComponent = null;
3187            }
3188            updateInstantAppInstallerLocked(null);
3189
3190            // Read and update the usage of dex files.
3191            // Do this at the end of PM init so that all the packages have their
3192            // data directory reconciled.
3193            // At this point we know the code paths of the packages, so we can validate
3194            // the disk file and build the internal cache.
3195            // The usage file is expected to be small so loading and verifying it
3196            // should take a fairly small time compare to the other activities (e.g. package
3197            // scanning).
3198            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3199            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3200            for (int userId : currentUserIds) {
3201                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3202            }
3203            mDexManager.load(userPackages);
3204            if (mIsUpgrade) {
3205                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3206                        (int) (SystemClock.uptimeMillis() - startTime));
3207            }
3208        } // synchronized (mPackages)
3209        } // synchronized (mInstallLock)
3210
3211        // Now after opening every single application zip, make sure they
3212        // are all flushed.  Not really needed, but keeps things nice and
3213        // tidy.
3214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3215        Runtime.getRuntime().gc();
3216        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3217
3218        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3219        FallbackCategoryProvider.loadFallbacks();
3220        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3221
3222        // The initial scanning above does many calls into installd while
3223        // holding the mPackages lock, but we're mostly interested in yelling
3224        // once we have a booted system.
3225        mInstaller.setWarnIfHeld(mPackages);
3226
3227        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3228    }
3229
3230    /**
3231     * Uncompress and install stub applications.
3232     * <p>In order to save space on the system partition, some applications are shipped in a
3233     * compressed form. In addition the compressed bits for the full application, the
3234     * system image contains a tiny stub comprised of only the Android manifest.
3235     * <p>During the first boot, attempt to uncompress and install the full application. If
3236     * the application can't be installed for any reason, disable the stub and prevent
3237     * uncompressing the full application during future boots.
3238     * <p>In order to forcefully attempt an installation of a full application, go to app
3239     * settings and enable the application.
3240     */
3241    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3242        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3243            final String pkgName = stubSystemApps.get(i);
3244            // skip if the system package is already disabled
3245            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3246                stubSystemApps.remove(i);
3247                continue;
3248            }
3249            // skip if the package isn't installed (?!); this should never happen
3250            final PackageParser.Package pkg = mPackages.get(pkgName);
3251            if (pkg == null) {
3252                stubSystemApps.remove(i);
3253                continue;
3254            }
3255            // skip if the package has been disabled by the user
3256            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3257            if (ps != null) {
3258                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3259                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3260                    stubSystemApps.remove(i);
3261                    continue;
3262                }
3263            }
3264
3265            if (DEBUG_COMPRESSION) {
3266                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3267            }
3268
3269            // uncompress the binary to its eventual destination on /data
3270            final File scanFile = decompressPackage(pkg);
3271            if (scanFile == null) {
3272                continue;
3273            }
3274
3275            // install the package to replace the stub on /system
3276            try {
3277                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3278                removePackageLI(pkg, true /*chatty*/);
3279                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3280                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3281                        UserHandle.USER_SYSTEM, "android");
3282                stubSystemApps.remove(i);
3283                continue;
3284            } catch (PackageManagerException e) {
3285                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3286            }
3287
3288            // any failed attempt to install the package will be cleaned up later
3289        }
3290
3291        // disable any stub still left; these failed to install the full application
3292        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3293            final String pkgName = stubSystemApps.get(i);
3294            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3295            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3296                    UserHandle.USER_SYSTEM, "android");
3297            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3298        }
3299    }
3300
3301    /**
3302     * Decompresses the given package on the system image onto
3303     * the /data partition.
3304     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3305     */
3306    private File decompressPackage(PackageParser.Package pkg) {
3307        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3308        if (compressedFiles == null || compressedFiles.length == 0) {
3309            if (DEBUG_COMPRESSION) {
3310                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3311            }
3312            return null;
3313        }
3314        final File dstCodePath =
3315                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3316        int ret = PackageManager.INSTALL_SUCCEEDED;
3317        try {
3318            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3319            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3320            for (File srcFile : compressedFiles) {
3321                final String srcFileName = srcFile.getName();
3322                final String dstFileName = srcFileName.substring(
3323                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3324                final File dstFile = new File(dstCodePath, dstFileName);
3325                ret = decompressFile(srcFile, dstFile);
3326                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3327                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3328                            + "; pkg: " + pkg.packageName
3329                            + ", file: " + dstFileName);
3330                    break;
3331                }
3332            }
3333        } catch (ErrnoException e) {
3334            logCriticalInfo(Log.ERROR, "Failed to decompress"
3335                    + "; pkg: " + pkg.packageName
3336                    + ", err: " + e.errno);
3337        }
3338        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3339            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3340            NativeLibraryHelper.Handle handle = null;
3341            try {
3342                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3343                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3344                        null /*abiOverride*/);
3345            } catch (IOException e) {
3346                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3347                        + "; pkg: " + pkg.packageName);
3348                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3349            } finally {
3350                IoUtils.closeQuietly(handle);
3351            }
3352        }
3353        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3354            if (dstCodePath == null || !dstCodePath.exists()) {
3355                return null;
3356            }
3357            removeCodePathLI(dstCodePath);
3358            return null;
3359        }
3360
3361        return dstCodePath;
3362    }
3363
3364    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3365        // we're only interested in updating the installer appliction when 1) it's not
3366        // already set or 2) the modified package is the installer
3367        if (mInstantAppInstallerActivity != null
3368                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3369                        .equals(modifiedPackage)) {
3370            return;
3371        }
3372        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3373    }
3374
3375    private static File preparePackageParserCache(boolean isUpgrade) {
3376        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3377            return null;
3378        }
3379
3380        // Disable package parsing on eng builds to allow for faster incremental development.
3381        if (Build.IS_ENG) {
3382            return null;
3383        }
3384
3385        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3386            Slog.i(TAG, "Disabling package parser cache due to system property.");
3387            return null;
3388        }
3389
3390        // The base directory for the package parser cache lives under /data/system/.
3391        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3392                "package_cache");
3393        if (cacheBaseDir == null) {
3394            return null;
3395        }
3396
3397        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3398        // This also serves to "GC" unused entries when the package cache version changes (which
3399        // can only happen during upgrades).
3400        if (isUpgrade) {
3401            FileUtils.deleteContents(cacheBaseDir);
3402        }
3403
3404
3405        // Return the versioned package cache directory. This is something like
3406        // "/data/system/package_cache/1"
3407        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3408
3409        if (cacheDir == null) {
3410            // Something went wrong. Attempt to delete everything and return.
3411            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3412            FileUtils.deleteContentsAndDir(cacheBaseDir);
3413            return null;
3414        }
3415
3416        // The following is a workaround to aid development on non-numbered userdebug
3417        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3418        // the system partition is newer.
3419        //
3420        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3421        // that starts with "eng." to signify that this is an engineering build and not
3422        // destined for release.
3423        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3424            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3425
3426            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3427            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3428            // in general and should not be used for production changes. In this specific case,
3429            // we know that they will work.
3430            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3431            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3432                FileUtils.deleteContents(cacheBaseDir);
3433                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3434            }
3435        }
3436
3437        return cacheDir;
3438    }
3439
3440    @Override
3441    public boolean isFirstBoot() {
3442        // allow instant applications
3443        return mFirstBoot;
3444    }
3445
3446    @Override
3447    public boolean isOnlyCoreApps() {
3448        // allow instant applications
3449        return mOnlyCore;
3450    }
3451
3452    @Override
3453    public boolean isUpgrade() {
3454        // allow instant applications
3455        // The system property allows testing ota flow when upgraded to the same image.
3456        return mIsUpgrade || SystemProperties.getBoolean(
3457                "persist.pm.mock-upgrade", false /* default */);
3458    }
3459
3460    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3461        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3462
3463        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3464                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3465                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3466        if (matches.size() == 1) {
3467            return matches.get(0).getComponentInfo().packageName;
3468        } else if (matches.size() == 0) {
3469            Log.e(TAG, "There should probably be a verifier, but, none were found");
3470            return null;
3471        }
3472        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3473    }
3474
3475    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3476        synchronized (mPackages) {
3477            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3478            if (libraryEntry == null) {
3479                throw new IllegalStateException("Missing required shared library:" + name);
3480            }
3481            return libraryEntry.apk;
3482        }
3483    }
3484
3485    private @NonNull String getRequiredInstallerLPr() {
3486        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3487        intent.addCategory(Intent.CATEGORY_DEFAULT);
3488        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3489
3490        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3491                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3492                UserHandle.USER_SYSTEM);
3493        if (matches.size() == 1) {
3494            ResolveInfo resolveInfo = matches.get(0);
3495            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3496                throw new RuntimeException("The installer must be a privileged app");
3497            }
3498            return matches.get(0).getComponentInfo().packageName;
3499        } else {
3500            throw new RuntimeException("There must be exactly one installer; found " + matches);
3501        }
3502    }
3503
3504    private @NonNull String getRequiredUninstallerLPr() {
3505        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3506        intent.addCategory(Intent.CATEGORY_DEFAULT);
3507        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3508
3509        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3510                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3511                UserHandle.USER_SYSTEM);
3512        if (resolveInfo == null ||
3513                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3514            throw new RuntimeException("There must be exactly one uninstaller; found "
3515                    + resolveInfo);
3516        }
3517        return resolveInfo.getComponentInfo().packageName;
3518    }
3519
3520    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3521        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3522
3523        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3524                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3525                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3526        ResolveInfo best = null;
3527        final int N = matches.size();
3528        for (int i = 0; i < N; i++) {
3529            final ResolveInfo cur = matches.get(i);
3530            final String packageName = cur.getComponentInfo().packageName;
3531            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3532                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3533                continue;
3534            }
3535
3536            if (best == null || cur.priority > best.priority) {
3537                best = cur;
3538            }
3539        }
3540
3541        if (best != null) {
3542            return best.getComponentInfo().getComponentName();
3543        }
3544        Slog.w(TAG, "Intent filter verifier not found");
3545        return null;
3546    }
3547
3548    @Override
3549    public @Nullable ComponentName getInstantAppResolverComponent() {
3550        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3551            return null;
3552        }
3553        synchronized (mPackages) {
3554            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3555            if (instantAppResolver == null) {
3556                return null;
3557            }
3558            return instantAppResolver.first;
3559        }
3560    }
3561
3562    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3563        final String[] packageArray =
3564                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3565        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3566            if (DEBUG_INSTANT) {
3567                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3568            }
3569            return null;
3570        }
3571
3572        final int callingUid = Binder.getCallingUid();
3573        final int resolveFlags =
3574                MATCH_DIRECT_BOOT_AWARE
3575                | MATCH_DIRECT_BOOT_UNAWARE
3576                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3577        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3578        final Intent resolverIntent = new Intent(actionName);
3579        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3580                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3581        final int N = resolvers.size();
3582        if (N == 0) {
3583            if (DEBUG_INSTANT) {
3584                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3585            }
3586            return null;
3587        }
3588
3589        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3590        for (int i = 0; i < N; i++) {
3591            final ResolveInfo info = resolvers.get(i);
3592
3593            if (info.serviceInfo == null) {
3594                continue;
3595            }
3596
3597            final String packageName = info.serviceInfo.packageName;
3598            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3599                if (DEBUG_INSTANT) {
3600                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3601                            + " pkg: " + packageName + ", info:" + info);
3602                }
3603                continue;
3604            }
3605
3606            if (DEBUG_INSTANT) {
3607                Slog.v(TAG, "Ephemeral resolver found;"
3608                        + " pkg: " + packageName + ", info:" + info);
3609            }
3610            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3611        }
3612        if (DEBUG_INSTANT) {
3613            Slog.v(TAG, "Ephemeral resolver NOT found");
3614        }
3615        return null;
3616    }
3617
3618    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3619        String[] orderedActions = Build.IS_ENG
3620                ? new String[]{
3621                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3622                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3623                : new String[]{
3624                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3625
3626        final int resolveFlags =
3627                MATCH_DIRECT_BOOT_AWARE
3628                        | MATCH_DIRECT_BOOT_UNAWARE
3629                        | Intent.FLAG_IGNORE_EPHEMERAL
3630                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3631        final Intent intent = new Intent();
3632        intent.addCategory(Intent.CATEGORY_DEFAULT);
3633        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3634        List<ResolveInfo> matches = null;
3635        for (String action : orderedActions) {
3636            intent.setAction(action);
3637            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3638                    resolveFlags, UserHandle.USER_SYSTEM);
3639            if (matches.isEmpty()) {
3640                if (DEBUG_INSTANT) {
3641                    Slog.d(TAG, "Instant App installer not found with " + action);
3642                }
3643            } else {
3644                break;
3645            }
3646        }
3647        Iterator<ResolveInfo> iter = matches.iterator();
3648        while (iter.hasNext()) {
3649            final ResolveInfo rInfo = iter.next();
3650            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3651            if (ps != null) {
3652                final PermissionsState permissionsState = ps.getPermissionsState();
3653                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3654                        || Build.IS_ENG) {
3655                    continue;
3656                }
3657            }
3658            iter.remove();
3659        }
3660        if (matches.size() == 0) {
3661            return null;
3662        } else if (matches.size() == 1) {
3663            return (ActivityInfo) matches.get(0).getComponentInfo();
3664        } else {
3665            throw new RuntimeException(
3666                    "There must be at most one ephemeral installer; found " + matches);
3667        }
3668    }
3669
3670    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3671            @NonNull ComponentName resolver) {
3672        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3673                .addCategory(Intent.CATEGORY_DEFAULT)
3674                .setPackage(resolver.getPackageName());
3675        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3676        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3677                UserHandle.USER_SYSTEM);
3678        if (matches.isEmpty()) {
3679            return null;
3680        }
3681        return matches.get(0).getComponentInfo().getComponentName();
3682    }
3683
3684    private void primeDomainVerificationsLPw(int userId) {
3685        if (DEBUG_DOMAIN_VERIFICATION) {
3686            Slog.d(TAG, "Priming domain verifications in user " + userId);
3687        }
3688
3689        SystemConfig systemConfig = SystemConfig.getInstance();
3690        ArraySet<String> packages = systemConfig.getLinkedApps();
3691
3692        for (String packageName : packages) {
3693            PackageParser.Package pkg = mPackages.get(packageName);
3694            if (pkg != null) {
3695                if (!pkg.isSystem()) {
3696                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3697                    continue;
3698                }
3699
3700                ArraySet<String> domains = null;
3701                for (PackageParser.Activity a : pkg.activities) {
3702                    for (ActivityIntentInfo filter : a.intents) {
3703                        if (hasValidDomains(filter)) {
3704                            if (domains == null) {
3705                                domains = new ArraySet<String>();
3706                            }
3707                            domains.addAll(filter.getHostsList());
3708                        }
3709                    }
3710                }
3711
3712                if (domains != null && domains.size() > 0) {
3713                    if (DEBUG_DOMAIN_VERIFICATION) {
3714                        Slog.v(TAG, "      + " + packageName);
3715                    }
3716                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3717                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3718                    // and then 'always' in the per-user state actually used for intent resolution.
3719                    final IntentFilterVerificationInfo ivi;
3720                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3721                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3722                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3723                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3724                } else {
3725                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3726                            + "' does not handle web links");
3727                }
3728            } else {
3729                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3730            }
3731        }
3732
3733        scheduleWritePackageRestrictionsLocked(userId);
3734        scheduleWriteSettingsLocked();
3735    }
3736
3737    private void applyFactoryDefaultBrowserLPw(int userId) {
3738        // The default browser app's package name is stored in a string resource,
3739        // with a product-specific overlay used for vendor customization.
3740        String browserPkg = mContext.getResources().getString(
3741                com.android.internal.R.string.default_browser);
3742        if (!TextUtils.isEmpty(browserPkg)) {
3743            // non-empty string => required to be a known package
3744            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3745            if (ps == null) {
3746                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3747                browserPkg = null;
3748            } else {
3749                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3750            }
3751        }
3752
3753        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3754        // default.  If there's more than one, just leave everything alone.
3755        if (browserPkg == null) {
3756            calculateDefaultBrowserLPw(userId);
3757        }
3758    }
3759
3760    private void calculateDefaultBrowserLPw(int userId) {
3761        List<String> allBrowsers = resolveAllBrowserApps(userId);
3762        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3763        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3764    }
3765
3766    private List<String> resolveAllBrowserApps(int userId) {
3767        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3768        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3769                PackageManager.MATCH_ALL, userId);
3770
3771        final int count = list.size();
3772        List<String> result = new ArrayList<String>(count);
3773        for (int i=0; i<count; i++) {
3774            ResolveInfo info = list.get(i);
3775            if (info.activityInfo == null
3776                    || !info.handleAllWebDataURI
3777                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3778                    || result.contains(info.activityInfo.packageName)) {
3779                continue;
3780            }
3781            result.add(info.activityInfo.packageName);
3782        }
3783
3784        return result;
3785    }
3786
3787    private boolean packageIsBrowser(String packageName, int userId) {
3788        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3789                PackageManager.MATCH_ALL, userId);
3790        final int N = list.size();
3791        for (int i = 0; i < N; i++) {
3792            ResolveInfo info = list.get(i);
3793            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3794                return true;
3795            }
3796        }
3797        return false;
3798    }
3799
3800    private void checkDefaultBrowser() {
3801        final int myUserId = UserHandle.myUserId();
3802        final String packageName = getDefaultBrowserPackageName(myUserId);
3803        if (packageName != null) {
3804            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3805            if (info == null) {
3806                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3807                synchronized (mPackages) {
3808                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3809                }
3810            }
3811        }
3812    }
3813
3814    @Override
3815    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3816            throws RemoteException {
3817        try {
3818            return super.onTransact(code, data, reply, flags);
3819        } catch (RuntimeException e) {
3820            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3821                Slog.wtf(TAG, "Package Manager Crash", e);
3822            }
3823            throw e;
3824        }
3825    }
3826
3827    static int[] appendInts(int[] cur, int[] add) {
3828        if (add == null) return cur;
3829        if (cur == null) return add;
3830        final int N = add.length;
3831        for (int i=0; i<N; i++) {
3832            cur = appendInt(cur, add[i]);
3833        }
3834        return cur;
3835    }
3836
3837    /**
3838     * Returns whether or not a full application can see an instant application.
3839     * <p>
3840     * Currently, there are three cases in which this can occur:
3841     * <ol>
3842     * <li>The calling application is a "special" process. Special processes
3843     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3844     * <li>The calling application has the permission
3845     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3846     * <li>The calling application is the default launcher on the
3847     *     system partition.</li>
3848     * </ol>
3849     */
3850    private boolean canViewInstantApps(int callingUid, int userId) {
3851        if (callingUid < Process.FIRST_APPLICATION_UID) {
3852            return true;
3853        }
3854        if (mContext.checkCallingOrSelfPermission(
3855                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3856            return true;
3857        }
3858        if (mContext.checkCallingOrSelfPermission(
3859                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3860            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3861            if (homeComponent != null
3862                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3863                return true;
3864            }
3865        }
3866        return false;
3867    }
3868
3869    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3870        if (!sUserManager.exists(userId)) return null;
3871        if (ps == null) {
3872            return null;
3873        }
3874        final int callingUid = Binder.getCallingUid();
3875        // Filter out ephemeral app metadata:
3876        //   * The system/shell/root can see metadata for any app
3877        //   * An installed app can see metadata for 1) other installed apps
3878        //     and 2) ephemeral apps that have explicitly interacted with it
3879        //   * Ephemeral apps can only see their own data and exposed installed apps
3880        //   * Holding a signature permission allows seeing instant apps
3881        if (filterAppAccessLPr(ps, callingUid, userId)) {
3882            return null;
3883        }
3884
3885        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3886                && ps.isSystem()) {
3887            flags |= MATCH_ANY_USER;
3888        }
3889
3890        final PackageUserState state = ps.readUserState(userId);
3891        PackageParser.Package p = ps.pkg;
3892        if (p != null) {
3893            final PermissionsState permissionsState = ps.getPermissionsState();
3894
3895            // Compute GIDs only if requested
3896            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3897                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3898            // Compute granted permissions only if package has requested permissions
3899            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3900                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3901
3902            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3903                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3904
3905            if (packageInfo == null) {
3906                return null;
3907            }
3908
3909            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3910                    resolveExternalPackageNameLPr(p);
3911
3912            return packageInfo;
3913        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3914            PackageInfo pi = new PackageInfo();
3915            pi.packageName = ps.name;
3916            pi.setLongVersionCode(ps.versionCode);
3917            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3918            pi.firstInstallTime = ps.firstInstallTime;
3919            pi.lastUpdateTime = ps.lastUpdateTime;
3920
3921            ApplicationInfo ai = new ApplicationInfo();
3922            ai.packageName = ps.name;
3923            ai.uid = UserHandle.getUid(userId, ps.appId);
3924            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3925            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3926            ai.versionCode = ps.versionCode;
3927            ai.flags = ps.pkgFlags;
3928            ai.privateFlags = ps.pkgPrivateFlags;
3929            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3930
3931            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3932                    + ps.name + "]. Provides a minimum info.");
3933            return pi;
3934        } else {
3935            return null;
3936        }
3937    }
3938
3939    @Override
3940    public void checkPackageStartable(String packageName, int userId) {
3941        final int callingUid = Binder.getCallingUid();
3942        if (getInstantAppPackageName(callingUid) != null) {
3943            throw new SecurityException("Instant applications don't have access to this method");
3944        }
3945        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3946        synchronized (mPackages) {
3947            final PackageSetting ps = mSettings.mPackages.get(packageName);
3948            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3949                throw new SecurityException("Package " + packageName + " was not found!");
3950            }
3951
3952            if (!ps.getInstalled(userId)) {
3953                throw new SecurityException(
3954                        "Package " + packageName + " was not installed for user " + userId + "!");
3955            }
3956
3957            if (mSafeMode && !ps.isSystem()) {
3958                throw new SecurityException("Package " + packageName + " not a system app!");
3959            }
3960
3961            if (mFrozenPackages.contains(packageName)) {
3962                throw new SecurityException("Package " + packageName + " is currently frozen!");
3963            }
3964
3965            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3966                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3967            }
3968        }
3969    }
3970
3971    @Override
3972    public boolean isPackageAvailable(String packageName, int userId) {
3973        if (!sUserManager.exists(userId)) return false;
3974        final int callingUid = Binder.getCallingUid();
3975        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3976                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3977        synchronized (mPackages) {
3978            PackageParser.Package p = mPackages.get(packageName);
3979            if (p != null) {
3980                final PackageSetting ps = (PackageSetting) p.mExtras;
3981                if (filterAppAccessLPr(ps, callingUid, userId)) {
3982                    return false;
3983                }
3984                if (ps != null) {
3985                    final PackageUserState state = ps.readUserState(userId);
3986                    if (state != null) {
3987                        return PackageParser.isAvailable(state);
3988                    }
3989                }
3990            }
3991        }
3992        return false;
3993    }
3994
3995    @Override
3996    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3997        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3998                flags, Binder.getCallingUid(), userId);
3999    }
4000
4001    @Override
4002    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4003            int flags, int userId) {
4004        return getPackageInfoInternal(versionedPackage.getPackageName(),
4005                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4006    }
4007
4008    /**
4009     * Important: The provided filterCallingUid is used exclusively to filter out packages
4010     * that can be seen based on user state. It's typically the original caller uid prior
4011     * to clearing. Because it can only be provided by trusted code, it's value can be
4012     * trusted and will be used as-is; unlike userId which will be validated by this method.
4013     */
4014    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4015            int flags, int filterCallingUid, int userId) {
4016        if (!sUserManager.exists(userId)) return null;
4017        flags = updateFlagsForPackage(flags, userId, packageName);
4018        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4019                false /* requireFullPermission */, false /* checkShell */, "get package info");
4020
4021        // reader
4022        synchronized (mPackages) {
4023            // Normalize package name to handle renamed packages and static libs
4024            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4025
4026            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4027            if (matchFactoryOnly) {
4028                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4029                if (ps != null) {
4030                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4031                        return null;
4032                    }
4033                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4034                        return null;
4035                    }
4036                    return generatePackageInfo(ps, flags, userId);
4037                }
4038            }
4039
4040            PackageParser.Package p = mPackages.get(packageName);
4041            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4042                return null;
4043            }
4044            if (DEBUG_PACKAGE_INFO)
4045                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4046            if (p != null) {
4047                final PackageSetting ps = (PackageSetting) p.mExtras;
4048                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4049                    return null;
4050                }
4051                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4052                    return null;
4053                }
4054                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4055            }
4056            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4057                final PackageSetting ps = mSettings.mPackages.get(packageName);
4058                if (ps == null) return null;
4059                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4060                    return null;
4061                }
4062                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4063                    return null;
4064                }
4065                return generatePackageInfo(ps, flags, userId);
4066            }
4067        }
4068        return null;
4069    }
4070
4071    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4072        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4073            return true;
4074        }
4075        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4076            return true;
4077        }
4078        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4079            return true;
4080        }
4081        return false;
4082    }
4083
4084    private boolean isComponentVisibleToInstantApp(
4085            @Nullable ComponentName component, @ComponentType int type) {
4086        if (type == TYPE_ACTIVITY) {
4087            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4088            if (activity == null) {
4089                return false;
4090            }
4091            final boolean visibleToInstantApp =
4092                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4093            final boolean explicitlyVisibleToInstantApp =
4094                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4095            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4096        } else if (type == TYPE_RECEIVER) {
4097            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4098            if (activity == null) {
4099                return false;
4100            }
4101            final boolean visibleToInstantApp =
4102                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4103            final boolean explicitlyVisibleToInstantApp =
4104                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4105            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4106        } else if (type == TYPE_SERVICE) {
4107            final PackageParser.Service service = mServices.mServices.get(component);
4108            return service != null
4109                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4110                    : false;
4111        } else if (type == TYPE_PROVIDER) {
4112            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4113            return provider != null
4114                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4115                    : false;
4116        } else if (type == TYPE_UNKNOWN) {
4117            return isComponentVisibleToInstantApp(component);
4118        }
4119        return false;
4120    }
4121
4122    /**
4123     * Returns whether or not access to the application should be filtered.
4124     * <p>
4125     * Access may be limited based upon whether the calling or target applications
4126     * are instant applications.
4127     *
4128     * @see #canAccessInstantApps(int)
4129     */
4130    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4131            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4132        // if we're in an isolated process, get the real calling UID
4133        if (Process.isIsolated(callingUid)) {
4134            callingUid = mIsolatedOwners.get(callingUid);
4135        }
4136        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4137        final boolean callerIsInstantApp = instantAppPkgName != null;
4138        if (ps == null) {
4139            if (callerIsInstantApp) {
4140                // pretend the application exists, but, needs to be filtered
4141                return true;
4142            }
4143            return false;
4144        }
4145        // if the target and caller are the same application, don't filter
4146        if (isCallerSameApp(ps.name, callingUid)) {
4147            return false;
4148        }
4149        if (callerIsInstantApp) {
4150            // both caller and target are both instant, but, different applications, filter
4151            if (ps.getInstantApp(userId)) {
4152                return true;
4153            }
4154            // request for a specific component; if it hasn't been explicitly exposed through
4155            // property or instrumentation target, filter
4156            if (component != null) {
4157                final PackageParser.Instrumentation instrumentation =
4158                        mInstrumentation.get(component);
4159                if (instrumentation != null
4160                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4161                    return false;
4162                }
4163                return !isComponentVisibleToInstantApp(component, componentType);
4164            }
4165            // request for application; if no components have been explicitly exposed, filter
4166            return !ps.pkg.visibleToInstantApps;
4167        }
4168        if (ps.getInstantApp(userId)) {
4169            // caller can see all components of all instant applications, don't filter
4170            if (canViewInstantApps(callingUid, userId)) {
4171                return false;
4172            }
4173            // request for a specific instant application component, filter
4174            if (component != null) {
4175                return true;
4176            }
4177            // request for an instant application; if the caller hasn't been granted access, filter
4178            return !mInstantAppRegistry.isInstantAccessGranted(
4179                    userId, UserHandle.getAppId(callingUid), ps.appId);
4180        }
4181        return false;
4182    }
4183
4184    /**
4185     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4186     */
4187    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4188        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4189    }
4190
4191    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4192            int flags) {
4193        // Callers can access only the libs they depend on, otherwise they need to explicitly
4194        // ask for the shared libraries given the caller is allowed to access all static libs.
4195        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4196            // System/shell/root get to see all static libs
4197            final int appId = UserHandle.getAppId(uid);
4198            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4199                    || appId == Process.ROOT_UID) {
4200                return false;
4201            }
4202        }
4203
4204        // No package means no static lib as it is always on internal storage
4205        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4206            return false;
4207        }
4208
4209        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4210                ps.pkg.staticSharedLibVersion);
4211        if (libEntry == null) {
4212            return false;
4213        }
4214
4215        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4216        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4217        if (uidPackageNames == null) {
4218            return true;
4219        }
4220
4221        for (String uidPackageName : uidPackageNames) {
4222            if (ps.name.equals(uidPackageName)) {
4223                return false;
4224            }
4225            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4226            if (uidPs != null) {
4227                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4228                        libEntry.info.getName());
4229                if (index < 0) {
4230                    continue;
4231                }
4232                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4233                    return false;
4234                }
4235            }
4236        }
4237        return true;
4238    }
4239
4240    @Override
4241    public String[] currentToCanonicalPackageNames(String[] names) {
4242        final int callingUid = Binder.getCallingUid();
4243        if (getInstantAppPackageName(callingUid) != null) {
4244            return names;
4245        }
4246        final String[] out = new String[names.length];
4247        // reader
4248        synchronized (mPackages) {
4249            final int callingUserId = UserHandle.getUserId(callingUid);
4250            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4251            for (int i=names.length-1; i>=0; i--) {
4252                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4253                boolean translateName = false;
4254                if (ps != null && ps.realName != null) {
4255                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4256                    translateName = !targetIsInstantApp
4257                            || canViewInstantApps
4258                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4259                                    UserHandle.getAppId(callingUid), ps.appId);
4260                }
4261                out[i] = translateName ? ps.realName : names[i];
4262            }
4263        }
4264        return out;
4265    }
4266
4267    @Override
4268    public String[] canonicalToCurrentPackageNames(String[] names) {
4269        final int callingUid = Binder.getCallingUid();
4270        if (getInstantAppPackageName(callingUid) != null) {
4271            return names;
4272        }
4273        final String[] out = new String[names.length];
4274        // reader
4275        synchronized (mPackages) {
4276            final int callingUserId = UserHandle.getUserId(callingUid);
4277            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4278            for (int i=names.length-1; i>=0; i--) {
4279                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4280                boolean translateName = false;
4281                if (cur != null) {
4282                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4283                    final boolean targetIsInstantApp =
4284                            ps != null && ps.getInstantApp(callingUserId);
4285                    translateName = !targetIsInstantApp
4286                            || canViewInstantApps
4287                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4288                                    UserHandle.getAppId(callingUid), ps.appId);
4289                }
4290                out[i] = translateName ? cur : names[i];
4291            }
4292        }
4293        return out;
4294    }
4295
4296    @Override
4297    public int getPackageUid(String packageName, int flags, int userId) {
4298        if (!sUserManager.exists(userId)) return -1;
4299        final int callingUid = Binder.getCallingUid();
4300        flags = updateFlagsForPackage(flags, userId, packageName);
4301        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4302                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4303
4304        // reader
4305        synchronized (mPackages) {
4306            final PackageParser.Package p = mPackages.get(packageName);
4307            if (p != null && p.isMatch(flags)) {
4308                PackageSetting ps = (PackageSetting) p.mExtras;
4309                if (filterAppAccessLPr(ps, callingUid, userId)) {
4310                    return -1;
4311                }
4312                return UserHandle.getUid(userId, p.applicationInfo.uid);
4313            }
4314            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4315                final PackageSetting ps = mSettings.mPackages.get(packageName);
4316                if (ps != null && ps.isMatch(flags)
4317                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4318                    return UserHandle.getUid(userId, ps.appId);
4319                }
4320            }
4321        }
4322
4323        return -1;
4324    }
4325
4326    @Override
4327    public int[] getPackageGids(String packageName, int flags, int userId) {
4328        if (!sUserManager.exists(userId)) return null;
4329        final int callingUid = Binder.getCallingUid();
4330        flags = updateFlagsForPackage(flags, userId, packageName);
4331        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4332                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4333
4334        // reader
4335        synchronized (mPackages) {
4336            final PackageParser.Package p = mPackages.get(packageName);
4337            if (p != null && p.isMatch(flags)) {
4338                PackageSetting ps = (PackageSetting) p.mExtras;
4339                if (filterAppAccessLPr(ps, callingUid, userId)) {
4340                    return null;
4341                }
4342                // TODO: Shouldn't this be checking for package installed state for userId and
4343                // return null?
4344                return ps.getPermissionsState().computeGids(userId);
4345            }
4346            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4347                final PackageSetting ps = mSettings.mPackages.get(packageName);
4348                if (ps != null && ps.isMatch(flags)
4349                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4350                    return ps.getPermissionsState().computeGids(userId);
4351                }
4352            }
4353        }
4354
4355        return null;
4356    }
4357
4358    @Override
4359    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4360        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4361    }
4362
4363    @Override
4364    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4365            int flags) {
4366        final List<PermissionInfo> permissionList =
4367                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4368        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4369    }
4370
4371    @Override
4372    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4373        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4374    }
4375
4376    @Override
4377    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4378        final List<PermissionGroupInfo> permissionList =
4379                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4380        return (permissionList == null)
4381                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4382    }
4383
4384    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4385            int filterCallingUid, int userId) {
4386        if (!sUserManager.exists(userId)) return null;
4387        PackageSetting ps = mSettings.mPackages.get(packageName);
4388        if (ps != null) {
4389            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4390                return null;
4391            }
4392            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4393                return null;
4394            }
4395            if (ps.pkg == null) {
4396                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4397                if (pInfo != null) {
4398                    return pInfo.applicationInfo;
4399                }
4400                return null;
4401            }
4402            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4403                    ps.readUserState(userId), userId);
4404            if (ai != null) {
4405                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4406            }
4407            return ai;
4408        }
4409        return null;
4410    }
4411
4412    @Override
4413    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4414        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4415    }
4416
4417    /**
4418     * Important: The provided filterCallingUid is used exclusively to filter out applications
4419     * that can be seen based on user state. It's typically the original caller uid prior
4420     * to clearing. Because it can only be provided by trusted code, it's value can be
4421     * trusted and will be used as-is; unlike userId which will be validated by this method.
4422     */
4423    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4424            int filterCallingUid, int userId) {
4425        if (!sUserManager.exists(userId)) return null;
4426        flags = updateFlagsForApplication(flags, userId, packageName);
4427        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4428                false /* requireFullPermission */, false /* checkShell */, "get application info");
4429
4430        // writer
4431        synchronized (mPackages) {
4432            // Normalize package name to handle renamed packages and static libs
4433            packageName = resolveInternalPackageNameLPr(packageName,
4434                    PackageManager.VERSION_CODE_HIGHEST);
4435
4436            PackageParser.Package p = mPackages.get(packageName);
4437            if (DEBUG_PACKAGE_INFO) Log.v(
4438                    TAG, "getApplicationInfo " + packageName
4439                    + ": " + p);
4440            if (p != null) {
4441                PackageSetting ps = mSettings.mPackages.get(packageName);
4442                if (ps == null) return null;
4443                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4444                    return null;
4445                }
4446                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4447                    return null;
4448                }
4449                // Note: isEnabledLP() does not apply here - always return info
4450                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4451                        p, flags, ps.readUserState(userId), userId);
4452                if (ai != null) {
4453                    ai.packageName = resolveExternalPackageNameLPr(p);
4454                }
4455                return ai;
4456            }
4457            if ("android".equals(packageName)||"system".equals(packageName)) {
4458                return mAndroidApplication;
4459            }
4460            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4461                // Already generates the external package name
4462                return generateApplicationInfoFromSettingsLPw(packageName,
4463                        flags, filterCallingUid, userId);
4464            }
4465        }
4466        return null;
4467    }
4468
4469    private String normalizePackageNameLPr(String packageName) {
4470        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4471        return normalizedPackageName != null ? normalizedPackageName : packageName;
4472    }
4473
4474    @Override
4475    public void deletePreloadsFileCache() {
4476        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4477            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4478        }
4479        File dir = Environment.getDataPreloadsFileCacheDirectory();
4480        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4481        FileUtils.deleteContents(dir);
4482    }
4483
4484    @Override
4485    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4486            final int storageFlags, final IPackageDataObserver observer) {
4487        mContext.enforceCallingOrSelfPermission(
4488                android.Manifest.permission.CLEAR_APP_CACHE, null);
4489        mHandler.post(() -> {
4490            boolean success = false;
4491            try {
4492                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4493                success = true;
4494            } catch (IOException e) {
4495                Slog.w(TAG, e);
4496            }
4497            if (observer != null) {
4498                try {
4499                    observer.onRemoveCompleted(null, success);
4500                } catch (RemoteException e) {
4501                    Slog.w(TAG, e);
4502                }
4503            }
4504        });
4505    }
4506
4507    @Override
4508    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4509            final int storageFlags, final IntentSender pi) {
4510        mContext.enforceCallingOrSelfPermission(
4511                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4512        mHandler.post(() -> {
4513            boolean success = false;
4514            try {
4515                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4516                success = true;
4517            } catch (IOException e) {
4518                Slog.w(TAG, e);
4519            }
4520            if (pi != null) {
4521                try {
4522                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4523                } catch (SendIntentException e) {
4524                    Slog.w(TAG, e);
4525                }
4526            }
4527        });
4528    }
4529
4530    /**
4531     * Blocking call to clear various types of cached data across the system
4532     * until the requested bytes are available.
4533     */
4534    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4535        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4536        final File file = storage.findPathForUuid(volumeUuid);
4537        if (file.getUsableSpace() >= bytes) return;
4538
4539        if (ENABLE_FREE_CACHE_V2) {
4540            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4541                    volumeUuid);
4542            final boolean aggressive = (storageFlags
4543                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4544            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4545
4546            // 1. Pre-flight to determine if we have any chance to succeed
4547            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4548            if (internalVolume && (aggressive || SystemProperties
4549                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4550                deletePreloadsFileCache();
4551                if (file.getUsableSpace() >= bytes) return;
4552            }
4553
4554            // 3. Consider parsed APK data (aggressive only)
4555            if (internalVolume && aggressive) {
4556                FileUtils.deleteContents(mCacheDir);
4557                if (file.getUsableSpace() >= bytes) return;
4558            }
4559
4560            // 4. Consider cached app data (above quotas)
4561            try {
4562                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4563                        Installer.FLAG_FREE_CACHE_V2);
4564            } catch (InstallerException ignored) {
4565            }
4566            if (file.getUsableSpace() >= bytes) return;
4567
4568            // 5. Consider shared libraries with refcount=0 and age>min cache period
4569            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4570                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4571                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4572                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4573                return;
4574            }
4575
4576            // 6. Consider dexopt output (aggressive only)
4577            // TODO: Implement
4578
4579            // 7. Consider installed instant apps unused longer than min cache period
4580            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4581                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4582                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4583                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4584                return;
4585            }
4586
4587            // 8. Consider cached app data (below quotas)
4588            try {
4589                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4590                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4591            } catch (InstallerException ignored) {
4592            }
4593            if (file.getUsableSpace() >= bytes) return;
4594
4595            // 9. Consider DropBox entries
4596            // TODO: Implement
4597
4598            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4599            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4600                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4601                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4602                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4603                return;
4604            }
4605        } else {
4606            try {
4607                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4608            } catch (InstallerException ignored) {
4609            }
4610            if (file.getUsableSpace() >= bytes) return;
4611        }
4612
4613        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4614    }
4615
4616    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4617            throws IOException {
4618        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4619        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4620
4621        List<VersionedPackage> packagesToDelete = null;
4622        final long now = System.currentTimeMillis();
4623
4624        synchronized (mPackages) {
4625            final int[] allUsers = sUserManager.getUserIds();
4626            final int libCount = mSharedLibraries.size();
4627            for (int i = 0; i < libCount; i++) {
4628                final LongSparseArray<SharedLibraryEntry> versionedLib
4629                        = mSharedLibraries.valueAt(i);
4630                if (versionedLib == null) {
4631                    continue;
4632                }
4633                final int versionCount = versionedLib.size();
4634                for (int j = 0; j < versionCount; j++) {
4635                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4636                    // Skip packages that are not static shared libs.
4637                    if (!libInfo.isStatic()) {
4638                        break;
4639                    }
4640                    // Important: We skip static shared libs used for some user since
4641                    // in such a case we need to keep the APK on the device. The check for
4642                    // a lib being used for any user is performed by the uninstall call.
4643                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4644                    // Resolve the package name - we use synthetic package names internally
4645                    final String internalPackageName = resolveInternalPackageNameLPr(
4646                            declaringPackage.getPackageName(),
4647                            declaringPackage.getLongVersionCode());
4648                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4649                    // Skip unused static shared libs cached less than the min period
4650                    // to prevent pruning a lib needed by a subsequently installed package.
4651                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4652                        continue;
4653                    }
4654                    if (packagesToDelete == null) {
4655                        packagesToDelete = new ArrayList<>();
4656                    }
4657                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4658                            declaringPackage.getLongVersionCode()));
4659                }
4660            }
4661        }
4662
4663        if (packagesToDelete != null) {
4664            final int packageCount = packagesToDelete.size();
4665            for (int i = 0; i < packageCount; i++) {
4666                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4667                // Delete the package synchronously (will fail of the lib used for any user).
4668                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4669                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4670                                == PackageManager.DELETE_SUCCEEDED) {
4671                    if (volume.getUsableSpace() >= neededSpace) {
4672                        return true;
4673                    }
4674                }
4675            }
4676        }
4677
4678        return false;
4679    }
4680
4681    /**
4682     * Update given flags based on encryption status of current user.
4683     */
4684    private int updateFlags(int flags, int userId) {
4685        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4686                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4687            // Caller expressed an explicit opinion about what encryption
4688            // aware/unaware components they want to see, so fall through and
4689            // give them what they want
4690        } else {
4691            // Caller expressed no opinion, so match based on user state
4692            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4693                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4694            } else {
4695                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4696            }
4697        }
4698        return flags;
4699    }
4700
4701    private UserManagerInternal getUserManagerInternal() {
4702        if (mUserManagerInternal == null) {
4703            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4704        }
4705        return mUserManagerInternal;
4706    }
4707
4708    private ActivityManagerInternal getActivityManagerInternal() {
4709        if (mActivityManagerInternal == null) {
4710            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4711        }
4712        return mActivityManagerInternal;
4713    }
4714
4715
4716    private DeviceIdleController.LocalService getDeviceIdleController() {
4717        if (mDeviceIdleController == null) {
4718            mDeviceIdleController =
4719                    LocalServices.getService(DeviceIdleController.LocalService.class);
4720        }
4721        return mDeviceIdleController;
4722    }
4723
4724    /**
4725     * Update given flags when being used to request {@link PackageInfo}.
4726     */
4727    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4728        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4729        boolean triaged = true;
4730        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4731                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4732            // Caller is asking for component details, so they'd better be
4733            // asking for specific encryption matching behavior, or be triaged
4734            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4735                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4736                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4737                triaged = false;
4738            }
4739        }
4740        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4741                | PackageManager.MATCH_SYSTEM_ONLY
4742                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4743            triaged = false;
4744        }
4745        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4746            mPermissionManager.enforceCrossUserPermission(
4747                    Binder.getCallingUid(), userId, false, false,
4748                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4749                    + Debug.getCallers(5));
4750        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4751                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4752            // If the caller wants all packages and has a restricted profile associated with it,
4753            // then match all users. This is to make sure that launchers that need to access work
4754            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4755            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4756            flags |= PackageManager.MATCH_ANY_USER;
4757        }
4758        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4759            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4760                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4761        }
4762        return updateFlags(flags, userId);
4763    }
4764
4765    /**
4766     * Update given flags when being used to request {@link ApplicationInfo}.
4767     */
4768    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4769        return updateFlagsForPackage(flags, userId, cookie);
4770    }
4771
4772    /**
4773     * Update given flags when being used to request {@link ComponentInfo}.
4774     */
4775    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4776        if (cookie instanceof Intent) {
4777            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4778                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4779            }
4780        }
4781
4782        boolean triaged = true;
4783        // Caller is asking for component details, so they'd better be
4784        // asking for specific encryption matching behavior, or be triaged
4785        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4786                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4787                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4788            triaged = false;
4789        }
4790        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4791            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4792                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4793        }
4794
4795        return updateFlags(flags, userId);
4796    }
4797
4798    /**
4799     * Update given intent when being used to request {@link ResolveInfo}.
4800     */
4801    private Intent updateIntentForResolve(Intent intent) {
4802        if (intent.getSelector() != null) {
4803            intent = intent.getSelector();
4804        }
4805        if (DEBUG_PREFERRED) {
4806            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4807        }
4808        return intent;
4809    }
4810
4811    /**
4812     * Update given flags when being used to request {@link ResolveInfo}.
4813     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4814     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4815     * flag set. However, this flag is only honoured in three circumstances:
4816     * <ul>
4817     * <li>when called from a system process</li>
4818     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4819     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4820     * action and a {@code android.intent.category.BROWSABLE} category</li>
4821     * </ul>
4822     */
4823    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4824        return updateFlagsForResolve(flags, userId, intent, callingUid,
4825                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4826    }
4827    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4828            boolean wantInstantApps) {
4829        return updateFlagsForResolve(flags, userId, intent, callingUid,
4830                wantInstantApps, false /*onlyExposedExplicitly*/);
4831    }
4832    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4833            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4834        // Safe mode means we shouldn't match any third-party components
4835        if (mSafeMode) {
4836            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4837        }
4838        if (getInstantAppPackageName(callingUid) != null) {
4839            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4840            if (onlyExposedExplicitly) {
4841                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4842            }
4843            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4844            flags |= PackageManager.MATCH_INSTANT;
4845        } else {
4846            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4847            final boolean allowMatchInstant = wantInstantApps
4848                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4849            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4850                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4851            if (!allowMatchInstant) {
4852                flags &= ~PackageManager.MATCH_INSTANT;
4853            }
4854        }
4855        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4856    }
4857
4858    @Override
4859    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4860        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4861    }
4862
4863    /**
4864     * Important: The provided filterCallingUid is used exclusively to filter out activities
4865     * that can be seen based on user state. It's typically the original caller uid prior
4866     * to clearing. Because it can only be provided by trusted code, it's value can be
4867     * trusted and will be used as-is; unlike userId which will be validated by this method.
4868     */
4869    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4870            int filterCallingUid, int userId) {
4871        if (!sUserManager.exists(userId)) return null;
4872        flags = updateFlagsForComponent(flags, userId, component);
4873
4874        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4875            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4876                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4877        }
4878
4879        synchronized (mPackages) {
4880            PackageParser.Activity a = mActivities.mActivities.get(component);
4881
4882            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4883            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4884                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4885                if (ps == null) return null;
4886                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4887                    return null;
4888                }
4889                return PackageParser.generateActivityInfo(
4890                        a, flags, ps.readUserState(userId), userId);
4891            }
4892            if (mResolveComponentName.equals(component)) {
4893                return PackageParser.generateActivityInfo(
4894                        mResolveActivity, flags, new PackageUserState(), userId);
4895            }
4896        }
4897        return null;
4898    }
4899
4900    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4901        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4902            return false;
4903        }
4904        final long token = Binder.clearCallingIdentity();
4905        try {
4906            final int callingUserId = UserHandle.getUserId(callingUid);
4907            if (ActivityManager.getCurrentUser() != callingUserId) {
4908                return false;
4909            }
4910            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4911        } finally {
4912            Binder.restoreCallingIdentity(token);
4913        }
4914    }
4915
4916    @Override
4917    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4918            String resolvedType) {
4919        synchronized (mPackages) {
4920            if (component.equals(mResolveComponentName)) {
4921                // The resolver supports EVERYTHING!
4922                return true;
4923            }
4924            final int callingUid = Binder.getCallingUid();
4925            final int callingUserId = UserHandle.getUserId(callingUid);
4926            PackageParser.Activity a = mActivities.mActivities.get(component);
4927            if (a == null) {
4928                return false;
4929            }
4930            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4931            if (ps == null) {
4932                return false;
4933            }
4934            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4935                return false;
4936            }
4937            for (int i=0; i<a.intents.size(); i++) {
4938                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4939                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4940                    return true;
4941                }
4942            }
4943            return false;
4944        }
4945    }
4946
4947    @Override
4948    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4949        if (!sUserManager.exists(userId)) return null;
4950        final int callingUid = Binder.getCallingUid();
4951        flags = updateFlagsForComponent(flags, userId, component);
4952        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4953                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4954        synchronized (mPackages) {
4955            PackageParser.Activity a = mReceivers.mActivities.get(component);
4956            if (DEBUG_PACKAGE_INFO) Log.v(
4957                TAG, "getReceiverInfo " + component + ": " + a);
4958            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4959                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4960                if (ps == null) return null;
4961                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4962                    return null;
4963                }
4964                return PackageParser.generateActivityInfo(
4965                        a, flags, ps.readUserState(userId), userId);
4966            }
4967        }
4968        return null;
4969    }
4970
4971    @Override
4972    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4973            int flags, int userId) {
4974        if (!sUserManager.exists(userId)) return null;
4975        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4976        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4977            return null;
4978        }
4979
4980        flags = updateFlagsForPackage(flags, userId, null);
4981
4982        final boolean canSeeStaticLibraries =
4983                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4984                        == PERMISSION_GRANTED
4985                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4986                        == PERMISSION_GRANTED
4987                || canRequestPackageInstallsInternal(packageName,
4988                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4989                        false  /* throwIfPermNotDeclared*/)
4990                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4991                        == PERMISSION_GRANTED;
4992
4993        synchronized (mPackages) {
4994            List<SharedLibraryInfo> result = null;
4995
4996            final int libCount = mSharedLibraries.size();
4997            for (int i = 0; i < libCount; i++) {
4998                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4999                if (versionedLib == null) {
5000                    continue;
5001                }
5002
5003                final int versionCount = versionedLib.size();
5004                for (int j = 0; j < versionCount; j++) {
5005                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5006                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5007                        break;
5008                    }
5009                    final long identity = Binder.clearCallingIdentity();
5010                    try {
5011                        PackageInfo packageInfo = getPackageInfoVersioned(
5012                                libInfo.getDeclaringPackage(), flags
5013                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5014                        if (packageInfo == null) {
5015                            continue;
5016                        }
5017                    } finally {
5018                        Binder.restoreCallingIdentity(identity);
5019                    }
5020
5021                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5022                            libInfo.getLongVersion(), libInfo.getType(),
5023                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5024                            flags, userId));
5025
5026                    if (result == null) {
5027                        result = new ArrayList<>();
5028                    }
5029                    result.add(resLibInfo);
5030                }
5031            }
5032
5033            return result != null ? new ParceledListSlice<>(result) : null;
5034        }
5035    }
5036
5037    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5038            SharedLibraryInfo libInfo, int flags, int userId) {
5039        List<VersionedPackage> versionedPackages = null;
5040        final int packageCount = mSettings.mPackages.size();
5041        for (int i = 0; i < packageCount; i++) {
5042            PackageSetting ps = mSettings.mPackages.valueAt(i);
5043
5044            if (ps == null) {
5045                continue;
5046            }
5047
5048            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5049                continue;
5050            }
5051
5052            final String libName = libInfo.getName();
5053            if (libInfo.isStatic()) {
5054                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5055                if (libIdx < 0) {
5056                    continue;
5057                }
5058                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5059                    continue;
5060                }
5061                if (versionedPackages == null) {
5062                    versionedPackages = new ArrayList<>();
5063                }
5064                // If the dependent is a static shared lib, use the public package name
5065                String dependentPackageName = ps.name;
5066                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5067                    dependentPackageName = ps.pkg.manifestPackageName;
5068                }
5069                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5070            } else if (ps.pkg != null) {
5071                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5072                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5073                    if (versionedPackages == null) {
5074                        versionedPackages = new ArrayList<>();
5075                    }
5076                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5077                }
5078            }
5079        }
5080
5081        return versionedPackages;
5082    }
5083
5084    @Override
5085    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5086        if (!sUserManager.exists(userId)) return null;
5087        final int callingUid = Binder.getCallingUid();
5088        flags = updateFlagsForComponent(flags, userId, component);
5089        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5090                false /* requireFullPermission */, false /* checkShell */, "get service info");
5091        synchronized (mPackages) {
5092            PackageParser.Service s = mServices.mServices.get(component);
5093            if (DEBUG_PACKAGE_INFO) Log.v(
5094                TAG, "getServiceInfo " + component + ": " + s);
5095            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5096                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5097                if (ps == null) return null;
5098                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5099                    return null;
5100                }
5101                return PackageParser.generateServiceInfo(
5102                        s, flags, ps.readUserState(userId), userId);
5103            }
5104        }
5105        return null;
5106    }
5107
5108    @Override
5109    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5110        if (!sUserManager.exists(userId)) return null;
5111        final int callingUid = Binder.getCallingUid();
5112        flags = updateFlagsForComponent(flags, userId, component);
5113        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5114                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5115        synchronized (mPackages) {
5116            PackageParser.Provider p = mProviders.mProviders.get(component);
5117            if (DEBUG_PACKAGE_INFO) Log.v(
5118                TAG, "getProviderInfo " + component + ": " + p);
5119            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5120                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5121                if (ps == null) return null;
5122                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5123                    return null;
5124                }
5125                return PackageParser.generateProviderInfo(
5126                        p, flags, ps.readUserState(userId), userId);
5127            }
5128        }
5129        return null;
5130    }
5131
5132    @Override
5133    public String[] getSystemSharedLibraryNames() {
5134        // allow instant applications
5135        synchronized (mPackages) {
5136            Set<String> libs = null;
5137            final int libCount = mSharedLibraries.size();
5138            for (int i = 0; i < libCount; i++) {
5139                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5140                if (versionedLib == null) {
5141                    continue;
5142                }
5143                final int versionCount = versionedLib.size();
5144                for (int j = 0; j < versionCount; j++) {
5145                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5146                    if (!libEntry.info.isStatic()) {
5147                        if (libs == null) {
5148                            libs = new ArraySet<>();
5149                        }
5150                        libs.add(libEntry.info.getName());
5151                        break;
5152                    }
5153                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5154                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5155                            UserHandle.getUserId(Binder.getCallingUid()),
5156                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5157                        if (libs == null) {
5158                            libs = new ArraySet<>();
5159                        }
5160                        libs.add(libEntry.info.getName());
5161                        break;
5162                    }
5163                }
5164            }
5165
5166            if (libs != null) {
5167                String[] libsArray = new String[libs.size()];
5168                libs.toArray(libsArray);
5169                return libsArray;
5170            }
5171
5172            return null;
5173        }
5174    }
5175
5176    @Override
5177    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5178        // allow instant applications
5179        synchronized (mPackages) {
5180            return mServicesSystemSharedLibraryPackageName;
5181        }
5182    }
5183
5184    @Override
5185    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5186        // allow instant applications
5187        synchronized (mPackages) {
5188            return mSharedSystemSharedLibraryPackageName;
5189        }
5190    }
5191
5192    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5193        for (int i = userList.length - 1; i >= 0; --i) {
5194            final int userId = userList[i];
5195            // don't add instant app to the list of updates
5196            if (pkgSetting.getInstantApp(userId)) {
5197                continue;
5198            }
5199            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5200            if (changedPackages == null) {
5201                changedPackages = new SparseArray<>();
5202                mChangedPackages.put(userId, changedPackages);
5203            }
5204            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5205            if (sequenceNumbers == null) {
5206                sequenceNumbers = new HashMap<>();
5207                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5208            }
5209            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5210            if (sequenceNumber != null) {
5211                changedPackages.remove(sequenceNumber);
5212            }
5213            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5214            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5215        }
5216        mChangedPackagesSequenceNumber++;
5217    }
5218
5219    @Override
5220    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5221        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5222            return null;
5223        }
5224        synchronized (mPackages) {
5225            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5226                return null;
5227            }
5228            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5229            if (changedPackages == null) {
5230                return null;
5231            }
5232            final List<String> packageNames =
5233                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5234            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5235                final String packageName = changedPackages.get(i);
5236                if (packageName != null) {
5237                    packageNames.add(packageName);
5238                }
5239            }
5240            return packageNames.isEmpty()
5241                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5242        }
5243    }
5244
5245    @Override
5246    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5247        // allow instant applications
5248        ArrayList<FeatureInfo> res;
5249        synchronized (mAvailableFeatures) {
5250            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5251            res.addAll(mAvailableFeatures.values());
5252        }
5253        final FeatureInfo fi = new FeatureInfo();
5254        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5255                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5256        res.add(fi);
5257
5258        return new ParceledListSlice<>(res);
5259    }
5260
5261    @Override
5262    public boolean hasSystemFeature(String name, int version) {
5263        // allow instant applications
5264        synchronized (mAvailableFeatures) {
5265            final FeatureInfo feat = mAvailableFeatures.get(name);
5266            if (feat == null) {
5267                return false;
5268            } else {
5269                return feat.version >= version;
5270            }
5271        }
5272    }
5273
5274    @Override
5275    public int checkPermission(String permName, String pkgName, int userId) {
5276        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5277    }
5278
5279    @Override
5280    public int checkUidPermission(String permName, int uid) {
5281        synchronized (mPackages) {
5282            final String[] packageNames = getPackagesForUid(uid);
5283            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5284                    ? mPackages.get(packageNames[0])
5285                    : null;
5286            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5287        }
5288    }
5289
5290    @Override
5291    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5292        if (UserHandle.getCallingUserId() != userId) {
5293            mContext.enforceCallingPermission(
5294                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5295                    "isPermissionRevokedByPolicy for user " + userId);
5296        }
5297
5298        if (checkPermission(permission, packageName, userId)
5299                == PackageManager.PERMISSION_GRANTED) {
5300            return false;
5301        }
5302
5303        final int callingUid = Binder.getCallingUid();
5304        if (getInstantAppPackageName(callingUid) != null) {
5305            if (!isCallerSameApp(packageName, callingUid)) {
5306                return false;
5307            }
5308        } else {
5309            if (isInstantApp(packageName, userId)) {
5310                return false;
5311            }
5312        }
5313
5314        final long identity = Binder.clearCallingIdentity();
5315        try {
5316            final int flags = getPermissionFlags(permission, packageName, userId);
5317            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5318        } finally {
5319            Binder.restoreCallingIdentity(identity);
5320        }
5321    }
5322
5323    @Override
5324    public String getPermissionControllerPackageName() {
5325        synchronized (mPackages) {
5326            return mRequiredInstallerPackage;
5327        }
5328    }
5329
5330    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5331        return mPermissionManager.addDynamicPermission(
5332                info, async, getCallingUid(), new PermissionCallback() {
5333                    @Override
5334                    public void onPermissionChanged() {
5335                        if (!async) {
5336                            mSettings.writeLPr();
5337                        } else {
5338                            scheduleWriteSettingsLocked();
5339                        }
5340                    }
5341                });
5342    }
5343
5344    @Override
5345    public boolean addPermission(PermissionInfo info) {
5346        synchronized (mPackages) {
5347            return addDynamicPermission(info, false);
5348        }
5349    }
5350
5351    @Override
5352    public boolean addPermissionAsync(PermissionInfo info) {
5353        synchronized (mPackages) {
5354            return addDynamicPermission(info, true);
5355        }
5356    }
5357
5358    @Override
5359    public void removePermission(String permName) {
5360        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5361    }
5362
5363    @Override
5364    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5365        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5366                getCallingUid(), userId, mPermissionCallback);
5367    }
5368
5369    @Override
5370    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5371        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5372                getCallingUid(), userId, mPermissionCallback);
5373    }
5374
5375    @Override
5376    public void resetRuntimePermissions() {
5377        mContext.enforceCallingOrSelfPermission(
5378                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5379                "revokeRuntimePermission");
5380
5381        int callingUid = Binder.getCallingUid();
5382        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5383            mContext.enforceCallingOrSelfPermission(
5384                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5385                    "resetRuntimePermissions");
5386        }
5387
5388        synchronized (mPackages) {
5389            mPermissionManager.updateAllPermissions(
5390                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5391                    mPermissionCallback);
5392            for (int userId : UserManagerService.getInstance().getUserIds()) {
5393                final int packageCount = mPackages.size();
5394                for (int i = 0; i < packageCount; i++) {
5395                    PackageParser.Package pkg = mPackages.valueAt(i);
5396                    if (!(pkg.mExtras instanceof PackageSetting)) {
5397                        continue;
5398                    }
5399                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5400                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5401                }
5402            }
5403        }
5404    }
5405
5406    @Override
5407    public int getPermissionFlags(String permName, String packageName, int userId) {
5408        return mPermissionManager.getPermissionFlags(
5409                permName, packageName, getCallingUid(), userId);
5410    }
5411
5412    @Override
5413    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5414            int flagValues, int userId) {
5415        mPermissionManager.updatePermissionFlags(
5416                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5417                mPermissionCallback);
5418    }
5419
5420    /**
5421     * Update the permission flags for all packages and runtime permissions of a user in order
5422     * to allow device or profile owner to remove POLICY_FIXED.
5423     */
5424    @Override
5425    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5426        synchronized (mPackages) {
5427            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5428                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5429                    mPermissionCallback);
5430            if (changed) {
5431                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5432            }
5433        }
5434    }
5435
5436    @Override
5437    public boolean shouldShowRequestPermissionRationale(String permissionName,
5438            String packageName, int userId) {
5439        if (UserHandle.getCallingUserId() != userId) {
5440            mContext.enforceCallingPermission(
5441                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5442                    "canShowRequestPermissionRationale for user " + userId);
5443        }
5444
5445        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5446        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5447            return false;
5448        }
5449
5450        if (checkPermission(permissionName, packageName, userId)
5451                == PackageManager.PERMISSION_GRANTED) {
5452            return false;
5453        }
5454
5455        final int flags;
5456
5457        final long identity = Binder.clearCallingIdentity();
5458        try {
5459            flags = getPermissionFlags(permissionName,
5460                    packageName, userId);
5461        } finally {
5462            Binder.restoreCallingIdentity(identity);
5463        }
5464
5465        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5466                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5467                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5468
5469        if ((flags & fixedFlags) != 0) {
5470            return false;
5471        }
5472
5473        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5474    }
5475
5476    @Override
5477    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5478        mContext.enforceCallingOrSelfPermission(
5479                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5480                "addOnPermissionsChangeListener");
5481
5482        synchronized (mPackages) {
5483            mOnPermissionChangeListeners.addListenerLocked(listener);
5484        }
5485    }
5486
5487    @Override
5488    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5489        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5490            throw new SecurityException("Instant applications don't have access to this method");
5491        }
5492        synchronized (mPackages) {
5493            mOnPermissionChangeListeners.removeListenerLocked(listener);
5494        }
5495    }
5496
5497    @Override
5498    public boolean isProtectedBroadcast(String actionName) {
5499        // allow instant applications
5500        synchronized (mProtectedBroadcasts) {
5501            if (mProtectedBroadcasts.contains(actionName)) {
5502                return true;
5503            } else if (actionName != null) {
5504                // TODO: remove these terrible hacks
5505                if (actionName.startsWith("android.net.netmon.lingerExpired")
5506                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5507                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5508                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5509                    return true;
5510                }
5511            }
5512        }
5513        return false;
5514    }
5515
5516    @Override
5517    public int checkSignatures(String pkg1, String pkg2) {
5518        synchronized (mPackages) {
5519            final PackageParser.Package p1 = mPackages.get(pkg1);
5520            final PackageParser.Package p2 = mPackages.get(pkg2);
5521            if (p1 == null || p1.mExtras == null
5522                    || p2 == null || p2.mExtras == null) {
5523                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5524            }
5525            final int callingUid = Binder.getCallingUid();
5526            final int callingUserId = UserHandle.getUserId(callingUid);
5527            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5528            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5529            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5530                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5531                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5532            }
5533            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5534        }
5535    }
5536
5537    @Override
5538    public int checkUidSignatures(int uid1, int uid2) {
5539        final int callingUid = Binder.getCallingUid();
5540        final int callingUserId = UserHandle.getUserId(callingUid);
5541        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5542        // Map to base uids.
5543        uid1 = UserHandle.getAppId(uid1);
5544        uid2 = UserHandle.getAppId(uid2);
5545        // reader
5546        synchronized (mPackages) {
5547            Signature[] s1;
5548            Signature[] s2;
5549            Object obj = mSettings.getUserIdLPr(uid1);
5550            if (obj != null) {
5551                if (obj instanceof SharedUserSetting) {
5552                    if (isCallerInstantApp) {
5553                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5554                    }
5555                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5556                } else if (obj instanceof PackageSetting) {
5557                    final PackageSetting ps = (PackageSetting) obj;
5558                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5559                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5560                    }
5561                    s1 = ps.signatures.mSigningDetails.signatures;
5562                } else {
5563                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5564                }
5565            } else {
5566                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5567            }
5568            obj = mSettings.getUserIdLPr(uid2);
5569            if (obj != null) {
5570                if (obj instanceof SharedUserSetting) {
5571                    if (isCallerInstantApp) {
5572                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5573                    }
5574                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5575                } else if (obj instanceof PackageSetting) {
5576                    final PackageSetting ps = (PackageSetting) obj;
5577                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5578                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5579                    }
5580                    s2 = ps.signatures.mSigningDetails.signatures;
5581                } else {
5582                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5583                }
5584            } else {
5585                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5586            }
5587            return compareSignatures(s1, s2);
5588        }
5589    }
5590
5591    @Override
5592    public boolean hasSigningCertificate(
5593            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5594
5595        synchronized (mPackages) {
5596            final PackageParser.Package p = mPackages.get(packageName);
5597            if (p == null || p.mExtras == null) {
5598                return false;
5599            }
5600            final int callingUid = Binder.getCallingUid();
5601            final int callingUserId = UserHandle.getUserId(callingUid);
5602            final PackageSetting ps = (PackageSetting) p.mExtras;
5603            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5604                return false;
5605            }
5606            switch (type) {
5607                case CERT_INPUT_RAW_X509:
5608                    return p.mSigningDetails.hasCertificate(certificate);
5609                case CERT_INPUT_SHA256:
5610                    return p.mSigningDetails.hasSha256Certificate(certificate);
5611                default:
5612                    return false;
5613            }
5614        }
5615    }
5616
5617    @Override
5618    public boolean hasUidSigningCertificate(
5619            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5620        final int callingUid = Binder.getCallingUid();
5621        final int callingUserId = UserHandle.getUserId(callingUid);
5622        // Map to base uids.
5623        uid = UserHandle.getAppId(uid);
5624        // reader
5625        synchronized (mPackages) {
5626            final PackageParser.SigningDetails signingDetails;
5627            final Object obj = mSettings.getUserIdLPr(uid);
5628            if (obj != null) {
5629                if (obj instanceof SharedUserSetting) {
5630                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5631                    if (isCallerInstantApp) {
5632                        return false;
5633                    }
5634                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5635                } else if (obj instanceof PackageSetting) {
5636                    final PackageSetting ps = (PackageSetting) obj;
5637                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5638                        return false;
5639                    }
5640                    signingDetails = ps.signatures.mSigningDetails;
5641                } else {
5642                    return false;
5643                }
5644            } else {
5645                return false;
5646            }
5647            switch (type) {
5648                case CERT_INPUT_RAW_X509:
5649                    return signingDetails.hasCertificate(certificate);
5650                case CERT_INPUT_SHA256:
5651                    return signingDetails.hasSha256Certificate(certificate);
5652                default:
5653                    return false;
5654            }
5655        }
5656    }
5657
5658    /**
5659     * This method should typically only be used when granting or revoking
5660     * permissions, since the app may immediately restart after this call.
5661     * <p>
5662     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5663     * guard your work against the app being relaunched.
5664     */
5665    private void killUid(int appId, int userId, String reason) {
5666        final long identity = Binder.clearCallingIdentity();
5667        try {
5668            IActivityManager am = ActivityManager.getService();
5669            if (am != null) {
5670                try {
5671                    am.killUid(appId, userId, reason);
5672                } catch (RemoteException e) {
5673                    /* ignore - same process */
5674                }
5675            }
5676        } finally {
5677            Binder.restoreCallingIdentity(identity);
5678        }
5679    }
5680
5681    /**
5682     * If the database version for this type of package (internal storage or
5683     * external storage) is less than the version where package signatures
5684     * were updated, return true.
5685     */
5686    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5687        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5688        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5689    }
5690
5691    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5692        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5693        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5694    }
5695
5696    @Override
5697    public List<String> getAllPackages() {
5698        final int callingUid = Binder.getCallingUid();
5699        final int callingUserId = UserHandle.getUserId(callingUid);
5700        synchronized (mPackages) {
5701            if (canViewInstantApps(callingUid, callingUserId)) {
5702                return new ArrayList<String>(mPackages.keySet());
5703            }
5704            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5705            final List<String> result = new ArrayList<>();
5706            if (instantAppPkgName != null) {
5707                // caller is an instant application; filter unexposed applications
5708                for (PackageParser.Package pkg : mPackages.values()) {
5709                    if (!pkg.visibleToInstantApps) {
5710                        continue;
5711                    }
5712                    result.add(pkg.packageName);
5713                }
5714            } else {
5715                // caller is a normal application; filter instant applications
5716                for (PackageParser.Package pkg : mPackages.values()) {
5717                    final PackageSetting ps =
5718                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5719                    if (ps != null
5720                            && ps.getInstantApp(callingUserId)
5721                            && !mInstantAppRegistry.isInstantAccessGranted(
5722                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5723                        continue;
5724                    }
5725                    result.add(pkg.packageName);
5726                }
5727            }
5728            return result;
5729        }
5730    }
5731
5732    @Override
5733    public String[] getPackagesForUid(int uid) {
5734        final int callingUid = Binder.getCallingUid();
5735        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5736        final int userId = UserHandle.getUserId(uid);
5737        uid = UserHandle.getAppId(uid);
5738        // reader
5739        synchronized (mPackages) {
5740            Object obj = mSettings.getUserIdLPr(uid);
5741            if (obj instanceof SharedUserSetting) {
5742                if (isCallerInstantApp) {
5743                    return null;
5744                }
5745                final SharedUserSetting sus = (SharedUserSetting) obj;
5746                final int N = sus.packages.size();
5747                String[] res = new String[N];
5748                final Iterator<PackageSetting> it = sus.packages.iterator();
5749                int i = 0;
5750                while (it.hasNext()) {
5751                    PackageSetting ps = it.next();
5752                    if (ps.getInstalled(userId)) {
5753                        res[i++] = ps.name;
5754                    } else {
5755                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5756                    }
5757                }
5758                return res;
5759            } else if (obj instanceof PackageSetting) {
5760                final PackageSetting ps = (PackageSetting) obj;
5761                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5762                    return new String[]{ps.name};
5763                }
5764            }
5765        }
5766        return null;
5767    }
5768
5769    @Override
5770    public String getNameForUid(int uid) {
5771        final int callingUid = Binder.getCallingUid();
5772        if (getInstantAppPackageName(callingUid) != null) {
5773            return null;
5774        }
5775        synchronized (mPackages) {
5776            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5777            if (obj instanceof SharedUserSetting) {
5778                final SharedUserSetting sus = (SharedUserSetting) obj;
5779                return sus.name + ":" + sus.userId;
5780            } else if (obj instanceof PackageSetting) {
5781                final PackageSetting ps = (PackageSetting) obj;
5782                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5783                    return null;
5784                }
5785                return ps.name;
5786            }
5787            return null;
5788        }
5789    }
5790
5791    @Override
5792    public String[] getNamesForUids(int[] uids) {
5793        if (uids == null || uids.length == 0) {
5794            return null;
5795        }
5796        final int callingUid = Binder.getCallingUid();
5797        if (getInstantAppPackageName(callingUid) != null) {
5798            return null;
5799        }
5800        final String[] names = new String[uids.length];
5801        synchronized (mPackages) {
5802            for (int i = uids.length - 1; i >= 0; i--) {
5803                final int uid = uids[i];
5804                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5805                if (obj instanceof SharedUserSetting) {
5806                    final SharedUserSetting sus = (SharedUserSetting) obj;
5807                    names[i] = "shared:" + sus.name;
5808                } else if (obj instanceof PackageSetting) {
5809                    final PackageSetting ps = (PackageSetting) obj;
5810                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5811                        names[i] = null;
5812                    } else {
5813                        names[i] = ps.name;
5814                    }
5815                } else {
5816                    names[i] = null;
5817                }
5818            }
5819        }
5820        return names;
5821    }
5822
5823    @Override
5824    public int getUidForSharedUser(String sharedUserName) {
5825        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5826            return -1;
5827        }
5828        if (sharedUserName == null) {
5829            return -1;
5830        }
5831        // reader
5832        synchronized (mPackages) {
5833            SharedUserSetting suid;
5834            try {
5835                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5836                if (suid != null) {
5837                    return suid.userId;
5838                }
5839            } catch (PackageManagerException ignore) {
5840                // can't happen, but, still need to catch it
5841            }
5842            return -1;
5843        }
5844    }
5845
5846    @Override
5847    public int getFlagsForUid(int uid) {
5848        final int callingUid = Binder.getCallingUid();
5849        if (getInstantAppPackageName(callingUid) != null) {
5850            return 0;
5851        }
5852        synchronized (mPackages) {
5853            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5854            if (obj instanceof SharedUserSetting) {
5855                final SharedUserSetting sus = (SharedUserSetting) obj;
5856                return sus.pkgFlags;
5857            } else if (obj instanceof PackageSetting) {
5858                final PackageSetting ps = (PackageSetting) obj;
5859                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5860                    return 0;
5861                }
5862                return ps.pkgFlags;
5863            }
5864        }
5865        return 0;
5866    }
5867
5868    @Override
5869    public int getPrivateFlagsForUid(int uid) {
5870        final int callingUid = Binder.getCallingUid();
5871        if (getInstantAppPackageName(callingUid) != null) {
5872            return 0;
5873        }
5874        synchronized (mPackages) {
5875            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5876            if (obj instanceof SharedUserSetting) {
5877                final SharedUserSetting sus = (SharedUserSetting) obj;
5878                return sus.pkgPrivateFlags;
5879            } else if (obj instanceof PackageSetting) {
5880                final PackageSetting ps = (PackageSetting) obj;
5881                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5882                    return 0;
5883                }
5884                return ps.pkgPrivateFlags;
5885            }
5886        }
5887        return 0;
5888    }
5889
5890    @Override
5891    public boolean isUidPrivileged(int uid) {
5892        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5893            return false;
5894        }
5895        uid = UserHandle.getAppId(uid);
5896        // reader
5897        synchronized (mPackages) {
5898            Object obj = mSettings.getUserIdLPr(uid);
5899            if (obj instanceof SharedUserSetting) {
5900                final SharedUserSetting sus = (SharedUserSetting) obj;
5901                final Iterator<PackageSetting> it = sus.packages.iterator();
5902                while (it.hasNext()) {
5903                    if (it.next().isPrivileged()) {
5904                        return true;
5905                    }
5906                }
5907            } else if (obj instanceof PackageSetting) {
5908                final PackageSetting ps = (PackageSetting) obj;
5909                return ps.isPrivileged();
5910            }
5911        }
5912        return false;
5913    }
5914
5915    @Override
5916    public String[] getAppOpPermissionPackages(String permName) {
5917        return mPermissionManager.getAppOpPermissionPackages(permName);
5918    }
5919
5920    @Override
5921    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5922            int flags, int userId) {
5923        return resolveIntentInternal(
5924                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5925    }
5926
5927    /**
5928     * Normally instant apps can only be resolved when they're visible to the caller.
5929     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5930     * since we need to allow the system to start any installed application.
5931     */
5932    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5933            int flags, int userId, boolean resolveForStart) {
5934        try {
5935            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5936
5937            if (!sUserManager.exists(userId)) return null;
5938            final int callingUid = Binder.getCallingUid();
5939            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5940            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5941                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5942
5943            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5944            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5945                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5946            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5947
5948            final ResolveInfo bestChoice =
5949                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5950            return bestChoice;
5951        } finally {
5952            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5953        }
5954    }
5955
5956    @Override
5957    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5958        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5959            throw new SecurityException(
5960                    "findPersistentPreferredActivity can only be run by the system");
5961        }
5962        if (!sUserManager.exists(userId)) {
5963            return null;
5964        }
5965        final int callingUid = Binder.getCallingUid();
5966        intent = updateIntentForResolve(intent);
5967        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5968        final int flags = updateFlagsForResolve(
5969                0, userId, intent, callingUid, false /*includeInstantApps*/);
5970        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5971                userId);
5972        synchronized (mPackages) {
5973            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5974                    userId);
5975        }
5976    }
5977
5978    @Override
5979    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5980            IntentFilter filter, int match, ComponentName activity) {
5981        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5982            return;
5983        }
5984        final int userId = UserHandle.getCallingUserId();
5985        if (DEBUG_PREFERRED) {
5986            Log.v(TAG, "setLastChosenActivity intent=" + intent
5987                + " resolvedType=" + resolvedType
5988                + " flags=" + flags
5989                + " filter=" + filter
5990                + " match=" + match
5991                + " activity=" + activity);
5992            filter.dump(new PrintStreamPrinter(System.out), "    ");
5993        }
5994        intent.setComponent(null);
5995        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5996                userId);
5997        // Find any earlier preferred or last chosen entries and nuke them
5998        findPreferredActivity(intent, resolvedType,
5999                flags, query, 0, false, true, false, userId);
6000        // Add the new activity as the last chosen for this filter
6001        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6002                "Setting last chosen");
6003    }
6004
6005    @Override
6006    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6007        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6008            return null;
6009        }
6010        final int userId = UserHandle.getCallingUserId();
6011        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6012        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6013                userId);
6014        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6015                false, false, false, userId);
6016    }
6017
6018    /**
6019     * Returns whether or not instant apps have been disabled remotely.
6020     */
6021    private boolean areWebInstantAppsDisabled() {
6022        return mWebInstantAppsDisabled;
6023    }
6024
6025    private boolean isInstantAppResolutionAllowed(
6026            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6027            boolean skipPackageCheck) {
6028        if (mInstantAppResolverConnection == null) {
6029            return false;
6030        }
6031        if (mInstantAppInstallerActivity == null) {
6032            return false;
6033        }
6034        if (intent.getComponent() != null) {
6035            return false;
6036        }
6037        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6038            return false;
6039        }
6040        if (!skipPackageCheck && intent.getPackage() != null) {
6041            return false;
6042        }
6043        if (!intent.isWebIntent()) {
6044            // for non web intents, we should not resolve externally if an app already exists to
6045            // handle it or if the caller didn't explicitly request it.
6046            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6047                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6048                return false;
6049            }
6050        } else {
6051            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6052                return false;
6053            } else if (areWebInstantAppsDisabled()) {
6054                return false;
6055            }
6056        }
6057        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6058        // Or if there's already an ephemeral app installed that handles the action
6059        synchronized (mPackages) {
6060            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6061            for (int n = 0; n < count; n++) {
6062                final ResolveInfo info = resolvedActivities.get(n);
6063                final String packageName = info.activityInfo.packageName;
6064                final PackageSetting ps = mSettings.mPackages.get(packageName);
6065                if (ps != null) {
6066                    // only check domain verification status if the app is not a browser
6067                    if (!info.handleAllWebDataURI) {
6068                        // Try to get the status from User settings first
6069                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6070                        final int status = (int) (packedStatus >> 32);
6071                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6072                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6073                            if (DEBUG_INSTANT) {
6074                                Slog.v(TAG, "DENY instant app;"
6075                                    + " pkg: " + packageName + ", status: " + status);
6076                            }
6077                            return false;
6078                        }
6079                    }
6080                    if (ps.getInstantApp(userId)) {
6081                        if (DEBUG_INSTANT) {
6082                            Slog.v(TAG, "DENY instant app installed;"
6083                                    + " pkg: " + packageName);
6084                        }
6085                        return false;
6086                    }
6087                }
6088            }
6089        }
6090        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6091        return true;
6092    }
6093
6094    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6095            Intent origIntent, String resolvedType, String callingPackage,
6096            Bundle verificationBundle, int userId) {
6097        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6098                new InstantAppRequest(responseObj, origIntent, resolvedType,
6099                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6100        mHandler.sendMessage(msg);
6101    }
6102
6103    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6104            int flags, List<ResolveInfo> query, int userId) {
6105        if (query != null) {
6106            final int N = query.size();
6107            if (N == 1) {
6108                return query.get(0);
6109            } else if (N > 1) {
6110                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6111                // If there is more than one activity with the same priority,
6112                // then let the user decide between them.
6113                ResolveInfo r0 = query.get(0);
6114                ResolveInfo r1 = query.get(1);
6115                if (DEBUG_INTENT_MATCHING || debug) {
6116                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6117                            + r1.activityInfo.name + "=" + r1.priority);
6118                }
6119                // If the first activity has a higher priority, or a different
6120                // default, then it is always desirable to pick it.
6121                if (r0.priority != r1.priority
6122                        || r0.preferredOrder != r1.preferredOrder
6123                        || r0.isDefault != r1.isDefault) {
6124                    return query.get(0);
6125                }
6126                // If we have saved a preference for a preferred activity for
6127                // this Intent, use that.
6128                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6129                        flags, query, r0.priority, true, false, debug, userId);
6130                if (ri != null) {
6131                    return ri;
6132                }
6133                // If we have an ephemeral app, use it
6134                for (int i = 0; i < N; i++) {
6135                    ri = query.get(i);
6136                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6137                        final String packageName = ri.activityInfo.packageName;
6138                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6139                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6140                        final int status = (int)(packedStatus >> 32);
6141                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6142                            return ri;
6143                        }
6144                    }
6145                }
6146                ri = new ResolveInfo(mResolveInfo);
6147                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6148                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6149                // If all of the options come from the same package, show the application's
6150                // label and icon instead of the generic resolver's.
6151                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6152                // and then throw away the ResolveInfo itself, meaning that the caller loses
6153                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6154                // a fallback for this case; we only set the target package's resources on
6155                // the ResolveInfo, not the ActivityInfo.
6156                final String intentPackage = intent.getPackage();
6157                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6158                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6159                    ri.resolvePackageName = intentPackage;
6160                    if (userNeedsBadging(userId)) {
6161                        ri.noResourceId = true;
6162                    } else {
6163                        ri.icon = appi.icon;
6164                    }
6165                    ri.iconResourceId = appi.icon;
6166                    ri.labelRes = appi.labelRes;
6167                }
6168                ri.activityInfo.applicationInfo = new ApplicationInfo(
6169                        ri.activityInfo.applicationInfo);
6170                if (userId != 0) {
6171                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6172                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6173                }
6174                // Make sure that the resolver is displayable in car mode
6175                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6176                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6177                return ri;
6178            }
6179        }
6180        return null;
6181    }
6182
6183    /**
6184     * Return true if the given list is not empty and all of its contents have
6185     * an activityInfo with the given package name.
6186     */
6187    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6188        if (ArrayUtils.isEmpty(list)) {
6189            return false;
6190        }
6191        for (int i = 0, N = list.size(); i < N; i++) {
6192            final ResolveInfo ri = list.get(i);
6193            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6194            if (ai == null || !packageName.equals(ai.packageName)) {
6195                return false;
6196            }
6197        }
6198        return true;
6199    }
6200
6201    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6202            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6203        final int N = query.size();
6204        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6205                .get(userId);
6206        // Get the list of persistent preferred activities that handle the intent
6207        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6208        List<PersistentPreferredActivity> pprefs = ppir != null
6209                ? ppir.queryIntent(intent, resolvedType,
6210                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6211                        userId)
6212                : null;
6213        if (pprefs != null && pprefs.size() > 0) {
6214            final int M = pprefs.size();
6215            for (int i=0; i<M; i++) {
6216                final PersistentPreferredActivity ppa = pprefs.get(i);
6217                if (DEBUG_PREFERRED || debug) {
6218                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6219                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6220                            + "\n  component=" + ppa.mComponent);
6221                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6222                }
6223                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6224                        flags | MATCH_DISABLED_COMPONENTS, userId);
6225                if (DEBUG_PREFERRED || debug) {
6226                    Slog.v(TAG, "Found persistent preferred activity:");
6227                    if (ai != null) {
6228                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6229                    } else {
6230                        Slog.v(TAG, "  null");
6231                    }
6232                }
6233                if (ai == null) {
6234                    // This previously registered persistent preferred activity
6235                    // component is no longer known. Ignore it and do NOT remove it.
6236                    continue;
6237                }
6238                for (int j=0; j<N; j++) {
6239                    final ResolveInfo ri = query.get(j);
6240                    if (!ri.activityInfo.applicationInfo.packageName
6241                            .equals(ai.applicationInfo.packageName)) {
6242                        continue;
6243                    }
6244                    if (!ri.activityInfo.name.equals(ai.name)) {
6245                        continue;
6246                    }
6247                    //  Found a persistent preference that can handle the intent.
6248                    if (DEBUG_PREFERRED || debug) {
6249                        Slog.v(TAG, "Returning persistent preferred activity: " +
6250                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6251                    }
6252                    return ri;
6253                }
6254            }
6255        }
6256        return null;
6257    }
6258
6259    // TODO: handle preferred activities missing while user has amnesia
6260    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6261            List<ResolveInfo> query, int priority, boolean always,
6262            boolean removeMatches, boolean debug, int userId) {
6263        if (!sUserManager.exists(userId)) return null;
6264        final int callingUid = Binder.getCallingUid();
6265        flags = updateFlagsForResolve(
6266                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6267        intent = updateIntentForResolve(intent);
6268        // writer
6269        synchronized (mPackages) {
6270            // Try to find a matching persistent preferred activity.
6271            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6272                    debug, userId);
6273
6274            // If a persistent preferred activity matched, use it.
6275            if (pri != null) {
6276                return pri;
6277            }
6278
6279            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6280            // Get the list of preferred activities that handle the intent
6281            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6282            List<PreferredActivity> prefs = pir != null
6283                    ? pir.queryIntent(intent, resolvedType,
6284                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6285                            userId)
6286                    : null;
6287            if (prefs != null && prefs.size() > 0) {
6288                boolean changed = false;
6289                try {
6290                    // First figure out how good the original match set is.
6291                    // We will only allow preferred activities that came
6292                    // from the same match quality.
6293                    int match = 0;
6294
6295                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6296
6297                    final int N = query.size();
6298                    for (int j=0; j<N; j++) {
6299                        final ResolveInfo ri = query.get(j);
6300                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6301                                + ": 0x" + Integer.toHexString(match));
6302                        if (ri.match > match) {
6303                            match = ri.match;
6304                        }
6305                    }
6306
6307                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6308                            + Integer.toHexString(match));
6309
6310                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6311                    final int M = prefs.size();
6312                    for (int i=0; i<M; i++) {
6313                        final PreferredActivity pa = prefs.get(i);
6314                        if (DEBUG_PREFERRED || debug) {
6315                            Slog.v(TAG, "Checking PreferredActivity ds="
6316                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6317                                    + "\n  component=" + pa.mPref.mComponent);
6318                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6319                        }
6320                        if (pa.mPref.mMatch != match) {
6321                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6322                                    + Integer.toHexString(pa.mPref.mMatch));
6323                            continue;
6324                        }
6325                        // If it's not an "always" type preferred activity and that's what we're
6326                        // looking for, skip it.
6327                        if (always && !pa.mPref.mAlways) {
6328                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6329                            continue;
6330                        }
6331                        final ActivityInfo ai = getActivityInfo(
6332                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6333                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6334                                userId);
6335                        if (DEBUG_PREFERRED || debug) {
6336                            Slog.v(TAG, "Found preferred activity:");
6337                            if (ai != null) {
6338                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6339                            } else {
6340                                Slog.v(TAG, "  null");
6341                            }
6342                        }
6343                        if (ai == null) {
6344                            // This previously registered preferred activity
6345                            // component is no longer known.  Most likely an update
6346                            // to the app was installed and in the new version this
6347                            // component no longer exists.  Clean it up by removing
6348                            // it from the preferred activities list, and skip it.
6349                            Slog.w(TAG, "Removing dangling preferred activity: "
6350                                    + pa.mPref.mComponent);
6351                            pir.removeFilter(pa);
6352                            changed = true;
6353                            continue;
6354                        }
6355                        for (int j=0; j<N; j++) {
6356                            final ResolveInfo ri = query.get(j);
6357                            if (!ri.activityInfo.applicationInfo.packageName
6358                                    .equals(ai.applicationInfo.packageName)) {
6359                                continue;
6360                            }
6361                            if (!ri.activityInfo.name.equals(ai.name)) {
6362                                continue;
6363                            }
6364
6365                            if (removeMatches) {
6366                                pir.removeFilter(pa);
6367                                changed = true;
6368                                if (DEBUG_PREFERRED) {
6369                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6370                                }
6371                                break;
6372                            }
6373
6374                            // Okay we found a previously set preferred or last chosen app.
6375                            // If the result set is different from when this
6376                            // was created, and is not a subset of the preferred set, we need to
6377                            // clear it and re-ask the user their preference, if we're looking for
6378                            // an "always" type entry.
6379                            if (always && !pa.mPref.sameSet(query)) {
6380                                if (pa.mPref.isSuperset(query)) {
6381                                    // some components of the set are no longer present in
6382                                    // the query, but the preferred activity can still be reused
6383                                    if (DEBUG_PREFERRED) {
6384                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6385                                                + " still valid as only non-preferred components"
6386                                                + " were removed for " + intent + " type "
6387                                                + resolvedType);
6388                                    }
6389                                    // remove obsolete components and re-add the up-to-date filter
6390                                    PreferredActivity freshPa = new PreferredActivity(pa,
6391                                            pa.mPref.mMatch,
6392                                            pa.mPref.discardObsoleteComponents(query),
6393                                            pa.mPref.mComponent,
6394                                            pa.mPref.mAlways);
6395                                    pir.removeFilter(pa);
6396                                    pir.addFilter(freshPa);
6397                                    changed = true;
6398                                } else {
6399                                    Slog.i(TAG,
6400                                            "Result set changed, dropping preferred activity for "
6401                                                    + intent + " type " + resolvedType);
6402                                    if (DEBUG_PREFERRED) {
6403                                        Slog.v(TAG, "Removing preferred activity since set changed "
6404                                                + pa.mPref.mComponent);
6405                                    }
6406                                    pir.removeFilter(pa);
6407                                    // Re-add the filter as a "last chosen" entry (!always)
6408                                    PreferredActivity lastChosen = new PreferredActivity(
6409                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6410                                    pir.addFilter(lastChosen);
6411                                    changed = true;
6412                                    return null;
6413                                }
6414                            }
6415
6416                            // Yay! Either the set matched or we're looking for the last chosen
6417                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6418                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6419                            return ri;
6420                        }
6421                    }
6422                } finally {
6423                    if (changed) {
6424                        if (DEBUG_PREFERRED) {
6425                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6426                        }
6427                        scheduleWritePackageRestrictionsLocked(userId);
6428                    }
6429                }
6430            }
6431        }
6432        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6433        return null;
6434    }
6435
6436    /*
6437     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6438     */
6439    @Override
6440    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6441            int targetUserId) {
6442        mContext.enforceCallingOrSelfPermission(
6443                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6444        List<CrossProfileIntentFilter> matches =
6445                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6446        if (matches != null) {
6447            int size = matches.size();
6448            for (int i = 0; i < size; i++) {
6449                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6450            }
6451        }
6452        if (intent.hasWebURI()) {
6453            // cross-profile app linking works only towards the parent.
6454            final int callingUid = Binder.getCallingUid();
6455            final UserInfo parent = getProfileParent(sourceUserId);
6456            synchronized(mPackages) {
6457                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6458                        false /*includeInstantApps*/);
6459                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6460                        intent, resolvedType, flags, sourceUserId, parent.id);
6461                return xpDomainInfo != null;
6462            }
6463        }
6464        return false;
6465    }
6466
6467    private UserInfo getProfileParent(int userId) {
6468        final long identity = Binder.clearCallingIdentity();
6469        try {
6470            return sUserManager.getProfileParent(userId);
6471        } finally {
6472            Binder.restoreCallingIdentity(identity);
6473        }
6474    }
6475
6476    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6477            String resolvedType, int userId) {
6478        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6479        if (resolver != null) {
6480            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6481        }
6482        return null;
6483    }
6484
6485    @Override
6486    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6487            String resolvedType, int flags, int userId) {
6488        try {
6489            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6490
6491            return new ParceledListSlice<>(
6492                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6493        } finally {
6494            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6495        }
6496    }
6497
6498    /**
6499     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6500     * instant, returns {@code null}.
6501     */
6502    private String getInstantAppPackageName(int callingUid) {
6503        synchronized (mPackages) {
6504            // If the caller is an isolated app use the owner's uid for the lookup.
6505            if (Process.isIsolated(callingUid)) {
6506                callingUid = mIsolatedOwners.get(callingUid);
6507            }
6508            final int appId = UserHandle.getAppId(callingUid);
6509            final Object obj = mSettings.getUserIdLPr(appId);
6510            if (obj instanceof PackageSetting) {
6511                final PackageSetting ps = (PackageSetting) obj;
6512                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6513                return isInstantApp ? ps.pkg.packageName : null;
6514            }
6515        }
6516        return null;
6517    }
6518
6519    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6520            String resolvedType, int flags, int userId) {
6521        return queryIntentActivitiesInternal(
6522                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6523                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6524    }
6525
6526    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6527            String resolvedType, int flags, int filterCallingUid, int userId,
6528            boolean resolveForStart, boolean allowDynamicSplits) {
6529        if (!sUserManager.exists(userId)) return Collections.emptyList();
6530        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6531        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6532                false /* requireFullPermission */, false /* checkShell */,
6533                "query intent activities");
6534        final String pkgName = intent.getPackage();
6535        ComponentName comp = intent.getComponent();
6536        if (comp == null) {
6537            if (intent.getSelector() != null) {
6538                intent = intent.getSelector();
6539                comp = intent.getComponent();
6540            }
6541        }
6542
6543        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6544                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6545        if (comp != null) {
6546            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6547            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6548            if (ai != null) {
6549                // When specifying an explicit component, we prevent the activity from being
6550                // used when either 1) the calling package is normal and the activity is within
6551                // an ephemeral application or 2) the calling package is ephemeral and the
6552                // activity is not visible to ephemeral applications.
6553                final boolean matchInstantApp =
6554                        (flags & PackageManager.MATCH_INSTANT) != 0;
6555                final boolean matchVisibleToInstantAppOnly =
6556                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6557                final boolean matchExplicitlyVisibleOnly =
6558                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6559                final boolean isCallerInstantApp =
6560                        instantAppPkgName != null;
6561                final boolean isTargetSameInstantApp =
6562                        comp.getPackageName().equals(instantAppPkgName);
6563                final boolean isTargetInstantApp =
6564                        (ai.applicationInfo.privateFlags
6565                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6566                final boolean isTargetVisibleToInstantApp =
6567                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6568                final boolean isTargetExplicitlyVisibleToInstantApp =
6569                        isTargetVisibleToInstantApp
6570                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6571                final boolean isTargetHiddenFromInstantApp =
6572                        !isTargetVisibleToInstantApp
6573                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6574                final boolean blockResolution =
6575                        !isTargetSameInstantApp
6576                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6577                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6578                                        && isTargetHiddenFromInstantApp));
6579                if (!blockResolution) {
6580                    final ResolveInfo ri = new ResolveInfo();
6581                    ri.activityInfo = ai;
6582                    list.add(ri);
6583                }
6584            }
6585            return applyPostResolutionFilter(
6586                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6587        }
6588
6589        // reader
6590        boolean sortResult = false;
6591        boolean addInstant = false;
6592        List<ResolveInfo> result;
6593        synchronized (mPackages) {
6594            if (pkgName == null) {
6595                List<CrossProfileIntentFilter> matchingFilters =
6596                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6597                // Check for results that need to skip the current profile.
6598                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6599                        resolvedType, flags, userId);
6600                if (xpResolveInfo != null) {
6601                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6602                    xpResult.add(xpResolveInfo);
6603                    return applyPostResolutionFilter(
6604                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6605                            allowDynamicSplits, filterCallingUid, userId, intent);
6606                }
6607
6608                // Check for results in the current profile.
6609                result = filterIfNotSystemUser(mActivities.queryIntent(
6610                        intent, resolvedType, flags, userId), userId);
6611                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6612                        false /*skipPackageCheck*/);
6613                // Check for cross profile results.
6614                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6615                xpResolveInfo = queryCrossProfileIntents(
6616                        matchingFilters, intent, resolvedType, flags, userId,
6617                        hasNonNegativePriorityResult);
6618                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6619                    boolean isVisibleToUser = filterIfNotSystemUser(
6620                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6621                    if (isVisibleToUser) {
6622                        result.add(xpResolveInfo);
6623                        sortResult = true;
6624                    }
6625                }
6626                if (intent.hasWebURI()) {
6627                    CrossProfileDomainInfo xpDomainInfo = null;
6628                    final UserInfo parent = getProfileParent(userId);
6629                    if (parent != null) {
6630                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6631                                flags, userId, parent.id);
6632                    }
6633                    if (xpDomainInfo != null) {
6634                        if (xpResolveInfo != null) {
6635                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6636                            // in the result.
6637                            result.remove(xpResolveInfo);
6638                        }
6639                        if (result.size() == 0 && !addInstant) {
6640                            // No result in current profile, but found candidate in parent user.
6641                            // And we are not going to add emphemeral app, so we can return the
6642                            // result straight away.
6643                            result.add(xpDomainInfo.resolveInfo);
6644                            return applyPostResolutionFilter(result, instantAppPkgName,
6645                                    allowDynamicSplits, filterCallingUid, userId, intent);
6646                        }
6647                    } else if (result.size() <= 1 && !addInstant) {
6648                        // No result in parent user and <= 1 result in current profile, and we
6649                        // are not going to add emphemeral app, so we can return the result without
6650                        // further processing.
6651                        return applyPostResolutionFilter(result, instantAppPkgName,
6652                                allowDynamicSplits, filterCallingUid, userId, intent);
6653                    }
6654                    // We have more than one candidate (combining results from current and parent
6655                    // profile), so we need filtering and sorting.
6656                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6657                            intent, flags, result, xpDomainInfo, userId);
6658                    sortResult = true;
6659                }
6660            } else {
6661                final PackageParser.Package pkg = mPackages.get(pkgName);
6662                result = null;
6663                if (pkg != null) {
6664                    result = filterIfNotSystemUser(
6665                            mActivities.queryIntentForPackage(
6666                                    intent, resolvedType, flags, pkg.activities, userId),
6667                            userId);
6668                }
6669                if (result == null || result.size() == 0) {
6670                    // the caller wants to resolve for a particular package; however, there
6671                    // were no installed results, so, try to find an ephemeral result
6672                    addInstant = isInstantAppResolutionAllowed(
6673                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6674                    if (result == null) {
6675                        result = new ArrayList<>();
6676                    }
6677                }
6678            }
6679        }
6680        if (addInstant) {
6681            result = maybeAddInstantAppInstaller(
6682                    result, intent, resolvedType, flags, userId, resolveForStart);
6683        }
6684        if (sortResult) {
6685            Collections.sort(result, mResolvePrioritySorter);
6686        }
6687        return applyPostResolutionFilter(
6688                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6689    }
6690
6691    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6692            String resolvedType, int flags, int userId, boolean resolveForStart) {
6693        // first, check to see if we've got an instant app already installed
6694        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6695        ResolveInfo localInstantApp = null;
6696        boolean blockResolution = false;
6697        if (!alreadyResolvedLocally) {
6698            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6699                    flags
6700                        | PackageManager.GET_RESOLVED_FILTER
6701                        | PackageManager.MATCH_INSTANT
6702                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6703                    userId);
6704            for (int i = instantApps.size() - 1; i >= 0; --i) {
6705                final ResolveInfo info = instantApps.get(i);
6706                final String packageName = info.activityInfo.packageName;
6707                final PackageSetting ps = mSettings.mPackages.get(packageName);
6708                if (ps.getInstantApp(userId)) {
6709                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6710                    final int status = (int)(packedStatus >> 32);
6711                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6712                        // there's a local instant application installed, but, the user has
6713                        // chosen to never use it; skip resolution and don't acknowledge
6714                        // an instant application is even available
6715                        if (DEBUG_INSTANT) {
6716                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6717                        }
6718                        blockResolution = true;
6719                        break;
6720                    } else {
6721                        // we have a locally installed instant application; skip resolution
6722                        // but acknowledge there's an instant application available
6723                        if (DEBUG_INSTANT) {
6724                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6725                        }
6726                        localInstantApp = info;
6727                        break;
6728                    }
6729                }
6730            }
6731        }
6732        // no app installed, let's see if one's available
6733        AuxiliaryResolveInfo auxiliaryResponse = null;
6734        if (!blockResolution) {
6735            if (localInstantApp == null) {
6736                // we don't have an instant app locally, resolve externally
6737                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6738                final InstantAppRequest requestObject = new InstantAppRequest(
6739                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6740                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6741                        resolveForStart);
6742                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6743                        mInstantAppResolverConnection, requestObject);
6744                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6745            } else {
6746                // we have an instant application locally, but, we can't admit that since
6747                // callers shouldn't be able to determine prior browsing. create a dummy
6748                // auxiliary response so the downstream code behaves as if there's an
6749                // instant application available externally. when it comes time to start
6750                // the instant application, we'll do the right thing.
6751                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6752                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6753                                        ai.packageName, ai.versionCode, null /* splitName */);
6754            }
6755        }
6756        if (intent.isWebIntent() && auxiliaryResponse == null) {
6757            return result;
6758        }
6759        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6760        if (ps == null
6761                || ps.getUserState().get(userId) == null
6762                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6763            return result;
6764        }
6765        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6766        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6767                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6768        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6769                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6770        // add a non-generic filter
6771        ephemeralInstaller.filter = new IntentFilter();
6772        if (intent.getAction() != null) {
6773            ephemeralInstaller.filter.addAction(intent.getAction());
6774        }
6775        if (intent.getData() != null && intent.getData().getPath() != null) {
6776            ephemeralInstaller.filter.addDataPath(
6777                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6778        }
6779        ephemeralInstaller.isInstantAppAvailable = true;
6780        // make sure this resolver is the default
6781        ephemeralInstaller.isDefault = true;
6782        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6783        if (DEBUG_INSTANT) {
6784            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6785        }
6786
6787        result.add(ephemeralInstaller);
6788        return result;
6789    }
6790
6791    private static class CrossProfileDomainInfo {
6792        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6793        ResolveInfo resolveInfo;
6794        /* Best domain verification status of the activities found in the other profile */
6795        int bestDomainVerificationStatus;
6796    }
6797
6798    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6799            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6800        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6801                sourceUserId)) {
6802            return null;
6803        }
6804        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6805                resolvedType, flags, parentUserId);
6806
6807        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6808            return null;
6809        }
6810        CrossProfileDomainInfo result = null;
6811        int size = resultTargetUser.size();
6812        for (int i = 0; i < size; i++) {
6813            ResolveInfo riTargetUser = resultTargetUser.get(i);
6814            // Intent filter verification is only for filters that specify a host. So don't return
6815            // those that handle all web uris.
6816            if (riTargetUser.handleAllWebDataURI) {
6817                continue;
6818            }
6819            String packageName = riTargetUser.activityInfo.packageName;
6820            PackageSetting ps = mSettings.mPackages.get(packageName);
6821            if (ps == null) {
6822                continue;
6823            }
6824            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6825            int status = (int)(verificationState >> 32);
6826            if (result == null) {
6827                result = new CrossProfileDomainInfo();
6828                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6829                        sourceUserId, parentUserId);
6830                result.bestDomainVerificationStatus = status;
6831            } else {
6832                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6833                        result.bestDomainVerificationStatus);
6834            }
6835        }
6836        // Don't consider matches with status NEVER across profiles.
6837        if (result != null && result.bestDomainVerificationStatus
6838                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6839            return null;
6840        }
6841        return result;
6842    }
6843
6844    /**
6845     * Verification statuses are ordered from the worse to the best, except for
6846     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6847     */
6848    private int bestDomainVerificationStatus(int status1, int status2) {
6849        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6850            return status2;
6851        }
6852        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6853            return status1;
6854        }
6855        return (int) MathUtils.max(status1, status2);
6856    }
6857
6858    private boolean isUserEnabled(int userId) {
6859        long callingId = Binder.clearCallingIdentity();
6860        try {
6861            UserInfo userInfo = sUserManager.getUserInfo(userId);
6862            return userInfo != null && userInfo.isEnabled();
6863        } finally {
6864            Binder.restoreCallingIdentity(callingId);
6865        }
6866    }
6867
6868    /**
6869     * Filter out activities with systemUserOnly flag set, when current user is not System.
6870     *
6871     * @return filtered list
6872     */
6873    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6874        if (userId == UserHandle.USER_SYSTEM) {
6875            return resolveInfos;
6876        }
6877        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6878            ResolveInfo info = resolveInfos.get(i);
6879            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6880                resolveInfos.remove(i);
6881            }
6882        }
6883        return resolveInfos;
6884    }
6885
6886    /**
6887     * Filters out ephemeral activities.
6888     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6889     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6890     *
6891     * @param resolveInfos The pre-filtered list of resolved activities
6892     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6893     *          is performed.
6894     * @param intent
6895     * @return A filtered list of resolved activities.
6896     */
6897    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6898            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6899            Intent intent) {
6900        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6901        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6902            final ResolveInfo info = resolveInfos.get(i);
6903            // remove locally resolved instant app web results when disabled
6904            if (info.isInstantAppAvailable && blockInstant) {
6905                resolveInfos.remove(i);
6906                continue;
6907            }
6908            // allow activities that are defined in the provided package
6909            if (allowDynamicSplits
6910                    && info.activityInfo != null
6911                    && info.activityInfo.splitName != null
6912                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6913                            info.activityInfo.splitName)) {
6914                if (mInstantAppInstallerActivity == null) {
6915                    if (DEBUG_INSTALL) {
6916                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6917                    }
6918                    resolveInfos.remove(i);
6919                    continue;
6920                }
6921                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6922                    resolveInfos.remove(i);
6923                    continue;
6924                }
6925                // requested activity is defined in a split that hasn't been installed yet.
6926                // add the installer to the resolve list
6927                if (DEBUG_INSTALL) {
6928                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6929                }
6930                final ResolveInfo installerInfo = new ResolveInfo(
6931                        mInstantAppInstallerInfo);
6932                final ComponentName installFailureActivity = findInstallFailureActivity(
6933                        info.activityInfo.packageName,  filterCallingUid, userId);
6934                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6935                        installFailureActivity,
6936                        info.activityInfo.packageName,
6937                        info.activityInfo.applicationInfo.versionCode,
6938                        info.activityInfo.splitName);
6939                // add a non-generic filter
6940                installerInfo.filter = new IntentFilter();
6941
6942                // This resolve info may appear in the chooser UI, so let us make it
6943                // look as the one it replaces as far as the user is concerned which
6944                // requires loading the correct label and icon for the resolve info.
6945                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6946                installerInfo.labelRes = info.resolveLabelResId();
6947                installerInfo.icon = info.resolveIconResId();
6948                installerInfo.isInstantAppAvailable = true;
6949                resolveInfos.set(i, installerInfo);
6950                continue;
6951            }
6952            // caller is a full app, don't need to apply any other filtering
6953            if (ephemeralPkgName == null) {
6954                continue;
6955            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6956                // caller is same app; don't need to apply any other filtering
6957                continue;
6958            }
6959            // allow activities that have been explicitly exposed to ephemeral apps
6960            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6961            if (!isEphemeralApp
6962                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6963                continue;
6964            }
6965            resolveInfos.remove(i);
6966        }
6967        return resolveInfos;
6968    }
6969
6970    /**
6971     * Returns the activity component that can handle install failures.
6972     * <p>By default, the instant application installer handles failures. However, an
6973     * application may want to handle failures on its own. Applications do this by
6974     * creating an activity with an intent filter that handles the action
6975     * {@link Intent#ACTION_INSTALL_FAILURE}.
6976     */
6977    private @Nullable ComponentName findInstallFailureActivity(
6978            String packageName, int filterCallingUid, int userId) {
6979        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6980        failureActivityIntent.setPackage(packageName);
6981        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6982        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6983                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6984                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6985        final int NR = result.size();
6986        if (NR > 0) {
6987            for (int i = 0; i < NR; i++) {
6988                final ResolveInfo info = result.get(i);
6989                if (info.activityInfo.splitName != null) {
6990                    continue;
6991                }
6992                return new ComponentName(packageName, info.activityInfo.name);
6993            }
6994        }
6995        return null;
6996    }
6997
6998    /**
6999     * @param resolveInfos list of resolve infos in descending priority order
7000     * @return if the list contains a resolve info with non-negative priority
7001     */
7002    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7003        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7004    }
7005
7006    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7007            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7008            int userId) {
7009        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7010
7011        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7012            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7013                    candidates.size());
7014        }
7015
7016        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7017        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7018        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7019        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7020        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7021        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7022
7023        synchronized (mPackages) {
7024            final int count = candidates.size();
7025            // First, try to use linked apps. Partition the candidates into four lists:
7026            // one for the final results, one for the "do not use ever", one for "undefined status"
7027            // and finally one for "browser app type".
7028            for (int n=0; n<count; n++) {
7029                ResolveInfo info = candidates.get(n);
7030                String packageName = info.activityInfo.packageName;
7031                PackageSetting ps = mSettings.mPackages.get(packageName);
7032                if (ps != null) {
7033                    // Add to the special match all list (Browser use case)
7034                    if (info.handleAllWebDataURI) {
7035                        matchAllList.add(info);
7036                        continue;
7037                    }
7038                    // Try to get the status from User settings first
7039                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7040                    int status = (int)(packedStatus >> 32);
7041                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7042                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7043                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7044                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7045                                    + " : linkgen=" + linkGeneration);
7046                        }
7047                        // Use link-enabled generation as preferredOrder, i.e.
7048                        // prefer newly-enabled over earlier-enabled.
7049                        info.preferredOrder = linkGeneration;
7050                        alwaysList.add(info);
7051                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7052                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7053                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7054                        }
7055                        neverList.add(info);
7056                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7057                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7058                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7059                        }
7060                        alwaysAskList.add(info);
7061                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7062                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7063                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7064                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7065                        }
7066                        undefinedList.add(info);
7067                    }
7068                }
7069            }
7070
7071            // We'll want to include browser possibilities in a few cases
7072            boolean includeBrowser = false;
7073
7074            // First try to add the "always" resolution(s) for the current user, if any
7075            if (alwaysList.size() > 0) {
7076                result.addAll(alwaysList);
7077            } else {
7078                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7079                result.addAll(undefinedList);
7080                // Maybe add one for the other profile.
7081                if (xpDomainInfo != null && (
7082                        xpDomainInfo.bestDomainVerificationStatus
7083                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7084                    result.add(xpDomainInfo.resolveInfo);
7085                }
7086                includeBrowser = true;
7087            }
7088
7089            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7090            // If there were 'always' entries their preferred order has been set, so we also
7091            // back that off to make the alternatives equivalent
7092            if (alwaysAskList.size() > 0) {
7093                for (ResolveInfo i : result) {
7094                    i.preferredOrder = 0;
7095                }
7096                result.addAll(alwaysAskList);
7097                includeBrowser = true;
7098            }
7099
7100            if (includeBrowser) {
7101                // Also add browsers (all of them or only the default one)
7102                if (DEBUG_DOMAIN_VERIFICATION) {
7103                    Slog.v(TAG, "   ...including browsers in candidate set");
7104                }
7105                if ((matchFlags & MATCH_ALL) != 0) {
7106                    result.addAll(matchAllList);
7107                } else {
7108                    // Browser/generic handling case.  If there's a default browser, go straight
7109                    // to that (but only if there is no other higher-priority match).
7110                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7111                    int maxMatchPrio = 0;
7112                    ResolveInfo defaultBrowserMatch = null;
7113                    final int numCandidates = matchAllList.size();
7114                    for (int n = 0; n < numCandidates; n++) {
7115                        ResolveInfo info = matchAllList.get(n);
7116                        // track the highest overall match priority...
7117                        if (info.priority > maxMatchPrio) {
7118                            maxMatchPrio = info.priority;
7119                        }
7120                        // ...and the highest-priority default browser match
7121                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7122                            if (defaultBrowserMatch == null
7123                                    || (defaultBrowserMatch.priority < info.priority)) {
7124                                if (debug) {
7125                                    Slog.v(TAG, "Considering default browser match " + info);
7126                                }
7127                                defaultBrowserMatch = info;
7128                            }
7129                        }
7130                    }
7131                    if (defaultBrowserMatch != null
7132                            && defaultBrowserMatch.priority >= maxMatchPrio
7133                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7134                    {
7135                        if (debug) {
7136                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7137                        }
7138                        result.add(defaultBrowserMatch);
7139                    } else {
7140                        result.addAll(matchAllList);
7141                    }
7142                }
7143
7144                // If there is nothing selected, add all candidates and remove the ones that the user
7145                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7146                if (result.size() == 0) {
7147                    result.addAll(candidates);
7148                    result.removeAll(neverList);
7149                }
7150            }
7151        }
7152        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7153            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7154                    result.size());
7155            for (ResolveInfo info : result) {
7156                Slog.v(TAG, "  + " + info.activityInfo);
7157            }
7158        }
7159        return result;
7160    }
7161
7162    // Returns a packed value as a long:
7163    //
7164    // high 'int'-sized word: link status: undefined/ask/never/always.
7165    // low 'int'-sized word: relative priority among 'always' results.
7166    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7167        long result = ps.getDomainVerificationStatusForUser(userId);
7168        // if none available, get the master status
7169        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7170            if (ps.getIntentFilterVerificationInfo() != null) {
7171                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7172            }
7173        }
7174        return result;
7175    }
7176
7177    private ResolveInfo querySkipCurrentProfileIntents(
7178            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7179            int flags, int sourceUserId) {
7180        if (matchingFilters != null) {
7181            int size = matchingFilters.size();
7182            for (int i = 0; i < size; i ++) {
7183                CrossProfileIntentFilter filter = matchingFilters.get(i);
7184                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7185                    // Checking if there are activities in the target user that can handle the
7186                    // intent.
7187                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7188                            resolvedType, flags, sourceUserId);
7189                    if (resolveInfo != null) {
7190                        return resolveInfo;
7191                    }
7192                }
7193            }
7194        }
7195        return null;
7196    }
7197
7198    // Return matching ResolveInfo in target user if any.
7199    private ResolveInfo queryCrossProfileIntents(
7200            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7201            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7202        if (matchingFilters != null) {
7203            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7204            // match the same intent. For performance reasons, it is better not to
7205            // run queryIntent twice for the same userId
7206            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7207            int size = matchingFilters.size();
7208            for (int i = 0; i < size; i++) {
7209                CrossProfileIntentFilter filter = matchingFilters.get(i);
7210                int targetUserId = filter.getTargetUserId();
7211                boolean skipCurrentProfile =
7212                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7213                boolean skipCurrentProfileIfNoMatchFound =
7214                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7215                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7216                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7217                    // Checking if there are activities in the target user that can handle the
7218                    // intent.
7219                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7220                            resolvedType, flags, sourceUserId);
7221                    if (resolveInfo != null) return resolveInfo;
7222                    alreadyTriedUserIds.put(targetUserId, true);
7223                }
7224            }
7225        }
7226        return null;
7227    }
7228
7229    /**
7230     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7231     * will forward the intent to the filter's target user.
7232     * Otherwise, returns null.
7233     */
7234    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7235            String resolvedType, int flags, int sourceUserId) {
7236        int targetUserId = filter.getTargetUserId();
7237        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7238                resolvedType, flags, targetUserId);
7239        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7240            // If all the matches in the target profile are suspended, return null.
7241            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7242                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7243                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7244                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7245                            targetUserId);
7246                }
7247            }
7248        }
7249        return null;
7250    }
7251
7252    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7253            int sourceUserId, int targetUserId) {
7254        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7255        long ident = Binder.clearCallingIdentity();
7256        boolean targetIsProfile;
7257        try {
7258            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7259        } finally {
7260            Binder.restoreCallingIdentity(ident);
7261        }
7262        String className;
7263        if (targetIsProfile) {
7264            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7265        } else {
7266            className = FORWARD_INTENT_TO_PARENT;
7267        }
7268        ComponentName forwardingActivityComponentName = new ComponentName(
7269                mAndroidApplication.packageName, className);
7270        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7271                sourceUserId);
7272        if (!targetIsProfile) {
7273            forwardingActivityInfo.showUserIcon = targetUserId;
7274            forwardingResolveInfo.noResourceId = true;
7275        }
7276        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7277        forwardingResolveInfo.priority = 0;
7278        forwardingResolveInfo.preferredOrder = 0;
7279        forwardingResolveInfo.match = 0;
7280        forwardingResolveInfo.isDefault = true;
7281        forwardingResolveInfo.filter = filter;
7282        forwardingResolveInfo.targetUserId = targetUserId;
7283        return forwardingResolveInfo;
7284    }
7285
7286    @Override
7287    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7288            Intent[] specifics, String[] specificTypes, Intent intent,
7289            String resolvedType, int flags, int userId) {
7290        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7291                specificTypes, intent, resolvedType, flags, userId));
7292    }
7293
7294    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7295            Intent[] specifics, String[] specificTypes, Intent intent,
7296            String resolvedType, int flags, int userId) {
7297        if (!sUserManager.exists(userId)) return Collections.emptyList();
7298        final int callingUid = Binder.getCallingUid();
7299        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7300                false /*includeInstantApps*/);
7301        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7302                false /*requireFullPermission*/, false /*checkShell*/,
7303                "query intent activity options");
7304        final String resultsAction = intent.getAction();
7305
7306        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7307                | PackageManager.GET_RESOLVED_FILTER, userId);
7308
7309        if (DEBUG_INTENT_MATCHING) {
7310            Log.v(TAG, "Query " + intent + ": " + results);
7311        }
7312
7313        int specificsPos = 0;
7314        int N;
7315
7316        // todo: note that the algorithm used here is O(N^2).  This
7317        // isn't a problem in our current environment, but if we start running
7318        // into situations where we have more than 5 or 10 matches then this
7319        // should probably be changed to something smarter...
7320
7321        // First we go through and resolve each of the specific items
7322        // that were supplied, taking care of removing any corresponding
7323        // duplicate items in the generic resolve list.
7324        if (specifics != null) {
7325            for (int i=0; i<specifics.length; i++) {
7326                final Intent sintent = specifics[i];
7327                if (sintent == null) {
7328                    continue;
7329                }
7330
7331                if (DEBUG_INTENT_MATCHING) {
7332                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7333                }
7334
7335                String action = sintent.getAction();
7336                if (resultsAction != null && resultsAction.equals(action)) {
7337                    // If this action was explicitly requested, then don't
7338                    // remove things that have it.
7339                    action = null;
7340                }
7341
7342                ResolveInfo ri = null;
7343                ActivityInfo ai = null;
7344
7345                ComponentName comp = sintent.getComponent();
7346                if (comp == null) {
7347                    ri = resolveIntent(
7348                        sintent,
7349                        specificTypes != null ? specificTypes[i] : null,
7350                            flags, userId);
7351                    if (ri == null) {
7352                        continue;
7353                    }
7354                    if (ri == mResolveInfo) {
7355                        // ACK!  Must do something better with this.
7356                    }
7357                    ai = ri.activityInfo;
7358                    comp = new ComponentName(ai.applicationInfo.packageName,
7359                            ai.name);
7360                } else {
7361                    ai = getActivityInfo(comp, flags, userId);
7362                    if (ai == null) {
7363                        continue;
7364                    }
7365                }
7366
7367                // Look for any generic query activities that are duplicates
7368                // of this specific one, and remove them from the results.
7369                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7370                N = results.size();
7371                int j;
7372                for (j=specificsPos; j<N; j++) {
7373                    ResolveInfo sri = results.get(j);
7374                    if ((sri.activityInfo.name.equals(comp.getClassName())
7375                            && sri.activityInfo.applicationInfo.packageName.equals(
7376                                    comp.getPackageName()))
7377                        || (action != null && sri.filter.matchAction(action))) {
7378                        results.remove(j);
7379                        if (DEBUG_INTENT_MATCHING) Log.v(
7380                            TAG, "Removing duplicate item from " + j
7381                            + " due to specific " + specificsPos);
7382                        if (ri == null) {
7383                            ri = sri;
7384                        }
7385                        j--;
7386                        N--;
7387                    }
7388                }
7389
7390                // Add this specific item to its proper place.
7391                if (ri == null) {
7392                    ri = new ResolveInfo();
7393                    ri.activityInfo = ai;
7394                }
7395                results.add(specificsPos, ri);
7396                ri.specificIndex = i;
7397                specificsPos++;
7398            }
7399        }
7400
7401        // Now we go through the remaining generic results and remove any
7402        // duplicate actions that are found here.
7403        N = results.size();
7404        for (int i=specificsPos; i<N-1; i++) {
7405            final ResolveInfo rii = results.get(i);
7406            if (rii.filter == null) {
7407                continue;
7408            }
7409
7410            // Iterate over all of the actions of this result's intent
7411            // filter...  typically this should be just one.
7412            final Iterator<String> it = rii.filter.actionsIterator();
7413            if (it == null) {
7414                continue;
7415            }
7416            while (it.hasNext()) {
7417                final String action = it.next();
7418                if (resultsAction != null && resultsAction.equals(action)) {
7419                    // If this action was explicitly requested, then don't
7420                    // remove things that have it.
7421                    continue;
7422                }
7423                for (int j=i+1; j<N; j++) {
7424                    final ResolveInfo rij = results.get(j);
7425                    if (rij.filter != null && rij.filter.hasAction(action)) {
7426                        results.remove(j);
7427                        if (DEBUG_INTENT_MATCHING) Log.v(
7428                            TAG, "Removing duplicate item from " + j
7429                            + " due to action " + action + " at " + i);
7430                        j--;
7431                        N--;
7432                    }
7433                }
7434            }
7435
7436            // If the caller didn't request filter information, drop it now
7437            // so we don't have to marshall/unmarshall it.
7438            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7439                rii.filter = null;
7440            }
7441        }
7442
7443        // Filter out the caller activity if so requested.
7444        if (caller != null) {
7445            N = results.size();
7446            for (int i=0; i<N; i++) {
7447                ActivityInfo ainfo = results.get(i).activityInfo;
7448                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7449                        && caller.getClassName().equals(ainfo.name)) {
7450                    results.remove(i);
7451                    break;
7452                }
7453            }
7454        }
7455
7456        // If the caller didn't request filter information,
7457        // drop them now so we don't have to
7458        // marshall/unmarshall it.
7459        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7460            N = results.size();
7461            for (int i=0; i<N; i++) {
7462                results.get(i).filter = null;
7463            }
7464        }
7465
7466        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7467        return results;
7468    }
7469
7470    @Override
7471    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7472            String resolvedType, int flags, int userId) {
7473        return new ParceledListSlice<>(
7474                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7475                        false /*allowDynamicSplits*/));
7476    }
7477
7478    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7479            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7480        if (!sUserManager.exists(userId)) return Collections.emptyList();
7481        final int callingUid = Binder.getCallingUid();
7482        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7483                false /*requireFullPermission*/, false /*checkShell*/,
7484                "query intent receivers");
7485        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7486        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7487                false /*includeInstantApps*/);
7488        ComponentName comp = intent.getComponent();
7489        if (comp == null) {
7490            if (intent.getSelector() != null) {
7491                intent = intent.getSelector();
7492                comp = intent.getComponent();
7493            }
7494        }
7495        if (comp != null) {
7496            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7497            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7498            if (ai != null) {
7499                // When specifying an explicit component, we prevent the activity from being
7500                // used when either 1) the calling package is normal and the activity is within
7501                // an instant application or 2) the calling package is ephemeral and the
7502                // activity is not visible to instant applications.
7503                final boolean matchInstantApp =
7504                        (flags & PackageManager.MATCH_INSTANT) != 0;
7505                final boolean matchVisibleToInstantAppOnly =
7506                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7507                final boolean matchExplicitlyVisibleOnly =
7508                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7509                final boolean isCallerInstantApp =
7510                        instantAppPkgName != null;
7511                final boolean isTargetSameInstantApp =
7512                        comp.getPackageName().equals(instantAppPkgName);
7513                final boolean isTargetInstantApp =
7514                        (ai.applicationInfo.privateFlags
7515                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7516                final boolean isTargetVisibleToInstantApp =
7517                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7518                final boolean isTargetExplicitlyVisibleToInstantApp =
7519                        isTargetVisibleToInstantApp
7520                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7521                final boolean isTargetHiddenFromInstantApp =
7522                        !isTargetVisibleToInstantApp
7523                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7524                final boolean blockResolution =
7525                        !isTargetSameInstantApp
7526                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7527                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7528                                        && isTargetHiddenFromInstantApp));
7529                if (!blockResolution) {
7530                    ResolveInfo ri = new ResolveInfo();
7531                    ri.activityInfo = ai;
7532                    list.add(ri);
7533                }
7534            }
7535            return applyPostResolutionFilter(
7536                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7537        }
7538
7539        // reader
7540        synchronized (mPackages) {
7541            String pkgName = intent.getPackage();
7542            if (pkgName == null) {
7543                final List<ResolveInfo> result =
7544                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7545                return applyPostResolutionFilter(
7546                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7547            }
7548            final PackageParser.Package pkg = mPackages.get(pkgName);
7549            if (pkg != null) {
7550                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7551                        intent, resolvedType, flags, pkg.receivers, userId);
7552                return applyPostResolutionFilter(
7553                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7554            }
7555            return Collections.emptyList();
7556        }
7557    }
7558
7559    @Override
7560    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7561        final int callingUid = Binder.getCallingUid();
7562        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7563    }
7564
7565    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7566            int userId, int callingUid) {
7567        if (!sUserManager.exists(userId)) return null;
7568        flags = updateFlagsForResolve(
7569                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7570        List<ResolveInfo> query = queryIntentServicesInternal(
7571                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7572        if (query != null) {
7573            if (query.size() >= 1) {
7574                // If there is more than one service with the same priority,
7575                // just arbitrarily pick the first one.
7576                return query.get(0);
7577            }
7578        }
7579        return null;
7580    }
7581
7582    @Override
7583    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7584            String resolvedType, int flags, int userId) {
7585        final int callingUid = Binder.getCallingUid();
7586        return new ParceledListSlice<>(queryIntentServicesInternal(
7587                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7588    }
7589
7590    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7591            String resolvedType, int flags, int userId, int callingUid,
7592            boolean includeInstantApps) {
7593        if (!sUserManager.exists(userId)) return Collections.emptyList();
7594        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7595                false /*requireFullPermission*/, false /*checkShell*/,
7596                "query intent receivers");
7597        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7598        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7599        ComponentName comp = intent.getComponent();
7600        if (comp == null) {
7601            if (intent.getSelector() != null) {
7602                intent = intent.getSelector();
7603                comp = intent.getComponent();
7604            }
7605        }
7606        if (comp != null) {
7607            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7608            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7609            if (si != null) {
7610                // When specifying an explicit component, we prevent the service from being
7611                // used when either 1) the service is in an instant application and the
7612                // caller is not the same instant application or 2) the calling package is
7613                // ephemeral and the activity is not visible to ephemeral applications.
7614                final boolean matchInstantApp =
7615                        (flags & PackageManager.MATCH_INSTANT) != 0;
7616                final boolean matchVisibleToInstantAppOnly =
7617                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7618                final boolean isCallerInstantApp =
7619                        instantAppPkgName != null;
7620                final boolean isTargetSameInstantApp =
7621                        comp.getPackageName().equals(instantAppPkgName);
7622                final boolean isTargetInstantApp =
7623                        (si.applicationInfo.privateFlags
7624                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7625                final boolean isTargetHiddenFromInstantApp =
7626                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7627                final boolean blockResolution =
7628                        !isTargetSameInstantApp
7629                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7630                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7631                                        && isTargetHiddenFromInstantApp));
7632                if (!blockResolution) {
7633                    final ResolveInfo ri = new ResolveInfo();
7634                    ri.serviceInfo = si;
7635                    list.add(ri);
7636                }
7637            }
7638            return list;
7639        }
7640
7641        // reader
7642        synchronized (mPackages) {
7643            String pkgName = intent.getPackage();
7644            if (pkgName == null) {
7645                return applyPostServiceResolutionFilter(
7646                        mServices.queryIntent(intent, resolvedType, flags, userId),
7647                        instantAppPkgName);
7648            }
7649            final PackageParser.Package pkg = mPackages.get(pkgName);
7650            if (pkg != null) {
7651                return applyPostServiceResolutionFilter(
7652                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7653                                userId),
7654                        instantAppPkgName);
7655            }
7656            return Collections.emptyList();
7657        }
7658    }
7659
7660    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7661            String instantAppPkgName) {
7662        if (instantAppPkgName == null) {
7663            return resolveInfos;
7664        }
7665        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7666            final ResolveInfo info = resolveInfos.get(i);
7667            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7668            // allow services that are defined in the provided package
7669            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7670                if (info.serviceInfo.splitName != null
7671                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7672                                info.serviceInfo.splitName)) {
7673                    // requested service is defined in a split that hasn't been installed yet.
7674                    // add the installer to the resolve list
7675                    if (DEBUG_INSTANT) {
7676                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7677                    }
7678                    final ResolveInfo installerInfo = new ResolveInfo(
7679                            mInstantAppInstallerInfo);
7680                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7681                            null /* installFailureActivity */,
7682                            info.serviceInfo.packageName,
7683                            info.serviceInfo.applicationInfo.versionCode,
7684                            info.serviceInfo.splitName);
7685                    // add a non-generic filter
7686                    installerInfo.filter = new IntentFilter();
7687                    // load resources from the correct package
7688                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7689                    resolveInfos.set(i, installerInfo);
7690                }
7691                continue;
7692            }
7693            // allow services that have been explicitly exposed to ephemeral apps
7694            if (!isEphemeralApp
7695                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7696                continue;
7697            }
7698            resolveInfos.remove(i);
7699        }
7700        return resolveInfos;
7701    }
7702
7703    @Override
7704    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7705            String resolvedType, int flags, int userId) {
7706        return new ParceledListSlice<>(
7707                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7708    }
7709
7710    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7711            Intent intent, String resolvedType, int flags, int userId) {
7712        if (!sUserManager.exists(userId)) return Collections.emptyList();
7713        final int callingUid = Binder.getCallingUid();
7714        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7715        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7716                false /*includeInstantApps*/);
7717        ComponentName comp = intent.getComponent();
7718        if (comp == null) {
7719            if (intent.getSelector() != null) {
7720                intent = intent.getSelector();
7721                comp = intent.getComponent();
7722            }
7723        }
7724        if (comp != null) {
7725            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7726            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7727            if (pi != null) {
7728                // When specifying an explicit component, we prevent the provider from being
7729                // used when either 1) the provider is in an instant application and the
7730                // caller is not the same instant application or 2) the calling package is an
7731                // instant application and the provider is not visible to instant applications.
7732                final boolean matchInstantApp =
7733                        (flags & PackageManager.MATCH_INSTANT) != 0;
7734                final boolean matchVisibleToInstantAppOnly =
7735                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7736                final boolean isCallerInstantApp =
7737                        instantAppPkgName != null;
7738                final boolean isTargetSameInstantApp =
7739                        comp.getPackageName().equals(instantAppPkgName);
7740                final boolean isTargetInstantApp =
7741                        (pi.applicationInfo.privateFlags
7742                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7743                final boolean isTargetHiddenFromInstantApp =
7744                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7745                final boolean blockResolution =
7746                        !isTargetSameInstantApp
7747                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7748                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7749                                        && isTargetHiddenFromInstantApp));
7750                if (!blockResolution) {
7751                    final ResolveInfo ri = new ResolveInfo();
7752                    ri.providerInfo = pi;
7753                    list.add(ri);
7754                }
7755            }
7756            return list;
7757        }
7758
7759        // reader
7760        synchronized (mPackages) {
7761            String pkgName = intent.getPackage();
7762            if (pkgName == null) {
7763                return applyPostContentProviderResolutionFilter(
7764                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7765                        instantAppPkgName);
7766            }
7767            final PackageParser.Package pkg = mPackages.get(pkgName);
7768            if (pkg != null) {
7769                return applyPostContentProviderResolutionFilter(
7770                        mProviders.queryIntentForPackage(
7771                        intent, resolvedType, flags, pkg.providers, userId),
7772                        instantAppPkgName);
7773            }
7774            return Collections.emptyList();
7775        }
7776    }
7777
7778    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7779            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7780        if (instantAppPkgName == null) {
7781            return resolveInfos;
7782        }
7783        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7784            final ResolveInfo info = resolveInfos.get(i);
7785            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7786            // allow providers that are defined in the provided package
7787            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7788                if (info.providerInfo.splitName != null
7789                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7790                                info.providerInfo.splitName)) {
7791                    // requested provider is defined in a split that hasn't been installed yet.
7792                    // add the installer to the resolve list
7793                    if (DEBUG_INSTANT) {
7794                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7795                    }
7796                    final ResolveInfo installerInfo = new ResolveInfo(
7797                            mInstantAppInstallerInfo);
7798                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7799                            null /*failureActivity*/,
7800                            info.providerInfo.packageName,
7801                            info.providerInfo.applicationInfo.versionCode,
7802                            info.providerInfo.splitName);
7803                    // add a non-generic filter
7804                    installerInfo.filter = new IntentFilter();
7805                    // load resources from the correct package
7806                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7807                    resolveInfos.set(i, installerInfo);
7808                }
7809                continue;
7810            }
7811            // allow providers that have been explicitly exposed to instant applications
7812            if (!isEphemeralApp
7813                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7814                continue;
7815            }
7816            resolveInfos.remove(i);
7817        }
7818        return resolveInfos;
7819    }
7820
7821    @Override
7822    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7823        final int callingUid = Binder.getCallingUid();
7824        if (getInstantAppPackageName(callingUid) != null) {
7825            return ParceledListSlice.emptyList();
7826        }
7827        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7828        flags = updateFlagsForPackage(flags, userId, null);
7829        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7830        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7831                true /* requireFullPermission */, false /* checkShell */,
7832                "get installed packages");
7833
7834        // writer
7835        synchronized (mPackages) {
7836            ArrayList<PackageInfo> list;
7837            if (listUninstalled) {
7838                list = new ArrayList<>(mSettings.mPackages.size());
7839                for (PackageSetting ps : mSettings.mPackages.values()) {
7840                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7841                        continue;
7842                    }
7843                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7844                        continue;
7845                    }
7846                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7847                    if (pi != null) {
7848                        list.add(pi);
7849                    }
7850                }
7851            } else {
7852                list = new ArrayList<>(mPackages.size());
7853                for (PackageParser.Package p : mPackages.values()) {
7854                    final PackageSetting ps = (PackageSetting) p.mExtras;
7855                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7856                        continue;
7857                    }
7858                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7859                        continue;
7860                    }
7861                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7862                            p.mExtras, flags, userId);
7863                    if (pi != null) {
7864                        list.add(pi);
7865                    }
7866                }
7867            }
7868
7869            return new ParceledListSlice<>(list);
7870        }
7871    }
7872
7873    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7874            String[] permissions, boolean[] tmp, int flags, int userId) {
7875        int numMatch = 0;
7876        final PermissionsState permissionsState = ps.getPermissionsState();
7877        for (int i=0; i<permissions.length; i++) {
7878            final String permission = permissions[i];
7879            if (permissionsState.hasPermission(permission, userId)) {
7880                tmp[i] = true;
7881                numMatch++;
7882            } else {
7883                tmp[i] = false;
7884            }
7885        }
7886        if (numMatch == 0) {
7887            return;
7888        }
7889        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7890
7891        // The above might return null in cases of uninstalled apps or install-state
7892        // skew across users/profiles.
7893        if (pi != null) {
7894            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7895                if (numMatch == permissions.length) {
7896                    pi.requestedPermissions = permissions;
7897                } else {
7898                    pi.requestedPermissions = new String[numMatch];
7899                    numMatch = 0;
7900                    for (int i=0; i<permissions.length; i++) {
7901                        if (tmp[i]) {
7902                            pi.requestedPermissions[numMatch] = permissions[i];
7903                            numMatch++;
7904                        }
7905                    }
7906                }
7907            }
7908            list.add(pi);
7909        }
7910    }
7911
7912    @Override
7913    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7914            String[] permissions, int flags, int userId) {
7915        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7916        flags = updateFlagsForPackage(flags, userId, permissions);
7917        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7918                true /* requireFullPermission */, false /* checkShell */,
7919                "get packages holding permissions");
7920        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7921
7922        // writer
7923        synchronized (mPackages) {
7924            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7925            boolean[] tmpBools = new boolean[permissions.length];
7926            if (listUninstalled) {
7927                for (PackageSetting ps : mSettings.mPackages.values()) {
7928                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7929                            userId);
7930                }
7931            } else {
7932                for (PackageParser.Package pkg : mPackages.values()) {
7933                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7934                    if (ps != null) {
7935                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7936                                userId);
7937                    }
7938                }
7939            }
7940
7941            return new ParceledListSlice<PackageInfo>(list);
7942        }
7943    }
7944
7945    @Override
7946    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7947        final int callingUid = Binder.getCallingUid();
7948        if (getInstantAppPackageName(callingUid) != null) {
7949            return ParceledListSlice.emptyList();
7950        }
7951        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7952        flags = updateFlagsForApplication(flags, userId, null);
7953        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7954
7955        // writer
7956        synchronized (mPackages) {
7957            ArrayList<ApplicationInfo> list;
7958            if (listUninstalled) {
7959                list = new ArrayList<>(mSettings.mPackages.size());
7960                for (PackageSetting ps : mSettings.mPackages.values()) {
7961                    ApplicationInfo ai;
7962                    int effectiveFlags = flags;
7963                    if (ps.isSystem()) {
7964                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7965                    }
7966                    if (ps.pkg != null) {
7967                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7968                            continue;
7969                        }
7970                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7971                            continue;
7972                        }
7973                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7974                                ps.readUserState(userId), userId);
7975                        if (ai != null) {
7976                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7977                        }
7978                    } else {
7979                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7980                        // and already converts to externally visible package name
7981                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7982                                callingUid, effectiveFlags, userId);
7983                    }
7984                    if (ai != null) {
7985                        list.add(ai);
7986                    }
7987                }
7988            } else {
7989                list = new ArrayList<>(mPackages.size());
7990                for (PackageParser.Package p : mPackages.values()) {
7991                    if (p.mExtras != null) {
7992                        PackageSetting ps = (PackageSetting) p.mExtras;
7993                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7994                            continue;
7995                        }
7996                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7997                            continue;
7998                        }
7999                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8000                                ps.readUserState(userId), userId);
8001                        if (ai != null) {
8002                            ai.packageName = resolveExternalPackageNameLPr(p);
8003                            list.add(ai);
8004                        }
8005                    }
8006                }
8007            }
8008
8009            return new ParceledListSlice<>(list);
8010        }
8011    }
8012
8013    @Override
8014    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8015        if (HIDE_EPHEMERAL_APIS) {
8016            return null;
8017        }
8018        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8019            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8020                    "getEphemeralApplications");
8021        }
8022        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8023                true /* requireFullPermission */, false /* checkShell */,
8024                "getEphemeralApplications");
8025        synchronized (mPackages) {
8026            List<InstantAppInfo> instantApps = mInstantAppRegistry
8027                    .getInstantAppsLPr(userId);
8028            if (instantApps != null) {
8029                return new ParceledListSlice<>(instantApps);
8030            }
8031        }
8032        return null;
8033    }
8034
8035    @Override
8036    public boolean isInstantApp(String packageName, int userId) {
8037        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8038                true /* requireFullPermission */, false /* checkShell */,
8039                "isInstantApp");
8040        if (HIDE_EPHEMERAL_APIS) {
8041            return false;
8042        }
8043
8044        synchronized (mPackages) {
8045            int callingUid = Binder.getCallingUid();
8046            if (Process.isIsolated(callingUid)) {
8047                callingUid = mIsolatedOwners.get(callingUid);
8048            }
8049            final PackageSetting ps = mSettings.mPackages.get(packageName);
8050            PackageParser.Package pkg = mPackages.get(packageName);
8051            final boolean returnAllowed =
8052                    ps != null
8053                    && (isCallerSameApp(packageName, callingUid)
8054                            || canViewInstantApps(callingUid, userId)
8055                            || mInstantAppRegistry.isInstantAccessGranted(
8056                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8057            if (returnAllowed) {
8058                return ps.getInstantApp(userId);
8059            }
8060        }
8061        return false;
8062    }
8063
8064    @Override
8065    public byte[] getInstantAppCookie(String packageName, int userId) {
8066        if (HIDE_EPHEMERAL_APIS) {
8067            return null;
8068        }
8069
8070        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8071                true /* requireFullPermission */, false /* checkShell */,
8072                "getInstantAppCookie");
8073        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8074            return null;
8075        }
8076        synchronized (mPackages) {
8077            return mInstantAppRegistry.getInstantAppCookieLPw(
8078                    packageName, userId);
8079        }
8080    }
8081
8082    @Override
8083    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8084        if (HIDE_EPHEMERAL_APIS) {
8085            return true;
8086        }
8087
8088        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8089                true /* requireFullPermission */, true /* checkShell */,
8090                "setInstantAppCookie");
8091        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8092            return false;
8093        }
8094        synchronized (mPackages) {
8095            return mInstantAppRegistry.setInstantAppCookieLPw(
8096                    packageName, cookie, userId);
8097        }
8098    }
8099
8100    @Override
8101    public Bitmap getInstantAppIcon(String packageName, int userId) {
8102        if (HIDE_EPHEMERAL_APIS) {
8103            return null;
8104        }
8105
8106        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8107            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8108                    "getInstantAppIcon");
8109        }
8110        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8111                true /* requireFullPermission */, false /* checkShell */,
8112                "getInstantAppIcon");
8113
8114        synchronized (mPackages) {
8115            return mInstantAppRegistry.getInstantAppIconLPw(
8116                    packageName, userId);
8117        }
8118    }
8119
8120    private boolean isCallerSameApp(String packageName, int uid) {
8121        PackageParser.Package pkg = mPackages.get(packageName);
8122        return pkg != null
8123                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8124    }
8125
8126    @Override
8127    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8128        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8129            return ParceledListSlice.emptyList();
8130        }
8131        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8132    }
8133
8134    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8135        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8136
8137        // reader
8138        synchronized (mPackages) {
8139            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8140            final int userId = UserHandle.getCallingUserId();
8141            while (i.hasNext()) {
8142                final PackageParser.Package p = i.next();
8143                if (p.applicationInfo == null) continue;
8144
8145                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8146                        && !p.applicationInfo.isDirectBootAware();
8147                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8148                        && p.applicationInfo.isDirectBootAware();
8149
8150                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8151                        && (!mSafeMode || isSystemApp(p))
8152                        && (matchesUnaware || matchesAware)) {
8153                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8154                    if (ps != null) {
8155                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8156                                ps.readUserState(userId), userId);
8157                        if (ai != null) {
8158                            finalList.add(ai);
8159                        }
8160                    }
8161                }
8162            }
8163        }
8164
8165        return finalList;
8166    }
8167
8168    @Override
8169    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8170        return resolveContentProviderInternal(name, flags, userId);
8171    }
8172
8173    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8174        if (!sUserManager.exists(userId)) return null;
8175        flags = updateFlagsForComponent(flags, userId, name);
8176        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8177        // reader
8178        synchronized (mPackages) {
8179            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8180            PackageSetting ps = provider != null
8181                    ? mSettings.mPackages.get(provider.owner.packageName)
8182                    : null;
8183            if (ps != null) {
8184                final boolean isInstantApp = ps.getInstantApp(userId);
8185                // normal application; filter out instant application provider
8186                if (instantAppPkgName == null && isInstantApp) {
8187                    return null;
8188                }
8189                // instant application; filter out other instant applications
8190                if (instantAppPkgName != null
8191                        && isInstantApp
8192                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8193                    return null;
8194                }
8195                // instant application; filter out non-exposed provider
8196                if (instantAppPkgName != null
8197                        && !isInstantApp
8198                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8199                    return null;
8200                }
8201                // provider not enabled
8202                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8203                    return null;
8204                }
8205                return PackageParser.generateProviderInfo(
8206                        provider, flags, ps.readUserState(userId), userId);
8207            }
8208            return null;
8209        }
8210    }
8211
8212    /**
8213     * @deprecated
8214     */
8215    @Deprecated
8216    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8217        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8218            return;
8219        }
8220        // reader
8221        synchronized (mPackages) {
8222            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8223                    .entrySet().iterator();
8224            final int userId = UserHandle.getCallingUserId();
8225            while (i.hasNext()) {
8226                Map.Entry<String, PackageParser.Provider> entry = i.next();
8227                PackageParser.Provider p = entry.getValue();
8228                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8229
8230                if (ps != null && p.syncable
8231                        && (!mSafeMode || (p.info.applicationInfo.flags
8232                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8233                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8234                            ps.readUserState(userId), userId);
8235                    if (info != null) {
8236                        outNames.add(entry.getKey());
8237                        outInfo.add(info);
8238                    }
8239                }
8240            }
8241        }
8242    }
8243
8244    @Override
8245    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8246            int uid, int flags, String metaDataKey) {
8247        final int callingUid = Binder.getCallingUid();
8248        final int userId = processName != null ? UserHandle.getUserId(uid)
8249                : UserHandle.getCallingUserId();
8250        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8251        flags = updateFlagsForComponent(flags, userId, processName);
8252        ArrayList<ProviderInfo> finalList = null;
8253        // reader
8254        synchronized (mPackages) {
8255            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8256            while (i.hasNext()) {
8257                final PackageParser.Provider p = i.next();
8258                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8259                if (ps != null && p.info.authority != null
8260                        && (processName == null
8261                                || (p.info.processName.equals(processName)
8262                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8263                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8264
8265                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8266                    // parameter.
8267                    if (metaDataKey != null
8268                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8269                        continue;
8270                    }
8271                    final ComponentName component =
8272                            new ComponentName(p.info.packageName, p.info.name);
8273                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8274                        continue;
8275                    }
8276                    if (finalList == null) {
8277                        finalList = new ArrayList<ProviderInfo>(3);
8278                    }
8279                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8280                            ps.readUserState(userId), userId);
8281                    if (info != null) {
8282                        finalList.add(info);
8283                    }
8284                }
8285            }
8286        }
8287
8288        if (finalList != null) {
8289            Collections.sort(finalList, mProviderInitOrderSorter);
8290            return new ParceledListSlice<ProviderInfo>(finalList);
8291        }
8292
8293        return ParceledListSlice.emptyList();
8294    }
8295
8296    @Override
8297    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8298        // reader
8299        synchronized (mPackages) {
8300            final int callingUid = Binder.getCallingUid();
8301            final int callingUserId = UserHandle.getUserId(callingUid);
8302            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8303            if (ps == null) return null;
8304            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8305                return null;
8306            }
8307            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8308            return PackageParser.generateInstrumentationInfo(i, flags);
8309        }
8310    }
8311
8312    @Override
8313    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8314            String targetPackage, int flags) {
8315        final int callingUid = Binder.getCallingUid();
8316        final int callingUserId = UserHandle.getUserId(callingUid);
8317        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8318        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8319            return ParceledListSlice.emptyList();
8320        }
8321        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8322    }
8323
8324    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8325            int flags) {
8326        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8327
8328        // reader
8329        synchronized (mPackages) {
8330            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8331            while (i.hasNext()) {
8332                final PackageParser.Instrumentation p = i.next();
8333                if (targetPackage == null
8334                        || targetPackage.equals(p.info.targetPackage)) {
8335                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8336                            flags);
8337                    if (ii != null) {
8338                        finalList.add(ii);
8339                    }
8340                }
8341            }
8342        }
8343
8344        return finalList;
8345    }
8346
8347    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8348        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8349        try {
8350            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8351        } finally {
8352            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8353        }
8354    }
8355
8356    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8357        final File[] files = scanDir.listFiles();
8358        if (ArrayUtils.isEmpty(files)) {
8359            Log.d(TAG, "No files in app dir " + scanDir);
8360            return;
8361        }
8362
8363        if (DEBUG_PACKAGE_SCANNING) {
8364            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8365                    + " flags=0x" + Integer.toHexString(parseFlags));
8366        }
8367        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8368                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8369                mParallelPackageParserCallback)) {
8370            // Submit files for parsing in parallel
8371            int fileCount = 0;
8372            for (File file : files) {
8373                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8374                        && !PackageInstallerService.isStageName(file.getName());
8375                if (!isPackage) {
8376                    // Ignore entries which are not packages
8377                    continue;
8378                }
8379                parallelPackageParser.submit(file, parseFlags);
8380                fileCount++;
8381            }
8382
8383            // Process results one by one
8384            for (; fileCount > 0; fileCount--) {
8385                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8386                Throwable throwable = parseResult.throwable;
8387                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8388
8389                if (throwable == null) {
8390                    // TODO(toddke): move lower in the scan chain
8391                    // Static shared libraries have synthetic package names
8392                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8393                        renameStaticSharedLibraryPackage(parseResult.pkg);
8394                    }
8395                    try {
8396                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8397                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8398                                    currentTime, null);
8399                        }
8400                    } catch (PackageManagerException e) {
8401                        errorCode = e.error;
8402                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8403                    }
8404                } else if (throwable instanceof PackageParser.PackageParserException) {
8405                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8406                            throwable;
8407                    errorCode = e.error;
8408                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8409                } else {
8410                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8411                            + parseResult.scanFile, throwable);
8412                }
8413
8414                // Delete invalid userdata apps
8415                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8416                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8417                    logCriticalInfo(Log.WARN,
8418                            "Deleting invalid package at " + parseResult.scanFile);
8419                    removeCodePathLI(parseResult.scanFile);
8420                }
8421            }
8422        }
8423    }
8424
8425    public static void reportSettingsProblem(int priority, String msg) {
8426        logCriticalInfo(priority, msg);
8427    }
8428
8429    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8430            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8431        // When upgrading from pre-N MR1, verify the package time stamp using the package
8432        // directory and not the APK file.
8433        final long lastModifiedTime = mIsPreNMR1Upgrade
8434                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8435        if (ps != null && !forceCollect
8436                && ps.codePathString.equals(pkg.codePath)
8437                && ps.timeStamp == lastModifiedTime
8438                && !isCompatSignatureUpdateNeeded(pkg)
8439                && !isRecoverSignatureUpdateNeeded(pkg)) {
8440            if (ps.signatures.mSigningDetails.signatures != null
8441                    && ps.signatures.mSigningDetails.signatures.length != 0
8442                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8443                            != SignatureSchemeVersion.UNKNOWN) {
8444                // Optimization: reuse the existing cached signing data
8445                // if the package appears to be unchanged.
8446                pkg.mSigningDetails =
8447                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8448                return;
8449            }
8450
8451            Slog.w(TAG, "PackageSetting for " + ps.name
8452                    + " is missing signatures.  Collecting certs again to recover them.");
8453        } else {
8454            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8455                    (forceCollect ? " (forced)" : ""));
8456        }
8457
8458        try {
8459            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8460            PackageParser.collectCertificates(pkg, skipVerify);
8461        } catch (PackageParserException e) {
8462            throw PackageManagerException.from(e);
8463        } finally {
8464            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8465        }
8466    }
8467
8468    /**
8469     *  Traces a package scan.
8470     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8471     */
8472    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8473            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8474        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8475        try {
8476            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8477        } finally {
8478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8479        }
8480    }
8481
8482    /**
8483     *  Scans a package and returns the newly parsed package.
8484     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8485     */
8486    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8487            long currentTime, UserHandle user) throws PackageManagerException {
8488        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8489        PackageParser pp = new PackageParser();
8490        pp.setSeparateProcesses(mSeparateProcesses);
8491        pp.setOnlyCoreApps(mOnlyCore);
8492        pp.setDisplayMetrics(mMetrics);
8493        pp.setCallback(mPackageParserCallback);
8494
8495        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8496        final PackageParser.Package pkg;
8497        try {
8498            pkg = pp.parsePackage(scanFile, parseFlags);
8499        } catch (PackageParserException e) {
8500            throw PackageManagerException.from(e);
8501        } finally {
8502            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8503        }
8504
8505        // Static shared libraries have synthetic package names
8506        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8507            renameStaticSharedLibraryPackage(pkg);
8508        }
8509
8510        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8511    }
8512
8513    /**
8514     *  Scans a package and returns the newly parsed package.
8515     *  @throws PackageManagerException on a parse error.
8516     */
8517    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8518            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8519            @Nullable UserHandle user)
8520                    throws PackageManagerException {
8521        // If the package has children and this is the first dive in the function
8522        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8523        // packages (parent and children) would be successfully scanned before the
8524        // actual scan since scanning mutates internal state and we want to atomically
8525        // install the package and its children.
8526        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8527            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8528                scanFlags |= SCAN_CHECK_ONLY;
8529            }
8530        } else {
8531            scanFlags &= ~SCAN_CHECK_ONLY;
8532        }
8533
8534        // Scan the parent
8535        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8536                scanFlags, currentTime, user);
8537
8538        // Scan the children
8539        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8540        for (int i = 0; i < childCount; i++) {
8541            PackageParser.Package childPackage = pkg.childPackages.get(i);
8542            addForInitLI(childPackage, parseFlags, scanFlags,
8543                    currentTime, user);
8544        }
8545
8546
8547        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8548            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8549        }
8550
8551        return scannedPkg;
8552    }
8553
8554    /**
8555     * Returns if full apk verification can be skipped for the whole package, including the splits.
8556     */
8557    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8558        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8559            return false;
8560        }
8561        // TODO: Allow base and splits to be verified individually.
8562        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8563            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8564                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8565                    return false;
8566                }
8567            }
8568        }
8569        return true;
8570    }
8571
8572    /**
8573     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8574     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8575     * match one in a trusted source, and should be done separately.
8576     */
8577    private boolean canSkipFullApkVerification(String apkPath) {
8578        byte[] rootHashObserved = null;
8579        try {
8580            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8581            if (rootHashObserved == null) {
8582                return false;  // APK does not contain Merkle tree root hash.
8583            }
8584            synchronized (mInstallLock) {
8585                // Returns whether the observed root hash matches what kernel has.
8586                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8587                return true;
8588            }
8589        } catch (InstallerException | IOException | DigestException |
8590                NoSuchAlgorithmException e) {
8591            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8592        }
8593        return false;
8594    }
8595
8596    /**
8597     * Adds a new package to the internal data structures during platform initialization.
8598     * <p>After adding, the package is known to the system and available for querying.
8599     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8600     * etc...], additional checks are performed. Basic verification [such as ensuring
8601     * matching signatures, checking version codes, etc...] occurs if the package is
8602     * identical to a previously known package. If the package fails a signature check,
8603     * the version installed on /data will be removed. If the version of the new package
8604     * is less than or equal than the version on /data, it will be ignored.
8605     * <p>Regardless of the package location, the results are applied to the internal
8606     * structures and the package is made available to the rest of the system.
8607     * <p>NOTE: The return value should be removed. It's the passed in package object.
8608     */
8609    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8610            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8611            @Nullable UserHandle user)
8612                    throws PackageManagerException {
8613        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8614        final String renamedPkgName;
8615        final PackageSetting disabledPkgSetting;
8616        final boolean isSystemPkgUpdated;
8617        final boolean pkgAlreadyExists;
8618        PackageSetting pkgSetting;
8619
8620        // NOTE: installPackageLI() has the same code to setup the package's
8621        // application info. This probably should be done lower in the call
8622        // stack [such as scanPackageOnly()]. However, we verify the application
8623        // info prior to that [in scanPackageNew()] and thus have to setup
8624        // the application info early.
8625        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8626        pkg.setApplicationInfoCodePath(pkg.codePath);
8627        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8628        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8629        pkg.setApplicationInfoResourcePath(pkg.codePath);
8630        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8631        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8632
8633        synchronized (mPackages) {
8634            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8635            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8636            if (realPkgName != null) {
8637                ensurePackageRenamed(pkg, renamedPkgName);
8638            }
8639            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8640            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8641            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8642            pkgAlreadyExists = pkgSetting != null;
8643            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8644            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8645            isSystemPkgUpdated = disabledPkgSetting != null;
8646
8647            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8648                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8649            }
8650
8651            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8652                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8653                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8654                    : null;
8655            if (DEBUG_PACKAGE_SCANNING
8656                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8657                    && sharedUserSetting != null) {
8658                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8659                        + " (uid=" + sharedUserSetting.userId + "):"
8660                        + " packages=" + sharedUserSetting.packages);
8661            }
8662
8663            if (scanSystemPartition) {
8664                // Potentially prune child packages. If the application on the /system
8665                // partition has been updated via OTA, but, is still disabled by a
8666                // version on /data, cycle through all of its children packages and
8667                // remove children that are no longer defined.
8668                if (isSystemPkgUpdated) {
8669                    final int scannedChildCount = (pkg.childPackages != null)
8670                            ? pkg.childPackages.size() : 0;
8671                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8672                            ? disabledPkgSetting.childPackageNames.size() : 0;
8673                    for (int i = 0; i < disabledChildCount; i++) {
8674                        String disabledChildPackageName =
8675                                disabledPkgSetting.childPackageNames.get(i);
8676                        boolean disabledPackageAvailable = false;
8677                        for (int j = 0; j < scannedChildCount; j++) {
8678                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8679                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8680                                disabledPackageAvailable = true;
8681                                break;
8682                            }
8683                        }
8684                        if (!disabledPackageAvailable) {
8685                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8686                        }
8687                    }
8688                    // we're updating the disabled package, so, scan it as the package setting
8689                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8690                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8691                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8692                            (pkg == mPlatformPackage), user);
8693                    applyPolicy(pkg, parseFlags, scanFlags);
8694                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8695                }
8696            }
8697        }
8698
8699        final boolean newPkgChangedPaths =
8700                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8701        final boolean newPkgVersionGreater =
8702                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8703        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8704                && newPkgChangedPaths && newPkgVersionGreater;
8705        if (isSystemPkgBetter) {
8706            // The version of the application on /system is greater than the version on
8707            // /data. Switch back to the application on /system.
8708            // It's safe to assume the application on /system will correctly scan. If not,
8709            // there won't be a working copy of the application.
8710            synchronized (mPackages) {
8711                // just remove the loaded entries from package lists
8712                mPackages.remove(pkgSetting.name);
8713            }
8714
8715            logCriticalInfo(Log.WARN,
8716                    "System package updated;"
8717                    + " name: " + pkgSetting.name
8718                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8719                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8720
8721            final InstallArgs args = createInstallArgsForExisting(
8722                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8723                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8724            args.cleanUpResourcesLI();
8725            synchronized (mPackages) {
8726                mSettings.enableSystemPackageLPw(pkgSetting.name);
8727            }
8728        }
8729
8730        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8731            // The version of the application on the /system partition is less than or
8732            // equal to the version on the /data partition. Throw an exception and use
8733            // the application already installed on the /data partition.
8734            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8735                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8736                    + " better than this " + pkg.getLongVersionCode());
8737        }
8738
8739        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8740        // force re-collecting certificate.
8741        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8742                disabledPkgSetting);
8743        // Full APK verification can be skipped during certificate collection, only if the file is
8744        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8745        // cases, only data in Signing Block is verified instead of the whole file.
8746        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8747                (forceCollect && canSkipFullPackageVerification(pkg));
8748        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8749
8750        boolean shouldHideSystemApp = false;
8751        // A new application appeared on /system, but, we already have a copy of
8752        // the application installed on /data.
8753        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8754                && !pkgSetting.isSystem()) {
8755
8756            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8757                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8758                logCriticalInfo(Log.WARN,
8759                        "System package signature mismatch;"
8760                        + " name: " + pkgSetting.name);
8761                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8762                        "scanPackageInternalLI")) {
8763                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8764                }
8765                pkgSetting = null;
8766            } else if (newPkgVersionGreater) {
8767                // The application on /system is newer than the application on /data.
8768                // Simply remove the application on /data [keeping application data]
8769                // and replace it with the version on /system.
8770                logCriticalInfo(Log.WARN,
8771                        "System package enabled;"
8772                        + " name: " + pkgSetting.name
8773                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8774                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8775                InstallArgs args = createInstallArgsForExisting(
8776                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8777                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8778                synchronized (mInstallLock) {
8779                    args.cleanUpResourcesLI();
8780                }
8781            } else {
8782                // The application on /system is older than the application on /data. Hide
8783                // the application on /system and the version on /data will be scanned later
8784                // and re-added like an update.
8785                shouldHideSystemApp = true;
8786                logCriticalInfo(Log.INFO,
8787                        "System package disabled;"
8788                        + " name: " + pkgSetting.name
8789                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8790                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8791            }
8792        }
8793
8794        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8795                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8796
8797        if (shouldHideSystemApp) {
8798            synchronized (mPackages) {
8799                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8800            }
8801        }
8802        return scannedPkg;
8803    }
8804
8805    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8806        // Derive the new package synthetic package name
8807        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8808                + pkg.staticSharedLibVersion);
8809    }
8810
8811    private static String fixProcessName(String defProcessName,
8812            String processName) {
8813        if (processName == null) {
8814            return defProcessName;
8815        }
8816        return processName;
8817    }
8818
8819    /**
8820     * Enforces that only the system UID or root's UID can call a method exposed
8821     * via Binder.
8822     *
8823     * @param message used as message if SecurityException is thrown
8824     * @throws SecurityException if the caller is not system or root
8825     */
8826    private static final void enforceSystemOrRoot(String message) {
8827        final int uid = Binder.getCallingUid();
8828        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8829            throw new SecurityException(message);
8830        }
8831    }
8832
8833    @Override
8834    public void performFstrimIfNeeded() {
8835        enforceSystemOrRoot("Only the system can request fstrim");
8836
8837        // Before everything else, see whether we need to fstrim.
8838        try {
8839            IStorageManager sm = PackageHelper.getStorageManager();
8840            if (sm != null) {
8841                boolean doTrim = false;
8842                final long interval = android.provider.Settings.Global.getLong(
8843                        mContext.getContentResolver(),
8844                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8845                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8846                if (interval > 0) {
8847                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8848                    if (timeSinceLast > interval) {
8849                        doTrim = true;
8850                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8851                                + "; running immediately");
8852                    }
8853                }
8854                if (doTrim) {
8855                    final boolean dexOptDialogShown;
8856                    synchronized (mPackages) {
8857                        dexOptDialogShown = mDexOptDialogShown;
8858                    }
8859                    if (!isFirstBoot() && dexOptDialogShown) {
8860                        try {
8861                            ActivityManager.getService().showBootMessage(
8862                                    mContext.getResources().getString(
8863                                            R.string.android_upgrading_fstrim), true);
8864                        } catch (RemoteException e) {
8865                        }
8866                    }
8867                    sm.runMaintenance();
8868                }
8869            } else {
8870                Slog.e(TAG, "storageManager service unavailable!");
8871            }
8872        } catch (RemoteException e) {
8873            // Can't happen; StorageManagerService is local
8874        }
8875    }
8876
8877    @Override
8878    public void updatePackagesIfNeeded() {
8879        enforceSystemOrRoot("Only the system can request package update");
8880
8881        // We need to re-extract after an OTA.
8882        boolean causeUpgrade = isUpgrade();
8883
8884        // First boot or factory reset.
8885        // Note: we also handle devices that are upgrading to N right now as if it is their
8886        //       first boot, as they do not have profile data.
8887        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8888
8889        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8890        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8891
8892        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8893            return;
8894        }
8895
8896        List<PackageParser.Package> pkgs;
8897        synchronized (mPackages) {
8898            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8899        }
8900
8901        final long startTime = System.nanoTime();
8902        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8903                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8904                    false /* bootComplete */);
8905
8906        final int elapsedTimeSeconds =
8907                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8908
8909        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8910        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8911        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8912        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8913        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8914    }
8915
8916    /*
8917     * Return the prebuilt profile path given a package base code path.
8918     */
8919    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8920        return pkg.baseCodePath + ".prof";
8921    }
8922
8923    /**
8924     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8925     * containing statistics about the invocation. The array consists of three elements,
8926     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8927     * and {@code numberOfPackagesFailed}.
8928     */
8929    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8930            final int compilationReason, boolean bootComplete) {
8931
8932        int numberOfPackagesVisited = 0;
8933        int numberOfPackagesOptimized = 0;
8934        int numberOfPackagesSkipped = 0;
8935        int numberOfPackagesFailed = 0;
8936        final int numberOfPackagesToDexopt = pkgs.size();
8937
8938        for (PackageParser.Package pkg : pkgs) {
8939            numberOfPackagesVisited++;
8940
8941            boolean useProfileForDexopt = false;
8942
8943            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8944                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8945                // that are already compiled.
8946                File profileFile = new File(getPrebuildProfilePath(pkg));
8947                // Copy profile if it exists.
8948                if (profileFile.exists()) {
8949                    try {
8950                        // We could also do this lazily before calling dexopt in
8951                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8952                        // is that we don't have a good way to say "do this only once".
8953                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8954                                pkg.applicationInfo.uid, pkg.packageName,
8955                                ArtManager.getProfileName(null))) {
8956                            Log.e(TAG, "Installer failed to copy system profile!");
8957                        } else {
8958                            // Disabled as this causes speed-profile compilation during first boot
8959                            // even if things are already compiled.
8960                            // useProfileForDexopt = true;
8961                        }
8962                    } catch (Exception e) {
8963                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8964                                e);
8965                    }
8966                } else {
8967                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8968                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8969                    // minimize the number off apps being speed-profile compiled during first boot.
8970                    // The other paths will not change the filter.
8971                    if (disabledPs != null && disabledPs.pkg.isStub) {
8972                        // The package is the stub one, remove the stub suffix to get the normal
8973                        // package and APK names.
8974                        String systemProfilePath =
8975                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8976                        profileFile = new File(systemProfilePath);
8977                        // If we have a profile for a compressed APK, copy it to the reference
8978                        // location.
8979                        // Note that copying the profile here will cause it to override the
8980                        // reference profile every OTA even though the existing reference profile
8981                        // may have more data. We can't copy during decompression since the
8982                        // directories are not set up at that point.
8983                        if (profileFile.exists()) {
8984                            try {
8985                                // We could also do this lazily before calling dexopt in
8986                                // PackageDexOptimizer to prevent this happening on first boot. The
8987                                // issue is that we don't have a good way to say "do this only
8988                                // once".
8989                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8990                                        pkg.applicationInfo.uid, pkg.packageName,
8991                                        ArtManager.getProfileName(null))) {
8992                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8993                                } else {
8994                                    useProfileForDexopt = true;
8995                                }
8996                            } catch (Exception e) {
8997                                Log.e(TAG, "Failed to copy profile " +
8998                                        profileFile.getAbsolutePath() + " ", e);
8999                            }
9000                        }
9001                    }
9002                }
9003            }
9004
9005            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9006                if (DEBUG_DEXOPT) {
9007                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9008                }
9009                numberOfPackagesSkipped++;
9010                continue;
9011            }
9012
9013            if (DEBUG_DEXOPT) {
9014                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9015                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9016            }
9017
9018            if (showDialog) {
9019                try {
9020                    ActivityManager.getService().showBootMessage(
9021                            mContext.getResources().getString(R.string.android_upgrading_apk,
9022                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9023                } catch (RemoteException e) {
9024                }
9025                synchronized (mPackages) {
9026                    mDexOptDialogShown = true;
9027                }
9028            }
9029
9030            int pkgCompilationReason = compilationReason;
9031            if (useProfileForDexopt) {
9032                // Use background dexopt mode to try and use the profile. Note that this does not
9033                // guarantee usage of the profile.
9034                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9035            }
9036
9037            // checkProfiles is false to avoid merging profiles during boot which
9038            // might interfere with background compilation (b/28612421).
9039            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9040            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9041            // trade-off worth doing to save boot time work.
9042            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9043            if (compilationReason == REASON_FIRST_BOOT) {
9044                // TODO: This doesn't cover the upgrade case, we should check for this too.
9045                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9046            }
9047            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9048                    pkg.packageName,
9049                    pkgCompilationReason,
9050                    dexoptFlags));
9051
9052            switch (primaryDexOptStaus) {
9053                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9054                    numberOfPackagesOptimized++;
9055                    break;
9056                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9057                    numberOfPackagesSkipped++;
9058                    break;
9059                case PackageDexOptimizer.DEX_OPT_FAILED:
9060                    numberOfPackagesFailed++;
9061                    break;
9062                default:
9063                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9064                    break;
9065            }
9066        }
9067
9068        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9069                numberOfPackagesFailed };
9070    }
9071
9072    @Override
9073    public void notifyPackageUse(String packageName, int reason) {
9074        synchronized (mPackages) {
9075            final int callingUid = Binder.getCallingUid();
9076            final int callingUserId = UserHandle.getUserId(callingUid);
9077            if (getInstantAppPackageName(callingUid) != null) {
9078                if (!isCallerSameApp(packageName, callingUid)) {
9079                    return;
9080                }
9081            } else {
9082                if (isInstantApp(packageName, callingUserId)) {
9083                    return;
9084                }
9085            }
9086            notifyPackageUseLocked(packageName, reason);
9087        }
9088    }
9089
9090    @GuardedBy("mPackages")
9091    private void notifyPackageUseLocked(String packageName, int reason) {
9092        final PackageParser.Package p = mPackages.get(packageName);
9093        if (p == null) {
9094            return;
9095        }
9096        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9097    }
9098
9099    @Override
9100    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9101            List<String> classPaths, String loaderIsa) {
9102        int userId = UserHandle.getCallingUserId();
9103        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9104        if (ai == null) {
9105            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9106                + loadingPackageName + ", user=" + userId);
9107            return;
9108        }
9109        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9110    }
9111
9112    @Override
9113    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9114            IDexModuleRegisterCallback callback) {
9115        int userId = UserHandle.getCallingUserId();
9116        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9117        DexManager.RegisterDexModuleResult result;
9118        if (ai == null) {
9119            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9120                     " calling user. package=" + packageName + ", user=" + userId);
9121            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9122        } else {
9123            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9124        }
9125
9126        if (callback != null) {
9127            mHandler.post(() -> {
9128                try {
9129                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9130                } catch (RemoteException e) {
9131                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9132                }
9133            });
9134        }
9135    }
9136
9137    /**
9138     * Ask the package manager to perform a dex-opt with the given compiler filter.
9139     *
9140     * Note: exposed only for the shell command to allow moving packages explicitly to a
9141     *       definite state.
9142     */
9143    @Override
9144    public boolean performDexOptMode(String packageName,
9145            boolean checkProfiles, String targetCompilerFilter, boolean force,
9146            boolean bootComplete, String splitName) {
9147        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9148                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9149                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9150        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9151                targetCompilerFilter, splitName, flags));
9152    }
9153
9154    /**
9155     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9156     * secondary dex files belonging to the given package.
9157     *
9158     * Note: exposed only for the shell command to allow moving packages explicitly to a
9159     *       definite state.
9160     */
9161    @Override
9162    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9163            boolean force) {
9164        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9165                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9166                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9167                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9168        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9169    }
9170
9171    /*package*/ boolean performDexOpt(DexoptOptions options) {
9172        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9173            return false;
9174        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9175            return false;
9176        }
9177
9178        if (options.isDexoptOnlySecondaryDex()) {
9179            return mDexManager.dexoptSecondaryDex(options);
9180        } else {
9181            int dexoptStatus = performDexOptWithStatus(options);
9182            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9183        }
9184    }
9185
9186    /**
9187     * Perform dexopt on the given package and return one of following result:
9188     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9189     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9190     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9191     */
9192    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9193        return performDexOptTraced(options);
9194    }
9195
9196    private int performDexOptTraced(DexoptOptions options) {
9197        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9198        try {
9199            return performDexOptInternal(options);
9200        } finally {
9201            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9202        }
9203    }
9204
9205    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9206    // if the package can now be considered up to date for the given filter.
9207    private int performDexOptInternal(DexoptOptions options) {
9208        PackageParser.Package p;
9209        synchronized (mPackages) {
9210            p = mPackages.get(options.getPackageName());
9211            if (p == null) {
9212                // Package could not be found. Report failure.
9213                return PackageDexOptimizer.DEX_OPT_FAILED;
9214            }
9215            mPackageUsage.maybeWriteAsync(mPackages);
9216            mCompilerStats.maybeWriteAsync();
9217        }
9218        long callingId = Binder.clearCallingIdentity();
9219        try {
9220            synchronized (mInstallLock) {
9221                return performDexOptInternalWithDependenciesLI(p, options);
9222            }
9223        } finally {
9224            Binder.restoreCallingIdentity(callingId);
9225        }
9226    }
9227
9228    public ArraySet<String> getOptimizablePackages() {
9229        ArraySet<String> pkgs = new ArraySet<String>();
9230        synchronized (mPackages) {
9231            for (PackageParser.Package p : mPackages.values()) {
9232                if (PackageDexOptimizer.canOptimizePackage(p)) {
9233                    pkgs.add(p.packageName);
9234                }
9235            }
9236        }
9237        return pkgs;
9238    }
9239
9240    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9241            DexoptOptions options) {
9242        // Select the dex optimizer based on the force parameter.
9243        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9244        //       allocate an object here.
9245        PackageDexOptimizer pdo = options.isForce()
9246                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9247                : mPackageDexOptimizer;
9248
9249        // Dexopt all dependencies first. Note: we ignore the return value and march on
9250        // on errors.
9251        // Note that we are going to call performDexOpt on those libraries as many times as
9252        // they are referenced in packages. When we do a batch of performDexOpt (for example
9253        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9254        // and the first package that uses the library will dexopt it. The
9255        // others will see that the compiled code for the library is up to date.
9256        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9257        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9258        if (!deps.isEmpty()) {
9259            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9260                    options.getCompilationReason(), options.getCompilerFilter(),
9261                    options.getSplitName(),
9262                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9263            for (PackageParser.Package depPackage : deps) {
9264                // TODO: Analyze and investigate if we (should) profile libraries.
9265                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9266                        getOrCreateCompilerPackageStats(depPackage),
9267                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9268            }
9269        }
9270        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9271                getOrCreateCompilerPackageStats(p),
9272                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9273    }
9274
9275    /**
9276     * Reconcile the information we have about the secondary dex files belonging to
9277     * {@code packagName} and the actual dex files. For all dex files that were
9278     * deleted, update the internal records and delete the generated oat files.
9279     */
9280    @Override
9281    public void reconcileSecondaryDexFiles(String packageName) {
9282        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9283            return;
9284        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9285            return;
9286        }
9287        mDexManager.reconcileSecondaryDexFiles(packageName);
9288    }
9289
9290    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9291    // a reference there.
9292    /*package*/ DexManager getDexManager() {
9293        return mDexManager;
9294    }
9295
9296    /**
9297     * Execute the background dexopt job immediately.
9298     */
9299    @Override
9300    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9301        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9302            return false;
9303        }
9304        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9305    }
9306
9307    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9308        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9309                || p.usesStaticLibraries != null) {
9310            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9311            Set<String> collectedNames = new HashSet<>();
9312            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9313
9314            retValue.remove(p);
9315
9316            return retValue;
9317        } else {
9318            return Collections.emptyList();
9319        }
9320    }
9321
9322    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9323            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9324        if (!collectedNames.contains(p.packageName)) {
9325            collectedNames.add(p.packageName);
9326            collected.add(p);
9327
9328            if (p.usesLibraries != null) {
9329                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9330                        null, collected, collectedNames);
9331            }
9332            if (p.usesOptionalLibraries != null) {
9333                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9334                        null, collected, collectedNames);
9335            }
9336            if (p.usesStaticLibraries != null) {
9337                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9338                        p.usesStaticLibrariesVersions, collected, collectedNames);
9339            }
9340        }
9341    }
9342
9343    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9344            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9345        final int libNameCount = libs.size();
9346        for (int i = 0; i < libNameCount; i++) {
9347            String libName = libs.get(i);
9348            long version = (versions != null && versions.length == libNameCount)
9349                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9350            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9351            if (libPkg != null) {
9352                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9353            }
9354        }
9355    }
9356
9357    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9358        synchronized (mPackages) {
9359            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9360            if (libEntry != null) {
9361                return mPackages.get(libEntry.apk);
9362            }
9363            return null;
9364        }
9365    }
9366
9367    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9368        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9369        if (versionedLib == null) {
9370            return null;
9371        }
9372        return versionedLib.get(version);
9373    }
9374
9375    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9376        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9377                pkg.staticSharedLibName);
9378        if (versionedLib == null) {
9379            return null;
9380        }
9381        long previousLibVersion = -1;
9382        final int versionCount = versionedLib.size();
9383        for (int i = 0; i < versionCount; i++) {
9384            final long libVersion = versionedLib.keyAt(i);
9385            if (libVersion < pkg.staticSharedLibVersion) {
9386                previousLibVersion = Math.max(previousLibVersion, libVersion);
9387            }
9388        }
9389        if (previousLibVersion >= 0) {
9390            return versionedLib.get(previousLibVersion);
9391        }
9392        return null;
9393    }
9394
9395    public void shutdown() {
9396        mPackageUsage.writeNow(mPackages);
9397        mCompilerStats.writeNow();
9398        mDexManager.writePackageDexUsageNow();
9399    }
9400
9401    @Override
9402    public void dumpProfiles(String packageName) {
9403        PackageParser.Package pkg;
9404        synchronized (mPackages) {
9405            pkg = mPackages.get(packageName);
9406            if (pkg == null) {
9407                throw new IllegalArgumentException("Unknown package: " + packageName);
9408            }
9409        }
9410        /* Only the shell, root, or the app user should be able to dump profiles. */
9411        int callingUid = Binder.getCallingUid();
9412        if (callingUid != Process.SHELL_UID &&
9413            callingUid != Process.ROOT_UID &&
9414            callingUid != pkg.applicationInfo.uid) {
9415            throw new SecurityException("dumpProfiles");
9416        }
9417
9418        synchronized (mInstallLock) {
9419            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9420            mArtManagerService.dumpProfiles(pkg);
9421            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9422        }
9423    }
9424
9425    @Override
9426    public void forceDexOpt(String packageName) {
9427        enforceSystemOrRoot("forceDexOpt");
9428
9429        PackageParser.Package pkg;
9430        synchronized (mPackages) {
9431            pkg = mPackages.get(packageName);
9432            if (pkg == null) {
9433                throw new IllegalArgumentException("Unknown package: " + packageName);
9434            }
9435        }
9436
9437        synchronized (mInstallLock) {
9438            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9439
9440            // Whoever is calling forceDexOpt wants a compiled package.
9441            // Don't use profiles since that may cause compilation to be skipped.
9442            final int res = performDexOptInternalWithDependenciesLI(
9443                    pkg,
9444                    new DexoptOptions(packageName,
9445                            getDefaultCompilerFilter(),
9446                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9447
9448            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9449            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9450                throw new IllegalStateException("Failed to dexopt: " + res);
9451            }
9452        }
9453    }
9454
9455    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9456        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9457            Slog.w(TAG, "Unable to update from " + oldPkg.name
9458                    + " to " + newPkg.packageName
9459                    + ": old package not in system partition");
9460            return false;
9461        } else if (mPackages.get(oldPkg.name) != null) {
9462            Slog.w(TAG, "Unable to update from " + oldPkg.name
9463                    + " to " + newPkg.packageName
9464                    + ": old package still exists");
9465            return false;
9466        }
9467        return true;
9468    }
9469
9470    void removeCodePathLI(File codePath) {
9471        if (codePath.isDirectory()) {
9472            try {
9473                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9474            } catch (InstallerException e) {
9475                Slog.w(TAG, "Failed to remove code path", e);
9476            }
9477        } else {
9478            codePath.delete();
9479        }
9480    }
9481
9482    private int[] resolveUserIds(int userId) {
9483        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9484    }
9485
9486    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9487        if (pkg == null) {
9488            Slog.wtf(TAG, "Package was null!", new Throwable());
9489            return;
9490        }
9491        clearAppDataLeafLIF(pkg, userId, flags);
9492        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9493        for (int i = 0; i < childCount; i++) {
9494            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9495        }
9496
9497        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9498    }
9499
9500    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9501        final PackageSetting ps;
9502        synchronized (mPackages) {
9503            ps = mSettings.mPackages.get(pkg.packageName);
9504        }
9505        for (int realUserId : resolveUserIds(userId)) {
9506            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9507            try {
9508                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9509                        ceDataInode);
9510            } catch (InstallerException e) {
9511                Slog.w(TAG, String.valueOf(e));
9512            }
9513        }
9514    }
9515
9516    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9517        if (pkg == null) {
9518            Slog.wtf(TAG, "Package was null!", new Throwable());
9519            return;
9520        }
9521        destroyAppDataLeafLIF(pkg, userId, flags);
9522        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9523        for (int i = 0; i < childCount; i++) {
9524            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9525        }
9526    }
9527
9528    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9529        final PackageSetting ps;
9530        synchronized (mPackages) {
9531            ps = mSettings.mPackages.get(pkg.packageName);
9532        }
9533        for (int realUserId : resolveUserIds(userId)) {
9534            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9535            try {
9536                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9537                        ceDataInode);
9538            } catch (InstallerException e) {
9539                Slog.w(TAG, String.valueOf(e));
9540            }
9541            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9542        }
9543    }
9544
9545    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9546        if (pkg == null) {
9547            Slog.wtf(TAG, "Package was null!", new Throwable());
9548            return;
9549        }
9550        destroyAppProfilesLeafLIF(pkg);
9551        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9552        for (int i = 0; i < childCount; i++) {
9553            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9554        }
9555    }
9556
9557    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9558        try {
9559            mInstaller.destroyAppProfiles(pkg.packageName);
9560        } catch (InstallerException e) {
9561            Slog.w(TAG, String.valueOf(e));
9562        }
9563    }
9564
9565    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9566        if (pkg == null) {
9567            Slog.wtf(TAG, "Package was null!", new Throwable());
9568            return;
9569        }
9570        mArtManagerService.clearAppProfiles(pkg);
9571        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9572        for (int i = 0; i < childCount; i++) {
9573            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9574        }
9575    }
9576
9577    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9578            long lastUpdateTime) {
9579        // Set parent install/update time
9580        PackageSetting ps = (PackageSetting) pkg.mExtras;
9581        if (ps != null) {
9582            ps.firstInstallTime = firstInstallTime;
9583            ps.lastUpdateTime = lastUpdateTime;
9584        }
9585        // Set children install/update time
9586        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9587        for (int i = 0; i < childCount; i++) {
9588            PackageParser.Package childPkg = pkg.childPackages.get(i);
9589            ps = (PackageSetting) childPkg.mExtras;
9590            if (ps != null) {
9591                ps.firstInstallTime = firstInstallTime;
9592                ps.lastUpdateTime = lastUpdateTime;
9593            }
9594        }
9595    }
9596
9597    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9598            SharedLibraryEntry file,
9599            PackageParser.Package changingLib) {
9600        if (file.path != null) {
9601            usesLibraryFiles.add(file.path);
9602            return;
9603        }
9604        PackageParser.Package p = mPackages.get(file.apk);
9605        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9606            // If we are doing this while in the middle of updating a library apk,
9607            // then we need to make sure to use that new apk for determining the
9608            // dependencies here.  (We haven't yet finished committing the new apk
9609            // to the package manager state.)
9610            if (p == null || p.packageName.equals(changingLib.packageName)) {
9611                p = changingLib;
9612            }
9613        }
9614        if (p != null) {
9615            usesLibraryFiles.addAll(p.getAllCodePaths());
9616            if (p.usesLibraryFiles != null) {
9617                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9618            }
9619        }
9620    }
9621
9622    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9623            PackageParser.Package changingLib) throws PackageManagerException {
9624        if (pkg == null) {
9625            return;
9626        }
9627        // The collection used here must maintain the order of addition (so
9628        // that libraries are searched in the correct order) and must have no
9629        // duplicates.
9630        Set<String> usesLibraryFiles = null;
9631        if (pkg.usesLibraries != null) {
9632            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9633                    null, null, pkg.packageName, changingLib, true,
9634                    pkg.applicationInfo.targetSdkVersion, null);
9635        }
9636        if (pkg.usesStaticLibraries != null) {
9637            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9638                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9639                    pkg.packageName, changingLib, true,
9640                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9641        }
9642        if (pkg.usesOptionalLibraries != null) {
9643            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9644                    null, null, pkg.packageName, changingLib, false,
9645                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9646        }
9647        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9648            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9649        } else {
9650            pkg.usesLibraryFiles = null;
9651        }
9652    }
9653
9654    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9655            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9656            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9657            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9658            throws PackageManagerException {
9659        final int libCount = requestedLibraries.size();
9660        for (int i = 0; i < libCount; i++) {
9661            final String libName = requestedLibraries.get(i);
9662            final long libVersion = requiredVersions != null ? requiredVersions[i]
9663                    : SharedLibraryInfo.VERSION_UNDEFINED;
9664            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9665            if (libEntry == null) {
9666                if (required) {
9667                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9668                            "Package " + packageName + " requires unavailable shared library "
9669                                    + libName + "; failing!");
9670                } else if (DEBUG_SHARED_LIBRARIES) {
9671                    Slog.i(TAG, "Package " + packageName
9672                            + " desires unavailable shared library "
9673                            + libName + "; ignoring!");
9674                }
9675            } else {
9676                if (requiredVersions != null && requiredCertDigests != null) {
9677                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9678                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9679                            "Package " + packageName + " requires unavailable static shared"
9680                                    + " library " + libName + " version "
9681                                    + libEntry.info.getLongVersion() + "; failing!");
9682                    }
9683
9684                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9685                    if (libPkg == null) {
9686                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9687                                "Package " + packageName + " requires unavailable static shared"
9688                                        + " library; failing!");
9689                    }
9690
9691                    final String[] expectedCertDigests = requiredCertDigests[i];
9692
9693
9694                    if (expectedCertDigests.length > 1) {
9695
9696                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9697                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9698                                ? PackageUtils.computeSignaturesSha256Digests(
9699                                libPkg.mSigningDetails.signatures)
9700                                : PackageUtils.computeSignaturesSha256Digests(
9701                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9702
9703                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9704                        // target O we don't parse the "additional-certificate" tags similarly
9705                        // how we only consider all certs only for apps targeting O (see above).
9706                        // Therefore, the size check is safe to make.
9707                        if (expectedCertDigests.length != libCertDigests.length) {
9708                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9709                                    "Package " + packageName + " requires differently signed" +
9710                                            " static shared library; failing!");
9711                        }
9712
9713                        // Use a predictable order as signature order may vary
9714                        Arrays.sort(libCertDigests);
9715                        Arrays.sort(expectedCertDigests);
9716
9717                        final int certCount = libCertDigests.length;
9718                        for (int j = 0; j < certCount; j++) {
9719                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9720                                throw new PackageManagerException(
9721                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9722                                        "Package " + packageName + " requires differently signed" +
9723                                                " static shared library; failing!");
9724                            }
9725                        }
9726                    } else {
9727
9728                        // lib signing cert could have rotated beyond the one expected, check to see
9729                        // if the new one has been blessed by the old
9730                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9731                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9732                            throw new PackageManagerException(
9733                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9734                                    "Package " + packageName + " requires differently signed" +
9735                                            " static shared library; failing!");
9736                        }
9737                    }
9738                }
9739
9740                if (outUsedLibraries == null) {
9741                    // Use LinkedHashSet to preserve the order of files added to
9742                    // usesLibraryFiles while eliminating duplicates.
9743                    outUsedLibraries = new LinkedHashSet<>();
9744                }
9745                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9746            }
9747        }
9748        return outUsedLibraries;
9749    }
9750
9751    private static boolean hasString(List<String> list, List<String> which) {
9752        if (list == null) {
9753            return false;
9754        }
9755        for (int i=list.size()-1; i>=0; i--) {
9756            for (int j=which.size()-1; j>=0; j--) {
9757                if (which.get(j).equals(list.get(i))) {
9758                    return true;
9759                }
9760            }
9761        }
9762        return false;
9763    }
9764
9765    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9766            PackageParser.Package changingPkg) {
9767        ArrayList<PackageParser.Package> res = null;
9768        for (PackageParser.Package pkg : mPackages.values()) {
9769            if (changingPkg != null
9770                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9771                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9772                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9773                            changingPkg.staticSharedLibName)) {
9774                return null;
9775            }
9776            if (res == null) {
9777                res = new ArrayList<>();
9778            }
9779            res.add(pkg);
9780            try {
9781                updateSharedLibrariesLPr(pkg, changingPkg);
9782            } catch (PackageManagerException e) {
9783                // If a system app update or an app and a required lib missing we
9784                // delete the package and for updated system apps keep the data as
9785                // it is better for the user to reinstall than to be in an limbo
9786                // state. Also libs disappearing under an app should never happen
9787                // - just in case.
9788                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9789                    final int flags = pkg.isUpdatedSystemApp()
9790                            ? PackageManager.DELETE_KEEP_DATA : 0;
9791                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9792                            flags , null, true, null);
9793                }
9794                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9795            }
9796        }
9797        return res;
9798    }
9799
9800    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9801            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9802            @Nullable UserHandle user) throws PackageManagerException {
9803        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9804        // If the package has children and this is the first dive in the function
9805        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9806        // whether all packages (parent and children) would be successfully scanned
9807        // before the actual scan since scanning mutates internal state and we want
9808        // to atomically install the package and its children.
9809        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9810            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9811                scanFlags |= SCAN_CHECK_ONLY;
9812            }
9813        } else {
9814            scanFlags &= ~SCAN_CHECK_ONLY;
9815        }
9816
9817        final PackageParser.Package scannedPkg;
9818        try {
9819            // Scan the parent
9820            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9821            // Scan the children
9822            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9823            for (int i = 0; i < childCount; i++) {
9824                PackageParser.Package childPkg = pkg.childPackages.get(i);
9825                scanPackageNewLI(childPkg, parseFlags,
9826                        scanFlags, currentTime, user);
9827            }
9828        } finally {
9829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9830        }
9831
9832        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9833            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9834        }
9835
9836        return scannedPkg;
9837    }
9838
9839    /** The result of a package scan. */
9840    private static class ScanResult {
9841        /** Whether or not the package scan was successful */
9842        public final boolean success;
9843        /**
9844         * The final package settings. This may be the same object passed in
9845         * the {@link ScanRequest}, but, with modified values.
9846         */
9847        @Nullable public final PackageSetting pkgSetting;
9848        /** ABI code paths that have changed in the package scan */
9849        @Nullable public final List<String> changedAbiCodePath;
9850        public ScanResult(
9851                boolean success,
9852                @Nullable PackageSetting pkgSetting,
9853                @Nullable List<String> changedAbiCodePath) {
9854            this.success = success;
9855            this.pkgSetting = pkgSetting;
9856            this.changedAbiCodePath = changedAbiCodePath;
9857        }
9858    }
9859
9860    /** A package to be scanned */
9861    private static class ScanRequest {
9862        /** The parsed package */
9863        @NonNull public final PackageParser.Package pkg;
9864        /** Shared user settings, if the package has a shared user */
9865        @Nullable public final SharedUserSetting sharedUserSetting;
9866        /**
9867         * Package settings of the currently installed version.
9868         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9869         * during scan.
9870         */
9871        @Nullable public final PackageSetting pkgSetting;
9872        /** A copy of the settings for the currently installed version */
9873        @Nullable public final PackageSetting oldPkgSetting;
9874        /** Package settings for the disabled version on the /system partition */
9875        @Nullable public final PackageSetting disabledPkgSetting;
9876        /** Package settings for the installed version under its original package name */
9877        @Nullable public final PackageSetting originalPkgSetting;
9878        /** The real package name of a renamed application */
9879        @Nullable public final String realPkgName;
9880        public final @ParseFlags int parseFlags;
9881        public final @ScanFlags int scanFlags;
9882        /** The user for which the package is being scanned */
9883        @Nullable public final UserHandle user;
9884        /** Whether or not the platform package is being scanned */
9885        public final boolean isPlatformPackage;
9886        public ScanRequest(
9887                @NonNull PackageParser.Package pkg,
9888                @Nullable SharedUserSetting sharedUserSetting,
9889                @Nullable PackageSetting pkgSetting,
9890                @Nullable PackageSetting disabledPkgSetting,
9891                @Nullable PackageSetting originalPkgSetting,
9892                @Nullable String realPkgName,
9893                @ParseFlags int parseFlags,
9894                @ScanFlags int scanFlags,
9895                boolean isPlatformPackage,
9896                @Nullable UserHandle user) {
9897            this.pkg = pkg;
9898            this.pkgSetting = pkgSetting;
9899            this.sharedUserSetting = sharedUserSetting;
9900            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9901            this.disabledPkgSetting = disabledPkgSetting;
9902            this.originalPkgSetting = originalPkgSetting;
9903            this.realPkgName = realPkgName;
9904            this.parseFlags = parseFlags;
9905            this.scanFlags = scanFlags;
9906            this.isPlatformPackage = isPlatformPackage;
9907            this.user = user;
9908        }
9909    }
9910
9911    /**
9912     * Returns the actual scan flags depending upon the state of the other settings.
9913     * <p>Updated system applications will not have the following flags set
9914     * by default and need to be adjusted after the fact:
9915     * <ul>
9916     * <li>{@link #SCAN_AS_SYSTEM}</li>
9917     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9918     * <li>{@link #SCAN_AS_OEM}</li>
9919     * <li>{@link #SCAN_AS_VENDOR}</li>
9920     * <li>{@link #SCAN_AS_PRODUCT}</li>
9921     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9922     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9923     * </ul>
9924     */
9925    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9926            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9927            PackageParser.Package pkg) {
9928        if (disabledPkgSetting != null) {
9929            // updated system application, must at least have SCAN_AS_SYSTEM
9930            scanFlags |= SCAN_AS_SYSTEM;
9931            if ((disabledPkgSetting.pkgPrivateFlags
9932                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9933                scanFlags |= SCAN_AS_PRIVILEGED;
9934            }
9935            if ((disabledPkgSetting.pkgPrivateFlags
9936                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9937                scanFlags |= SCAN_AS_OEM;
9938            }
9939            if ((disabledPkgSetting.pkgPrivateFlags
9940                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9941                scanFlags |= SCAN_AS_VENDOR;
9942            }
9943            if ((disabledPkgSetting.pkgPrivateFlags
9944                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9945                scanFlags |= SCAN_AS_PRODUCT;
9946            }
9947        }
9948        if (pkgSetting != null) {
9949            final int userId = ((user == null) ? 0 : user.getIdentifier());
9950            if (pkgSetting.getInstantApp(userId)) {
9951                scanFlags |= SCAN_AS_INSTANT_APP;
9952            }
9953            if (pkgSetting.getVirtulalPreload(userId)) {
9954                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9955            }
9956        }
9957
9958        // Scan as privileged apps that share a user with a priv-app.
9959        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9960                && (pkg.mSharedUserId != null)) {
9961            SharedUserSetting sharedUserSetting = null;
9962            try {
9963                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9964            } catch (PackageManagerException ignore) {}
9965            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9966                // Exempt SharedUsers signed with the platform key.
9967                // TODO(b/72378145) Fix this exemption. Force signature apps
9968                // to whitelist their privileged permissions just like other
9969                // priv-apps.
9970                synchronized (mPackages) {
9971                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9972                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9973                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9974                        scanFlags |= SCAN_AS_PRIVILEGED;
9975                    }
9976                }
9977            }
9978        }
9979
9980        return scanFlags;
9981    }
9982
9983    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
9984    // the results / removing app data needs to be moved up a level to the callers of this
9985    // method. Also, we need to solve the problem of potentially creating a new shared user
9986    // setting. That can probably be done later and patch things up after the fact.
9987    @GuardedBy("mInstallLock")
9988    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9989            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9990            @Nullable UserHandle user) throws PackageManagerException {
9991
9992        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9993        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9994        if (realPkgName != null) {
9995            ensurePackageRenamed(pkg, renamedPkgName);
9996        }
9997        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9998        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9999        final PackageSetting disabledPkgSetting =
10000                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10001
10002        if (mTransferedPackages.contains(pkg.packageName)) {
10003            Slog.w(TAG, "Package " + pkg.packageName
10004                    + " was transferred to another, but its .apk remains");
10005        }
10006
10007        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10008        synchronized (mPackages) {
10009            applyPolicy(pkg, parseFlags, scanFlags);
10010            assertPackageIsValid(pkg, parseFlags, scanFlags);
10011
10012            SharedUserSetting sharedUserSetting = null;
10013            if (pkg.mSharedUserId != null) {
10014                // SIDE EFFECTS; may potentially allocate a new shared user
10015                sharedUserSetting = mSettings.getSharedUserLPw(
10016                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10017                if (DEBUG_PACKAGE_SCANNING) {
10018                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10019                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10020                                + " (uid=" + sharedUserSetting.userId + "):"
10021                                + " packages=" + sharedUserSetting.packages);
10022                }
10023            }
10024
10025            boolean scanSucceeded = false;
10026            try {
10027                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10028                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10029                        (pkg == mPlatformPackage), user);
10030                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10031                if (result.success) {
10032                    commitScanResultsLocked(request, result);
10033                }
10034                scanSucceeded = true;
10035            } finally {
10036                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10037                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10038                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10039                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10040                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10041                  }
10042            }
10043        }
10044        return pkg;
10045    }
10046
10047    /**
10048     * Commits the package scan and modifies system state.
10049     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10050     * of committing the package, leaving the system in an inconsistent state.
10051     * This needs to be fixed so, once we get to this point, no errors are
10052     * possible and the system is not left in an inconsistent state.
10053     */
10054    @GuardedBy("mPackages")
10055    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10056            throws PackageManagerException {
10057        final PackageParser.Package pkg = request.pkg;
10058        final @ParseFlags int parseFlags = request.parseFlags;
10059        final @ScanFlags int scanFlags = request.scanFlags;
10060        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10061        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10062        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10063        final UserHandle user = request.user;
10064        final String realPkgName = request.realPkgName;
10065        final PackageSetting pkgSetting = result.pkgSetting;
10066        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10067        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10068
10069        if (newPkgSettingCreated) {
10070            if (originalPkgSetting != null) {
10071                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10072            }
10073            // THROWS: when we can't allocate a user id. add call to check if there's
10074            // enough space to ensure we won't throw; otherwise, don't modify state
10075            mSettings.addUserToSettingLPw(pkgSetting);
10076
10077            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10078                mTransferedPackages.add(originalPkgSetting.name);
10079            }
10080        }
10081        // TODO(toddke): Consider a method specifically for modifying the Package object
10082        // post scan; or, moving this stuff out of the Package object since it has nothing
10083        // to do with the package on disk.
10084        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10085        // for creating the application ID. If we did this earlier, we would be saving the
10086        // correct ID.
10087        pkg.applicationInfo.uid = pkgSetting.appId;
10088
10089        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10090
10091        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10092            mTransferedPackages.add(pkg.packageName);
10093        }
10094
10095        // THROWS: when requested libraries that can't be found. it only changes
10096        // the state of the passed in pkg object, so, move to the top of the method
10097        // and allow it to abort
10098        if ((scanFlags & SCAN_BOOTING) == 0
10099                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10100            // Check all shared libraries and map to their actual file path.
10101            // We only do this here for apps not on a system dir, because those
10102            // are the only ones that can fail an install due to this.  We
10103            // will take care of the system apps by updating all of their
10104            // library paths after the scan is done. Also during the initial
10105            // scan don't update any libs as we do this wholesale after all
10106            // apps are scanned to avoid dependency based scanning.
10107            updateSharedLibrariesLPr(pkg, null);
10108        }
10109
10110        // All versions of a static shared library are referenced with the same
10111        // package name. Internally, we use a synthetic package name to allow
10112        // multiple versions of the same shared library to be installed. So,
10113        // we need to generate the synthetic package name of the latest shared
10114        // library in order to compare signatures.
10115        PackageSetting signatureCheckPs = pkgSetting;
10116        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10117            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10118            if (libraryEntry != null) {
10119                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10120            }
10121        }
10122
10123        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10124        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10125            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10126                // We just determined the app is signed correctly, so bring
10127                // over the latest parsed certs.
10128                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10129            } else {
10130                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10131                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10132                            "Package " + pkg.packageName + " upgrade keys do not match the "
10133                                    + "previously installed version");
10134                } else {
10135                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10136                    String msg = "System package " + pkg.packageName
10137                            + " signature changed; retaining data.";
10138                    reportSettingsProblem(Log.WARN, msg);
10139                }
10140            }
10141        } else {
10142            try {
10143                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10144                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10145                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10146                        pkg.mSigningDetails, compareCompat, compareRecover);
10147                // The new KeySets will be re-added later in the scanning process.
10148                if (compatMatch) {
10149                    synchronized (mPackages) {
10150                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10151                    }
10152                }
10153                // We just determined the app is signed correctly, so bring
10154                // over the latest parsed certs.
10155                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10156
10157
10158                // if this is is a sharedUser, check to see if the new package is signed by a newer
10159                // signing certificate than the existing one, and if so, copy over the new details
10160                if (signatureCheckPs.sharedUser != null
10161                        && pkg.mSigningDetails.hasAncestor(
10162                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10163                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10164                }
10165            } catch (PackageManagerException e) {
10166                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10167                    throw e;
10168                }
10169                // The signature has changed, but this package is in the system
10170                // image...  let's recover!
10171                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10172                // However...  if this package is part of a shared user, but it
10173                // doesn't match the signature of the shared user, let's fail.
10174                // What this means is that you can't change the signatures
10175                // associated with an overall shared user, which doesn't seem all
10176                // that unreasonable.
10177                if (signatureCheckPs.sharedUser != null) {
10178                    if (compareSignatures(
10179                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10180                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10181                        throw new PackageManagerException(
10182                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10183                                "Signature mismatch for shared user: "
10184                                        + pkgSetting.sharedUser);
10185                    }
10186                }
10187                // File a report about this.
10188                String msg = "System package " + pkg.packageName
10189                        + " signature changed; retaining data.";
10190                reportSettingsProblem(Log.WARN, msg);
10191            } catch (IllegalArgumentException e) {
10192
10193                // should never happen: certs matched when checking, but not when comparing
10194                // old to new for sharedUser
10195                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10196                        "Signing certificates comparison made on incomparable signing details"
10197                        + " but somehow passed verifySignatures!");
10198            }
10199        }
10200
10201        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10202            // This package wants to adopt ownership of permissions from
10203            // another package.
10204            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10205                final String origName = pkg.mAdoptPermissions.get(i);
10206                final PackageSetting orig = mSettings.getPackageLPr(origName);
10207                if (orig != null) {
10208                    if (verifyPackageUpdateLPr(orig, pkg)) {
10209                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10210                                + pkg.packageName);
10211                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10212                    }
10213                }
10214            }
10215        }
10216
10217        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10218            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10219                final String codePathString = changedAbiCodePath.get(i);
10220                try {
10221                    mInstaller.rmdex(codePathString,
10222                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10223                } catch (InstallerException ignored) {
10224                }
10225            }
10226        }
10227
10228        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10229            if (oldPkgSetting != null) {
10230                synchronized (mPackages) {
10231                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10232                }
10233            }
10234        } else {
10235            final int userId = user == null ? 0 : user.getIdentifier();
10236            // Modify state for the given package setting
10237            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10238                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10239            if (pkgSetting.getInstantApp(userId)) {
10240                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10241            }
10242        }
10243    }
10244
10245    /**
10246     * Returns the "real" name of the package.
10247     * <p>This may differ from the package's actual name if the application has already
10248     * been installed under one of this package's original names.
10249     */
10250    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10251            @Nullable String renamedPkgName) {
10252        if (isPackageRenamed(pkg, renamedPkgName)) {
10253            return pkg.mRealPackage;
10254        }
10255        return null;
10256    }
10257
10258    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10259    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10260            @Nullable String renamedPkgName) {
10261        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10262    }
10263
10264    /**
10265     * Returns the original package setting.
10266     * <p>A package can migrate its name during an update. In this scenario, a package
10267     * designates a set of names that it considers as one of its original names.
10268     * <p>An original package must be signed identically and it must have the same
10269     * shared user [if any].
10270     */
10271    @GuardedBy("mPackages")
10272    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10273            @Nullable String renamedPkgName) {
10274        if (!isPackageRenamed(pkg, renamedPkgName)) {
10275            return null;
10276        }
10277        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10278            final PackageSetting originalPs =
10279                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10280            if (originalPs != null) {
10281                // the package is already installed under its original name...
10282                // but, should we use it?
10283                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10284                    // the new package is incompatible with the original
10285                    continue;
10286                } else if (originalPs.sharedUser != null) {
10287                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10288                        // the shared user id is incompatible with the original
10289                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10290                                + " to " + pkg.packageName + ": old uid "
10291                                + originalPs.sharedUser.name
10292                                + " differs from " + pkg.mSharedUserId);
10293                        continue;
10294                    }
10295                    // TODO: Add case when shared user id is added [b/28144775]
10296                } else {
10297                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10298                            + pkg.packageName + " to old name " + originalPs.name);
10299                }
10300                return originalPs;
10301            }
10302        }
10303        return null;
10304    }
10305
10306    /**
10307     * Renames the package if it was installed under a different name.
10308     * <p>When we've already installed the package under an original name, update
10309     * the new package so we can continue to have the old name.
10310     */
10311    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10312            @NonNull String renamedPackageName) {
10313        if (pkg.mOriginalPackages == null
10314                || !pkg.mOriginalPackages.contains(renamedPackageName)
10315                || pkg.packageName.equals(renamedPackageName)) {
10316            return;
10317        }
10318        pkg.setPackageName(renamedPackageName);
10319    }
10320
10321    /**
10322     * Just scans the package without any side effects.
10323     * <p>Not entirely true at the moment. There is still one side effect -- this
10324     * method potentially modifies a live {@link PackageSetting} object representing
10325     * the package being scanned. This will be resolved in the future.
10326     *
10327     * @param request Information about the package to be scanned
10328     * @param isUnderFactoryTest Whether or not the device is under factory test
10329     * @param currentTime The current time, in millis
10330     * @return The results of the scan
10331     */
10332    @GuardedBy("mInstallLock")
10333    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10334            boolean isUnderFactoryTest, long currentTime)
10335                    throws PackageManagerException {
10336        final PackageParser.Package pkg = request.pkg;
10337        PackageSetting pkgSetting = request.pkgSetting;
10338        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10339        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10340        final @ParseFlags int parseFlags = request.parseFlags;
10341        final @ScanFlags int scanFlags = request.scanFlags;
10342        final String realPkgName = request.realPkgName;
10343        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10344        final UserHandle user = request.user;
10345        final boolean isPlatformPackage = request.isPlatformPackage;
10346
10347        List<String> changedAbiCodePath = null;
10348
10349        if (DEBUG_PACKAGE_SCANNING) {
10350            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10351                Log.d(TAG, "Scanning package " + pkg.packageName);
10352        }
10353
10354        if (Build.IS_DEBUGGABLE &&
10355                pkg.isPrivileged() &&
10356                !SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, true)) {
10357            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10358        }
10359
10360        // Initialize package source and resource directories
10361        final File scanFile = new File(pkg.codePath);
10362        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10363        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10364
10365        // We keep references to the derived CPU Abis from settings in oder to reuse
10366        // them in the case where we're not upgrading or booting for the first time.
10367        String primaryCpuAbiFromSettings = null;
10368        String secondaryCpuAbiFromSettings = null;
10369        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10370
10371        if (!needToDeriveAbi) {
10372            if (pkgSetting != null) {
10373                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10374                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10375            } else {
10376                // Re-scanning a system package after uninstalling updates; need to derive ABI
10377                needToDeriveAbi = true;
10378            }
10379        }
10380
10381        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10382            PackageManagerService.reportSettingsProblem(Log.WARN,
10383                    "Package " + pkg.packageName + " shared user changed from "
10384                            + (pkgSetting.sharedUser != null
10385                            ? pkgSetting.sharedUser.name : "<nothing>")
10386                            + " to "
10387                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10388                            + "; replacing with new");
10389            pkgSetting = null;
10390        }
10391
10392        String[] usesStaticLibraries = null;
10393        if (pkg.usesStaticLibraries != null) {
10394            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10395            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10396        }
10397        final boolean createNewPackage = (pkgSetting == null);
10398        if (createNewPackage) {
10399            final String parentPackageName = (pkg.parentPackage != null)
10400                    ? pkg.parentPackage.packageName : null;
10401            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10402            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10403            // REMOVE SharedUserSetting from method; update in a separate call
10404            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10405                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10406                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10407                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10408                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10409                    user, true /*allowInstall*/, instantApp, virtualPreload,
10410                    parentPackageName, pkg.getChildPackageNames(),
10411                    UserManagerService.getInstance(), usesStaticLibraries,
10412                    pkg.usesStaticLibrariesVersions);
10413        } else {
10414            // REMOVE SharedUserSetting from method; update in a separate call.
10415            //
10416            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10417            // secondaryCpuAbi are not known at this point so we always update them
10418            // to null here, only to reset them at a later point.
10419            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10420                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10421                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10422                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10423                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10424                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10425        }
10426        if (createNewPackage && originalPkgSetting != null) {
10427            // This is the initial transition from the original package, so,
10428            // fix up the new package's name now. We must do this after looking
10429            // up the package under its new name, so getPackageLP takes care of
10430            // fiddling things correctly.
10431            pkg.setPackageName(originalPkgSetting.name);
10432
10433            // File a report about this.
10434            String msg = "New package " + pkgSetting.realName
10435                    + " renamed to replace old package " + pkgSetting.name;
10436            reportSettingsProblem(Log.WARN, msg);
10437        }
10438
10439        if (disabledPkgSetting != null) {
10440            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10441        }
10442
10443        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10444        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10445        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10446        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10447        // least restrictive selinux domain.
10448        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10449        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10450        // ensures that all packages continue to run in the same selinux domain.
10451        final int targetSdkVersion =
10452            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10453            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10454        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10455        // They currently can be if the sharedUser apps are signed with the platform key.
10456        final boolean isPrivileged = (sharedUserSetting != null) ?
10457            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10458
10459        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10460                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10461
10462        pkg.mExtras = pkgSetting;
10463        pkg.applicationInfo.processName = fixProcessName(
10464                pkg.applicationInfo.packageName,
10465                pkg.applicationInfo.processName);
10466
10467        if (!isPlatformPackage) {
10468            // Get all of our default paths setup
10469            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10470        }
10471
10472        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10473
10474        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10475            if (needToDeriveAbi) {
10476                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10477                final boolean extractNativeLibs = !pkg.isLibrary();
10478                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10479                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10480
10481                // Some system apps still use directory structure for native libraries
10482                // in which case we might end up not detecting abi solely based on apk
10483                // structure. Try to detect abi based on directory structure.
10484                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10485                        pkg.applicationInfo.primaryCpuAbi == null) {
10486                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10487                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10488                }
10489            } else {
10490                // This is not a first boot or an upgrade, don't bother deriving the
10491                // ABI during the scan. Instead, trust the value that was stored in the
10492                // package setting.
10493                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10494                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10495
10496                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10497
10498                if (DEBUG_ABI_SELECTION) {
10499                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10500                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10501                            pkg.applicationInfo.secondaryCpuAbi);
10502                }
10503            }
10504        } else {
10505            if ((scanFlags & SCAN_MOVE) != 0) {
10506                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10507                // but we already have this packages package info in the PackageSetting. We just
10508                // use that and derive the native library path based on the new codepath.
10509                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10510                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10511            }
10512
10513            // Set native library paths again. For moves, the path will be updated based on the
10514            // ABIs we've determined above. For non-moves, the path will be updated based on the
10515            // ABIs we determined during compilation, but the path will depend on the final
10516            // package path (after the rename away from the stage path).
10517            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10518        }
10519
10520        // This is a special case for the "system" package, where the ABI is
10521        // dictated by the zygote configuration (and init.rc). We should keep track
10522        // of this ABI so that we can deal with "normal" applications that run under
10523        // the same UID correctly.
10524        if (isPlatformPackage) {
10525            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10526                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10527        }
10528
10529        // If there's a mismatch between the abi-override in the package setting
10530        // and the abiOverride specified for the install. Warn about this because we
10531        // would've already compiled the app without taking the package setting into
10532        // account.
10533        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10534            if (cpuAbiOverride == null && pkg.packageName != null) {
10535                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10536                        " for package " + pkg.packageName);
10537            }
10538        }
10539
10540        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10541        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10542        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10543
10544        // Copy the derived override back to the parsed package, so that we can
10545        // update the package settings accordingly.
10546        pkg.cpuAbiOverride = cpuAbiOverride;
10547
10548        if (DEBUG_ABI_SELECTION) {
10549            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10550                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10551                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10552        }
10553
10554        // Push the derived path down into PackageSettings so we know what to
10555        // clean up at uninstall time.
10556        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10557
10558        if (DEBUG_ABI_SELECTION) {
10559            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10560                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10561                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10562        }
10563
10564        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10565            // We don't do this here during boot because we can do it all
10566            // at once after scanning all existing packages.
10567            //
10568            // We also do this *before* we perform dexopt on this package, so that
10569            // we can avoid redundant dexopts, and also to make sure we've got the
10570            // code and package path correct.
10571            changedAbiCodePath =
10572                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10573        }
10574
10575        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10576                android.Manifest.permission.FACTORY_TEST)) {
10577            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10578        }
10579
10580        if (isSystemApp(pkg)) {
10581            pkgSetting.isOrphaned = true;
10582        }
10583
10584        // Take care of first install / last update times.
10585        final long scanFileTime = getLastModifiedTime(pkg);
10586        if (currentTime != 0) {
10587            if (pkgSetting.firstInstallTime == 0) {
10588                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10589            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10590                pkgSetting.lastUpdateTime = currentTime;
10591            }
10592        } else if (pkgSetting.firstInstallTime == 0) {
10593            // We need *something*.  Take time time stamp of the file.
10594            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10595        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10596            if (scanFileTime != pkgSetting.timeStamp) {
10597                // A package on the system image has changed; consider this
10598                // to be an update.
10599                pkgSetting.lastUpdateTime = scanFileTime;
10600            }
10601        }
10602        pkgSetting.setTimeStamp(scanFileTime);
10603
10604        pkgSetting.pkg = pkg;
10605        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10606        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10607            pkgSetting.versionCode = pkg.getLongVersionCode();
10608        }
10609        // Update volume if needed
10610        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10611        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10612            Slog.i(PackageManagerService.TAG,
10613                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10614                    + " package " + pkg.packageName
10615                    + " volume from " + pkgSetting.volumeUuid
10616                    + " to " + volumeUuid);
10617            pkgSetting.volumeUuid = volumeUuid;
10618        }
10619
10620        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10621    }
10622
10623    /**
10624     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10625     */
10626    private static boolean apkHasCode(String fileName) {
10627        StrictJarFile jarFile = null;
10628        try {
10629            jarFile = new StrictJarFile(fileName,
10630                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10631            return jarFile.findEntry("classes.dex") != null;
10632        } catch (IOException ignore) {
10633        } finally {
10634            try {
10635                if (jarFile != null) {
10636                    jarFile.close();
10637                }
10638            } catch (IOException ignore) {}
10639        }
10640        return false;
10641    }
10642
10643    /**
10644     * Enforces code policy for the package. This ensures that if an APK has
10645     * declared hasCode="true" in its manifest that the APK actually contains
10646     * code.
10647     *
10648     * @throws PackageManagerException If bytecode could not be found when it should exist
10649     */
10650    private static void assertCodePolicy(PackageParser.Package pkg)
10651            throws PackageManagerException {
10652        final boolean shouldHaveCode =
10653                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10654        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10655            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10656                    "Package " + pkg.baseCodePath + " code is missing");
10657        }
10658
10659        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10660            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10661                final boolean splitShouldHaveCode =
10662                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10663                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10664                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10665                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10666                }
10667            }
10668        }
10669    }
10670
10671    /**
10672     * Applies policy to the parsed package based upon the given policy flags.
10673     * Ensures the package is in a good state.
10674     * <p>
10675     * Implementation detail: This method must NOT have any side effect. It would
10676     * ideally be static, but, it requires locks to read system state.
10677     */
10678    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10679            final @ScanFlags int scanFlags) {
10680        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10681            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10682            if (pkg.applicationInfo.isDirectBootAware()) {
10683                // we're direct boot aware; set for all components
10684                for (PackageParser.Service s : pkg.services) {
10685                    s.info.encryptionAware = s.info.directBootAware = true;
10686                }
10687                for (PackageParser.Provider p : pkg.providers) {
10688                    p.info.encryptionAware = p.info.directBootAware = true;
10689                }
10690                for (PackageParser.Activity a : pkg.activities) {
10691                    a.info.encryptionAware = a.info.directBootAware = true;
10692                }
10693                for (PackageParser.Activity r : pkg.receivers) {
10694                    r.info.encryptionAware = r.info.directBootAware = true;
10695                }
10696            }
10697            if (compressedFileExists(pkg.codePath)) {
10698                pkg.isStub = true;
10699            }
10700        } else {
10701            // non system apps can't be flagged as core
10702            pkg.coreApp = false;
10703            // clear flags not applicable to regular apps
10704            pkg.applicationInfo.flags &=
10705                    ~ApplicationInfo.FLAG_PERSISTENT;
10706            pkg.applicationInfo.privateFlags &=
10707                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10708            pkg.applicationInfo.privateFlags &=
10709                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10710            // cap permission priorities
10711            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10712                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10713                    pkg.permissionGroups.get(i).info.priority = 0;
10714                }
10715            }
10716        }
10717        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10718            // clear protected broadcasts
10719            pkg.protectedBroadcasts = null;
10720            // ignore export request for single user receivers
10721            if (pkg.receivers != null) {
10722                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10723                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10724                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10725                        receiver.info.exported = false;
10726                    }
10727                }
10728            }
10729            // ignore export request for single user services
10730            if (pkg.services != null) {
10731                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10732                    final PackageParser.Service service = pkg.services.get(i);
10733                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10734                        service.info.exported = false;
10735                    }
10736                }
10737            }
10738            // ignore export request for single user providers
10739            if (pkg.providers != null) {
10740                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10741                    final PackageParser.Provider provider = pkg.providers.get(i);
10742                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10743                        provider.info.exported = false;
10744                    }
10745                }
10746            }
10747        }
10748
10749        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10750            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10751        }
10752
10753        if ((scanFlags & SCAN_AS_OEM) != 0) {
10754            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10755        }
10756
10757        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10758            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10759        }
10760
10761        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10762            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10763        }
10764
10765        if (!isSystemApp(pkg)) {
10766            // Only system apps can use these features.
10767            pkg.mOriginalPackages = null;
10768            pkg.mRealPackage = null;
10769            pkg.mAdoptPermissions = null;
10770        }
10771    }
10772
10773    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10774            throws PackageManagerException {
10775        if (object == null) {
10776            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10777        }
10778        return object;
10779    }
10780
10781    /**
10782     * Asserts the parsed package is valid according to the given policy. If the
10783     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10784     * <p>
10785     * Implementation detail: This method must NOT have any side effects. It would
10786     * ideally be static, but, it requires locks to read system state.
10787     *
10788     * @throws PackageManagerException If the package fails any of the validation checks
10789     */
10790    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10791            final @ScanFlags int scanFlags)
10792                    throws PackageManagerException {
10793        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10794            assertCodePolicy(pkg);
10795        }
10796
10797        if (pkg.applicationInfo.getCodePath() == null ||
10798                pkg.applicationInfo.getResourcePath() == null) {
10799            // Bail out. The resource and code paths haven't been set.
10800            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10801                    "Code and resource paths haven't been set correctly");
10802        }
10803
10804        // Make sure we're not adding any bogus keyset info
10805        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10806        ksms.assertScannedPackageValid(pkg);
10807
10808        synchronized (mPackages) {
10809            // The special "android" package can only be defined once
10810            if (pkg.packageName.equals("android")) {
10811                if (mAndroidApplication != null) {
10812                    Slog.w(TAG, "*************************************************");
10813                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10814                    Slog.w(TAG, " codePath=" + pkg.codePath);
10815                    Slog.w(TAG, "*************************************************");
10816                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10817                            "Core android package being redefined.  Skipping.");
10818                }
10819            }
10820
10821            // A package name must be unique; don't allow duplicates
10822            if (mPackages.containsKey(pkg.packageName)) {
10823                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10824                        "Application package " + pkg.packageName
10825                        + " already installed.  Skipping duplicate.");
10826            }
10827
10828            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10829                // Static libs have a synthetic package name containing the version
10830                // but we still want the base name to be unique.
10831                if (mPackages.containsKey(pkg.manifestPackageName)) {
10832                    throw new PackageManagerException(
10833                            "Duplicate static shared lib provider package");
10834                }
10835
10836                // Static shared libraries should have at least O target SDK
10837                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10838                    throw new PackageManagerException(
10839                            "Packages declaring static-shared libs must target O SDK or higher");
10840                }
10841
10842                // Package declaring static a shared lib cannot be instant apps
10843                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10844                    throw new PackageManagerException(
10845                            "Packages declaring static-shared libs cannot be instant apps");
10846                }
10847
10848                // Package declaring static a shared lib cannot be renamed since the package
10849                // name is synthetic and apps can't code around package manager internals.
10850                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10851                    throw new PackageManagerException(
10852                            "Packages declaring static-shared libs cannot be renamed");
10853                }
10854
10855                // Package declaring static a shared lib cannot declare child packages
10856                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10857                    throw new PackageManagerException(
10858                            "Packages declaring static-shared libs cannot have child packages");
10859                }
10860
10861                // Package declaring static a shared lib cannot declare dynamic libs
10862                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10863                    throw new PackageManagerException(
10864                            "Packages declaring static-shared libs cannot declare dynamic libs");
10865                }
10866
10867                // Package declaring static a shared lib cannot declare shared users
10868                if (pkg.mSharedUserId != null) {
10869                    throw new PackageManagerException(
10870                            "Packages declaring static-shared libs cannot declare shared users");
10871                }
10872
10873                // Static shared libs cannot declare activities
10874                if (!pkg.activities.isEmpty()) {
10875                    throw new PackageManagerException(
10876                            "Static shared libs cannot declare activities");
10877                }
10878
10879                // Static shared libs cannot declare services
10880                if (!pkg.services.isEmpty()) {
10881                    throw new PackageManagerException(
10882                            "Static shared libs cannot declare services");
10883                }
10884
10885                // Static shared libs cannot declare providers
10886                if (!pkg.providers.isEmpty()) {
10887                    throw new PackageManagerException(
10888                            "Static shared libs cannot declare content providers");
10889                }
10890
10891                // Static shared libs cannot declare receivers
10892                if (!pkg.receivers.isEmpty()) {
10893                    throw new PackageManagerException(
10894                            "Static shared libs cannot declare broadcast receivers");
10895                }
10896
10897                // Static shared libs cannot declare permission groups
10898                if (!pkg.permissionGroups.isEmpty()) {
10899                    throw new PackageManagerException(
10900                            "Static shared libs cannot declare permission groups");
10901                }
10902
10903                // Static shared libs cannot declare permissions
10904                if (!pkg.permissions.isEmpty()) {
10905                    throw new PackageManagerException(
10906                            "Static shared libs cannot declare permissions");
10907                }
10908
10909                // Static shared libs cannot declare protected broadcasts
10910                if (pkg.protectedBroadcasts != null) {
10911                    throw new PackageManagerException(
10912                            "Static shared libs cannot declare protected broadcasts");
10913                }
10914
10915                // Static shared libs cannot be overlay targets
10916                if (pkg.mOverlayTarget != null) {
10917                    throw new PackageManagerException(
10918                            "Static shared libs cannot be overlay targets");
10919                }
10920
10921                // The version codes must be ordered as lib versions
10922                long minVersionCode = Long.MIN_VALUE;
10923                long maxVersionCode = Long.MAX_VALUE;
10924
10925                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10926                        pkg.staticSharedLibName);
10927                if (versionedLib != null) {
10928                    final int versionCount = versionedLib.size();
10929                    for (int i = 0; i < versionCount; i++) {
10930                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10931                        final long libVersionCode = libInfo.getDeclaringPackage()
10932                                .getLongVersionCode();
10933                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10934                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10935                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10936                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10937                        } else {
10938                            minVersionCode = maxVersionCode = libVersionCode;
10939                            break;
10940                        }
10941                    }
10942                }
10943                if (pkg.getLongVersionCode() < minVersionCode
10944                        || pkg.getLongVersionCode() > maxVersionCode) {
10945                    throw new PackageManagerException("Static shared"
10946                            + " lib version codes must be ordered as lib versions");
10947                }
10948            }
10949
10950            // Only privileged apps and updated privileged apps can add child packages.
10951            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10952                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10953                    throw new PackageManagerException("Only privileged apps can add child "
10954                            + "packages. Ignoring package " + pkg.packageName);
10955                }
10956                final int childCount = pkg.childPackages.size();
10957                for (int i = 0; i < childCount; i++) {
10958                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10959                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10960                            childPkg.packageName)) {
10961                        throw new PackageManagerException("Can't override child of "
10962                                + "another disabled app. Ignoring package " + pkg.packageName);
10963                    }
10964                }
10965            }
10966
10967            // If we're only installing presumed-existing packages, require that the
10968            // scanned APK is both already known and at the path previously established
10969            // for it.  Previously unknown packages we pick up normally, but if we have an
10970            // a priori expectation about this package's install presence, enforce it.
10971            // With a singular exception for new system packages. When an OTA contains
10972            // a new system package, we allow the codepath to change from a system location
10973            // to the user-installed location. If we don't allow this change, any newer,
10974            // user-installed version of the application will be ignored.
10975            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10976                if (mExpectingBetter.containsKey(pkg.packageName)) {
10977                    logCriticalInfo(Log.WARN,
10978                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10979                } else {
10980                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10981                    if (known != null) {
10982                        if (DEBUG_PACKAGE_SCANNING) {
10983                            Log.d(TAG, "Examining " + pkg.codePath
10984                                    + " and requiring known paths " + known.codePathString
10985                                    + " & " + known.resourcePathString);
10986                        }
10987                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10988                                || !pkg.applicationInfo.getResourcePath().equals(
10989                                        known.resourcePathString)) {
10990                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10991                                    "Application package " + pkg.packageName
10992                                    + " found at " + pkg.applicationInfo.getCodePath()
10993                                    + " but expected at " + known.codePathString
10994                                    + "; ignoring.");
10995                        }
10996                    } else {
10997                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10998                                "Application package " + pkg.packageName
10999                                + " not found; ignoring.");
11000                    }
11001                }
11002            }
11003
11004            // Verify that this new package doesn't have any content providers
11005            // that conflict with existing packages.  Only do this if the
11006            // package isn't already installed, since we don't want to break
11007            // things that are installed.
11008            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11009                final int N = pkg.providers.size();
11010                int i;
11011                for (i=0; i<N; i++) {
11012                    PackageParser.Provider p = pkg.providers.get(i);
11013                    if (p.info.authority != null) {
11014                        String names[] = p.info.authority.split(";");
11015                        for (int j = 0; j < names.length; j++) {
11016                            if (mProvidersByAuthority.containsKey(names[j])) {
11017                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11018                                final String otherPackageName =
11019                                        ((other != null && other.getComponentName() != null) ?
11020                                                other.getComponentName().getPackageName() : "?");
11021                                throw new PackageManagerException(
11022                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11023                                        "Can't install because provider name " + names[j]
11024                                                + " (in package " + pkg.applicationInfo.packageName
11025                                                + ") is already used by " + otherPackageName);
11026                            }
11027                        }
11028                    }
11029                }
11030            }
11031
11032            // Verify that packages sharing a user with a privileged app are marked as privileged.
11033            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11034                SharedUserSetting sharedUserSetting = null;
11035                try {
11036                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11037                } catch (PackageManagerException ignore) {}
11038                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11039                    // Exempt SharedUsers signed with the platform key.
11040                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11041                    if ((platformPkgSetting.signatures.mSigningDetails
11042                            != PackageParser.SigningDetails.UNKNOWN)
11043                            && (compareSignatures(
11044                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11045                                    pkg.mSigningDetails.signatures)
11046                                            != PackageManager.SIGNATURE_MATCH)) {
11047                        throw new PackageManagerException("Apps that share a user with a " +
11048                                "privileged app must themselves be marked as privileged. " +
11049                                pkg.packageName + " shares privileged user " +
11050                                pkg.mSharedUserId + ".");
11051                    }
11052                }
11053            }
11054
11055            // Apply policies specific for runtime resource overlays (RROs).
11056            if (pkg.mOverlayTarget != null) {
11057                // System overlays have some restrictions on their use of the 'static' state.
11058                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11059                    // We are scanning a system overlay. This can be the first scan of the
11060                    // system/vendor/oem partition, or an update to the system overlay.
11061                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11062                        // This must be an update to a system overlay.
11063                        final PackageSetting previousPkg = assertNotNull(
11064                                mSettings.getPackageLPr(pkg.packageName),
11065                                "previous package state not present");
11066
11067                        // Static overlays cannot be updated.
11068                        if (previousPkg.pkg.mOverlayIsStatic) {
11069                            throw new PackageManagerException("Overlay " + pkg.packageName +
11070                                    " is static and cannot be upgraded.");
11071                        // Non-static overlays cannot be converted to static overlays.
11072                        } else if (pkg.mOverlayIsStatic) {
11073                            throw new PackageManagerException("Overlay " + pkg.packageName +
11074                                    " cannot be upgraded into a static overlay.");
11075                        }
11076                    }
11077                } else {
11078                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11079                    if (pkg.mOverlayIsStatic) {
11080                        throw new PackageManagerException("Overlay " + pkg.packageName +
11081                                " is static but not pre-installed.");
11082                    }
11083
11084                    // The only case where we allow installation of a non-system overlay is when
11085                    // its signature is signed with the platform certificate.
11086                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11087                    if ((platformPkgSetting.signatures.mSigningDetails
11088                            != PackageParser.SigningDetails.UNKNOWN)
11089                            && (compareSignatures(
11090                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11091                                    pkg.mSigningDetails.signatures)
11092                                            != PackageManager.SIGNATURE_MATCH)) {
11093                        throw new PackageManagerException("Overlay " + pkg.packageName +
11094                                " must be signed with the platform certificate.");
11095                    }
11096                }
11097            }
11098        }
11099    }
11100
11101    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11102            int type, String declaringPackageName, long declaringVersionCode) {
11103        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11104        if (versionedLib == null) {
11105            versionedLib = new LongSparseArray<>();
11106            mSharedLibraries.put(name, versionedLib);
11107            if (type == SharedLibraryInfo.TYPE_STATIC) {
11108                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11109            }
11110        } else if (versionedLib.indexOfKey(version) >= 0) {
11111            return false;
11112        }
11113        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11114                version, type, declaringPackageName, declaringVersionCode);
11115        versionedLib.put(version, libEntry);
11116        return true;
11117    }
11118
11119    private boolean removeSharedLibraryLPw(String name, long version) {
11120        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11121        if (versionedLib == null) {
11122            return false;
11123        }
11124        final int libIdx = versionedLib.indexOfKey(version);
11125        if (libIdx < 0) {
11126            return false;
11127        }
11128        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11129        versionedLib.remove(version);
11130        if (versionedLib.size() <= 0) {
11131            mSharedLibraries.remove(name);
11132            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11133                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11134                        .getPackageName());
11135            }
11136        }
11137        return true;
11138    }
11139
11140    /**
11141     * Adds a scanned package to the system. When this method is finished, the package will
11142     * be available for query, resolution, etc...
11143     */
11144    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11145            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11146        final String pkgName = pkg.packageName;
11147        if (mCustomResolverComponentName != null &&
11148                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11149            setUpCustomResolverActivity(pkg);
11150        }
11151
11152        if (pkg.packageName.equals("android")) {
11153            synchronized (mPackages) {
11154                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11155                    // Set up information for our fall-back user intent resolution activity.
11156                    mPlatformPackage = pkg;
11157                    pkg.mVersionCode = mSdkVersion;
11158                    pkg.mVersionCodeMajor = 0;
11159                    mAndroidApplication = pkg.applicationInfo;
11160                    if (!mResolverReplaced) {
11161                        mResolveActivity.applicationInfo = mAndroidApplication;
11162                        mResolveActivity.name = ResolverActivity.class.getName();
11163                        mResolveActivity.packageName = mAndroidApplication.packageName;
11164                        mResolveActivity.processName = "system:ui";
11165                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11166                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11167                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11168                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11169                        mResolveActivity.exported = true;
11170                        mResolveActivity.enabled = true;
11171                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11172                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11173                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11174                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11175                                | ActivityInfo.CONFIG_ORIENTATION
11176                                | ActivityInfo.CONFIG_KEYBOARD
11177                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11178                        mResolveInfo.activityInfo = mResolveActivity;
11179                        mResolveInfo.priority = 0;
11180                        mResolveInfo.preferredOrder = 0;
11181                        mResolveInfo.match = 0;
11182                        mResolveComponentName = new ComponentName(
11183                                mAndroidApplication.packageName, mResolveActivity.name);
11184                    }
11185                }
11186            }
11187        }
11188
11189        ArrayList<PackageParser.Package> clientLibPkgs = null;
11190        // writer
11191        synchronized (mPackages) {
11192            boolean hasStaticSharedLibs = false;
11193
11194            // Any app can add new static shared libraries
11195            if (pkg.staticSharedLibName != null) {
11196                // Static shared libs don't allow renaming as they have synthetic package
11197                // names to allow install of multiple versions, so use name from manifest.
11198                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11199                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11200                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11201                    hasStaticSharedLibs = true;
11202                } else {
11203                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11204                                + pkg.staticSharedLibName + " already exists; skipping");
11205                }
11206                // Static shared libs cannot be updated once installed since they
11207                // use synthetic package name which includes the version code, so
11208                // not need to update other packages's shared lib dependencies.
11209            }
11210
11211            if (!hasStaticSharedLibs
11212                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11213                // Only system apps can add new dynamic shared libraries.
11214                if (pkg.libraryNames != null) {
11215                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11216                        String name = pkg.libraryNames.get(i);
11217                        boolean allowed = false;
11218                        if (pkg.isUpdatedSystemApp()) {
11219                            // New library entries can only be added through the
11220                            // system image.  This is important to get rid of a lot
11221                            // of nasty edge cases: for example if we allowed a non-
11222                            // system update of the app to add a library, then uninstalling
11223                            // the update would make the library go away, and assumptions
11224                            // we made such as through app install filtering would now
11225                            // have allowed apps on the device which aren't compatible
11226                            // with it.  Better to just have the restriction here, be
11227                            // conservative, and create many fewer cases that can negatively
11228                            // impact the user experience.
11229                            final PackageSetting sysPs = mSettings
11230                                    .getDisabledSystemPkgLPr(pkg.packageName);
11231                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11232                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11233                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11234                                        allowed = true;
11235                                        break;
11236                                    }
11237                                }
11238                            }
11239                        } else {
11240                            allowed = true;
11241                        }
11242                        if (allowed) {
11243                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11244                                    SharedLibraryInfo.VERSION_UNDEFINED,
11245                                    SharedLibraryInfo.TYPE_DYNAMIC,
11246                                    pkg.packageName, pkg.getLongVersionCode())) {
11247                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11248                                        + name + " already exists; skipping");
11249                            }
11250                        } else {
11251                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11252                                    + name + " that is not declared on system image; skipping");
11253                        }
11254                    }
11255
11256                    if ((scanFlags & SCAN_BOOTING) == 0) {
11257                        // If we are not booting, we need to update any applications
11258                        // that are clients of our shared library.  If we are booting,
11259                        // this will all be done once the scan is complete.
11260                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11261                    }
11262                }
11263            }
11264        }
11265
11266        if ((scanFlags & SCAN_BOOTING) != 0) {
11267            // No apps can run during boot scan, so they don't need to be frozen
11268        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11269            // Caller asked to not kill app, so it's probably not frozen
11270        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11271            // Caller asked us to ignore frozen check for some reason; they
11272            // probably didn't know the package name
11273        } else {
11274            // We're doing major surgery on this package, so it better be frozen
11275            // right now to keep it from launching
11276            checkPackageFrozen(pkgName);
11277        }
11278
11279        // Also need to kill any apps that are dependent on the library.
11280        if (clientLibPkgs != null) {
11281            for (int i=0; i<clientLibPkgs.size(); i++) {
11282                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11283                killApplication(clientPkg.applicationInfo.packageName,
11284                        clientPkg.applicationInfo.uid, "update lib");
11285            }
11286        }
11287
11288        // writer
11289        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11290
11291        synchronized (mPackages) {
11292            // We don't expect installation to fail beyond this point
11293
11294            // Add the new setting to mSettings
11295            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11296            // Add the new setting to mPackages
11297            mPackages.put(pkg.applicationInfo.packageName, pkg);
11298            // Make sure we don't accidentally delete its data.
11299            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11300            while (iter.hasNext()) {
11301                PackageCleanItem item = iter.next();
11302                if (pkgName.equals(item.packageName)) {
11303                    iter.remove();
11304                }
11305            }
11306
11307            // Add the package's KeySets to the global KeySetManagerService
11308            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11309            ksms.addScannedPackageLPw(pkg);
11310
11311            int N = pkg.providers.size();
11312            StringBuilder r = null;
11313            int i;
11314            for (i=0; i<N; i++) {
11315                PackageParser.Provider p = pkg.providers.get(i);
11316                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11317                        p.info.processName);
11318                mProviders.addProvider(p);
11319                p.syncable = p.info.isSyncable;
11320                if (p.info.authority != null) {
11321                    String names[] = p.info.authority.split(";");
11322                    p.info.authority = null;
11323                    for (int j = 0; j < names.length; j++) {
11324                        if (j == 1 && p.syncable) {
11325                            // We only want the first authority for a provider to possibly be
11326                            // syncable, so if we already added this provider using a different
11327                            // authority clear the syncable flag. We copy the provider before
11328                            // changing it because the mProviders object contains a reference
11329                            // to a provider that we don't want to change.
11330                            // Only do this for the second authority since the resulting provider
11331                            // object can be the same for all future authorities for this provider.
11332                            p = new PackageParser.Provider(p);
11333                            p.syncable = false;
11334                        }
11335                        if (!mProvidersByAuthority.containsKey(names[j])) {
11336                            mProvidersByAuthority.put(names[j], p);
11337                            if (p.info.authority == null) {
11338                                p.info.authority = names[j];
11339                            } else {
11340                                p.info.authority = p.info.authority + ";" + names[j];
11341                            }
11342                            if (DEBUG_PACKAGE_SCANNING) {
11343                                if (chatty)
11344                                    Log.d(TAG, "Registered content provider: " + names[j]
11345                                            + ", className = " + p.info.name + ", isSyncable = "
11346                                            + p.info.isSyncable);
11347                            }
11348                        } else {
11349                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11350                            Slog.w(TAG, "Skipping provider name " + names[j] +
11351                                    " (in package " + pkg.applicationInfo.packageName +
11352                                    "): name already used by "
11353                                    + ((other != null && other.getComponentName() != null)
11354                                            ? other.getComponentName().getPackageName() : "?"));
11355                        }
11356                    }
11357                }
11358                if (chatty) {
11359                    if (r == null) {
11360                        r = new StringBuilder(256);
11361                    } else {
11362                        r.append(' ');
11363                    }
11364                    r.append(p.info.name);
11365                }
11366            }
11367            if (r != null) {
11368                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11369            }
11370
11371            N = pkg.services.size();
11372            r = null;
11373            for (i=0; i<N; i++) {
11374                PackageParser.Service s = pkg.services.get(i);
11375                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11376                        s.info.processName);
11377                mServices.addService(s);
11378                if (chatty) {
11379                    if (r == null) {
11380                        r = new StringBuilder(256);
11381                    } else {
11382                        r.append(' ');
11383                    }
11384                    r.append(s.info.name);
11385                }
11386            }
11387            if (r != null) {
11388                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11389            }
11390
11391            N = pkg.receivers.size();
11392            r = null;
11393            for (i=0; i<N; i++) {
11394                PackageParser.Activity a = pkg.receivers.get(i);
11395                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11396                        a.info.processName);
11397                mReceivers.addActivity(a, "receiver");
11398                if (chatty) {
11399                    if (r == null) {
11400                        r = new StringBuilder(256);
11401                    } else {
11402                        r.append(' ');
11403                    }
11404                    r.append(a.info.name);
11405                }
11406            }
11407            if (r != null) {
11408                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11409            }
11410
11411            N = pkg.activities.size();
11412            r = null;
11413            for (i=0; i<N; i++) {
11414                PackageParser.Activity a = pkg.activities.get(i);
11415                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11416                        a.info.processName);
11417                mActivities.addActivity(a, "activity");
11418                if (chatty) {
11419                    if (r == null) {
11420                        r = new StringBuilder(256);
11421                    } else {
11422                        r.append(' ');
11423                    }
11424                    r.append(a.info.name);
11425                }
11426            }
11427            if (r != null) {
11428                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11429            }
11430
11431            // Don't allow ephemeral applications to define new permissions groups.
11432            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11433                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11434                        + " ignored: instant apps cannot define new permission groups.");
11435            } else {
11436                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11437            }
11438
11439            // Don't allow ephemeral applications to define new permissions.
11440            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11441                Slog.w(TAG, "Permissions from package " + pkg.packageName
11442                        + " ignored: instant apps cannot define new permissions.");
11443            } else {
11444                mPermissionManager.addAllPermissions(pkg, chatty);
11445            }
11446
11447            N = pkg.instrumentation.size();
11448            r = null;
11449            for (i=0; i<N; i++) {
11450                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11451                a.info.packageName = pkg.applicationInfo.packageName;
11452                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11453                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11454                a.info.splitNames = pkg.splitNames;
11455                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11456                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11457                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11458                a.info.dataDir = pkg.applicationInfo.dataDir;
11459                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11460                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11461                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11462                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11463                mInstrumentation.put(a.getComponentName(), a);
11464                if (chatty) {
11465                    if (r == null) {
11466                        r = new StringBuilder(256);
11467                    } else {
11468                        r.append(' ');
11469                    }
11470                    r.append(a.info.name);
11471                }
11472            }
11473            if (r != null) {
11474                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11475            }
11476
11477            if (pkg.protectedBroadcasts != null) {
11478                N = pkg.protectedBroadcasts.size();
11479                synchronized (mProtectedBroadcasts) {
11480                    for (i = 0; i < N; i++) {
11481                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11482                    }
11483                }
11484            }
11485        }
11486
11487        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11488    }
11489
11490    /**
11491     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11492     * is derived purely on the basis of the contents of {@code scanFile} and
11493     * {@code cpuAbiOverride}.
11494     *
11495     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11496     */
11497    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11498            boolean extractLibs)
11499                    throws PackageManagerException {
11500        // Give ourselves some initial paths; we'll come back for another
11501        // pass once we've determined ABI below.
11502        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11503
11504        // We would never need to extract libs for forward-locked and external packages,
11505        // since the container service will do it for us. We shouldn't attempt to
11506        // extract libs from system app when it was not updated.
11507        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11508                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11509            extractLibs = false;
11510        }
11511
11512        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11513        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11514
11515        NativeLibraryHelper.Handle handle = null;
11516        try {
11517            handle = NativeLibraryHelper.Handle.create(pkg);
11518            // TODO(multiArch): This can be null for apps that didn't go through the
11519            // usual installation process. We can calculate it again, like we
11520            // do during install time.
11521            //
11522            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11523            // unnecessary.
11524            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11525
11526            // Null out the abis so that they can be recalculated.
11527            pkg.applicationInfo.primaryCpuAbi = null;
11528            pkg.applicationInfo.secondaryCpuAbi = null;
11529            if (isMultiArch(pkg.applicationInfo)) {
11530                // Warn if we've set an abiOverride for multi-lib packages..
11531                // By definition, we need to copy both 32 and 64 bit libraries for
11532                // such packages.
11533                if (pkg.cpuAbiOverride != null
11534                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11535                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11536                }
11537
11538                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11539                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11540                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11541                    if (extractLibs) {
11542                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11543                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11544                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11545                                useIsaSpecificSubdirs);
11546                    } else {
11547                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11548                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11549                    }
11550                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11551                }
11552
11553                // Shared library native code should be in the APK zip aligned
11554                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11555                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11556                            "Shared library native lib extraction not supported");
11557                }
11558
11559                maybeThrowExceptionForMultiArchCopy(
11560                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11561
11562                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11563                    if (extractLibs) {
11564                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11565                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11566                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11567                                useIsaSpecificSubdirs);
11568                    } else {
11569                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11570                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11571                    }
11572                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11573                }
11574
11575                maybeThrowExceptionForMultiArchCopy(
11576                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11577
11578                if (abi64 >= 0) {
11579                    // Shared library native libs should be in the APK zip aligned
11580                    if (extractLibs && pkg.isLibrary()) {
11581                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11582                                "Shared library native lib extraction not supported");
11583                    }
11584                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11585                }
11586
11587                if (abi32 >= 0) {
11588                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11589                    if (abi64 >= 0) {
11590                        if (pkg.use32bitAbi) {
11591                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11592                            pkg.applicationInfo.primaryCpuAbi = abi;
11593                        } else {
11594                            pkg.applicationInfo.secondaryCpuAbi = abi;
11595                        }
11596                    } else {
11597                        pkg.applicationInfo.primaryCpuAbi = abi;
11598                    }
11599                }
11600            } else {
11601                String[] abiList = (cpuAbiOverride != null) ?
11602                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11603
11604                // Enable gross and lame hacks for apps that are built with old
11605                // SDK tools. We must scan their APKs for renderscript bitcode and
11606                // not launch them if it's present. Don't bother checking on devices
11607                // that don't have 64 bit support.
11608                boolean needsRenderScriptOverride = false;
11609                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11610                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11611                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11612                    needsRenderScriptOverride = true;
11613                }
11614
11615                final int copyRet;
11616                if (extractLibs) {
11617                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11618                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11619                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11620                } else {
11621                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11622                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11623                }
11624                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11625
11626                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11627                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11628                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11629                }
11630
11631                if (copyRet >= 0) {
11632                    // Shared libraries that have native libs must be multi-architecture
11633                    if (pkg.isLibrary()) {
11634                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11635                                "Shared library with native libs must be multiarch");
11636                    }
11637                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11638                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11639                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11640                } else if (needsRenderScriptOverride) {
11641                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11642                }
11643            }
11644        } catch (IOException ioe) {
11645            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11646        } finally {
11647            IoUtils.closeQuietly(handle);
11648        }
11649
11650        // Now that we've calculated the ABIs and determined if it's an internal app,
11651        // we will go ahead and populate the nativeLibraryPath.
11652        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11653    }
11654
11655    /**
11656     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11657     * i.e, so that all packages can be run inside a single process if required.
11658     *
11659     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11660     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11661     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11662     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11663     * updating a package that belongs to a shared user.
11664     *
11665     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11666     * adds unnecessary complexity.
11667     */
11668    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11669            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11670        List<String> changedAbiCodePath = null;
11671        String requiredInstructionSet = null;
11672        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11673            requiredInstructionSet = VMRuntime.getInstructionSet(
11674                     scannedPackage.applicationInfo.primaryCpuAbi);
11675        }
11676
11677        PackageSetting requirer = null;
11678        for (PackageSetting ps : packagesForUser) {
11679            // If packagesForUser contains scannedPackage, we skip it. This will happen
11680            // when scannedPackage is an update of an existing package. Without this check,
11681            // we will never be able to change the ABI of any package belonging to a shared
11682            // user, even if it's compatible with other packages.
11683            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11684                if (ps.primaryCpuAbiString == null) {
11685                    continue;
11686                }
11687
11688                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11689                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11690                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11691                    // this but there's not much we can do.
11692                    String errorMessage = "Instruction set mismatch, "
11693                            + ((requirer == null) ? "[caller]" : requirer)
11694                            + " requires " + requiredInstructionSet + " whereas " + ps
11695                            + " requires " + instructionSet;
11696                    Slog.w(TAG, errorMessage);
11697                }
11698
11699                if (requiredInstructionSet == null) {
11700                    requiredInstructionSet = instructionSet;
11701                    requirer = ps;
11702                }
11703            }
11704        }
11705
11706        if (requiredInstructionSet != null) {
11707            String adjustedAbi;
11708            if (requirer != null) {
11709                // requirer != null implies that either scannedPackage was null or that scannedPackage
11710                // did not require an ABI, in which case we have to adjust scannedPackage to match
11711                // the ABI of the set (which is the same as requirer's ABI)
11712                adjustedAbi = requirer.primaryCpuAbiString;
11713                if (scannedPackage != null) {
11714                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11715                }
11716            } else {
11717                // requirer == null implies that we're updating all ABIs in the set to
11718                // match scannedPackage.
11719                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11720            }
11721
11722            for (PackageSetting ps : packagesForUser) {
11723                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11724                    if (ps.primaryCpuAbiString != null) {
11725                        continue;
11726                    }
11727
11728                    ps.primaryCpuAbiString = adjustedAbi;
11729                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11730                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11731                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11732                        if (DEBUG_ABI_SELECTION) {
11733                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11734                                    + " (requirer="
11735                                    + (requirer != null ? requirer.pkg : "null")
11736                                    + ", scannedPackage="
11737                                    + (scannedPackage != null ? scannedPackage : "null")
11738                                    + ")");
11739                        }
11740                        if (changedAbiCodePath == null) {
11741                            changedAbiCodePath = new ArrayList<>();
11742                        }
11743                        changedAbiCodePath.add(ps.codePathString);
11744                    }
11745                }
11746            }
11747        }
11748        return changedAbiCodePath;
11749    }
11750
11751    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11752        synchronized (mPackages) {
11753            mResolverReplaced = true;
11754            // Set up information for custom user intent resolution activity.
11755            mResolveActivity.applicationInfo = pkg.applicationInfo;
11756            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11757            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11758            mResolveActivity.processName = pkg.applicationInfo.packageName;
11759            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11760            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11761                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11762            mResolveActivity.theme = 0;
11763            mResolveActivity.exported = true;
11764            mResolveActivity.enabled = true;
11765            mResolveInfo.activityInfo = mResolveActivity;
11766            mResolveInfo.priority = 0;
11767            mResolveInfo.preferredOrder = 0;
11768            mResolveInfo.match = 0;
11769            mResolveComponentName = mCustomResolverComponentName;
11770            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11771                    mResolveComponentName);
11772        }
11773    }
11774
11775    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11776        if (installerActivity == null) {
11777            if (DEBUG_INSTANT) {
11778                Slog.d(TAG, "Clear ephemeral installer activity");
11779            }
11780            mInstantAppInstallerActivity = null;
11781            return;
11782        }
11783
11784        if (DEBUG_INSTANT) {
11785            Slog.d(TAG, "Set ephemeral installer activity: "
11786                    + installerActivity.getComponentName());
11787        }
11788        // Set up information for ephemeral installer activity
11789        mInstantAppInstallerActivity = installerActivity;
11790        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11791                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11792        mInstantAppInstallerActivity.exported = true;
11793        mInstantAppInstallerActivity.enabled = true;
11794        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11795        mInstantAppInstallerInfo.priority = 1;
11796        mInstantAppInstallerInfo.preferredOrder = 1;
11797        mInstantAppInstallerInfo.isDefault = true;
11798        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11799                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11800    }
11801
11802    private static String calculateBundledApkRoot(final String codePathString) {
11803        final File codePath = new File(codePathString);
11804        final File codeRoot;
11805        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11806            codeRoot = Environment.getRootDirectory();
11807        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11808            codeRoot = Environment.getOemDirectory();
11809        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11810            codeRoot = Environment.getVendorDirectory();
11811        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11812            codeRoot = Environment.getOdmDirectory();
11813        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11814            codeRoot = Environment.getProductDirectory();
11815        } else {
11816            // Unrecognized code path; take its top real segment as the apk root:
11817            // e.g. /something/app/blah.apk => /something
11818            try {
11819                File f = codePath.getCanonicalFile();
11820                File parent = f.getParentFile();    // non-null because codePath is a file
11821                File tmp;
11822                while ((tmp = parent.getParentFile()) != null) {
11823                    f = parent;
11824                    parent = tmp;
11825                }
11826                codeRoot = f;
11827                Slog.w(TAG, "Unrecognized code path "
11828                        + codePath + " - using " + codeRoot);
11829            } catch (IOException e) {
11830                // Can't canonicalize the code path -- shenanigans?
11831                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11832                return Environment.getRootDirectory().getPath();
11833            }
11834        }
11835        return codeRoot.getPath();
11836    }
11837
11838    /**
11839     * Derive and set the location of native libraries for the given package,
11840     * which varies depending on where and how the package was installed.
11841     */
11842    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11843        final ApplicationInfo info = pkg.applicationInfo;
11844        final String codePath = pkg.codePath;
11845        final File codeFile = new File(codePath);
11846        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11847        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11848
11849        info.nativeLibraryRootDir = null;
11850        info.nativeLibraryRootRequiresIsa = false;
11851        info.nativeLibraryDir = null;
11852        info.secondaryNativeLibraryDir = null;
11853
11854        if (isApkFile(codeFile)) {
11855            // Monolithic install
11856            if (bundledApp) {
11857                // If "/system/lib64/apkname" exists, assume that is the per-package
11858                // native library directory to use; otherwise use "/system/lib/apkname".
11859                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11860                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11861                        getPrimaryInstructionSet(info));
11862
11863                // This is a bundled system app so choose the path based on the ABI.
11864                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11865                // is just the default path.
11866                final String apkName = deriveCodePathName(codePath);
11867                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11868                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11869                        apkName).getAbsolutePath();
11870
11871                if (info.secondaryCpuAbi != null) {
11872                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11873                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11874                            secondaryLibDir, apkName).getAbsolutePath();
11875                }
11876            } else if (asecApp) {
11877                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11878                        .getAbsolutePath();
11879            } else {
11880                final String apkName = deriveCodePathName(codePath);
11881                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11882                        .getAbsolutePath();
11883            }
11884
11885            info.nativeLibraryRootRequiresIsa = false;
11886            info.nativeLibraryDir = info.nativeLibraryRootDir;
11887        } else {
11888            // Cluster install
11889            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11890            info.nativeLibraryRootRequiresIsa = true;
11891
11892            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11893                    getPrimaryInstructionSet(info)).getAbsolutePath();
11894
11895            if (info.secondaryCpuAbi != null) {
11896                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11897                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11898            }
11899        }
11900    }
11901
11902    /**
11903     * Calculate the abis and roots for a bundled app. These can uniquely
11904     * be determined from the contents of the system partition, i.e whether
11905     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11906     * of this information, and instead assume that the system was built
11907     * sensibly.
11908     */
11909    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11910                                           PackageSetting pkgSetting) {
11911        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11912
11913        // If "/system/lib64/apkname" exists, assume that is the per-package
11914        // native library directory to use; otherwise use "/system/lib/apkname".
11915        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11916        setBundledAppAbi(pkg, apkRoot, apkName);
11917        // pkgSetting might be null during rescan following uninstall of updates
11918        // to a bundled app, so accommodate that possibility.  The settings in
11919        // that case will be established later from the parsed package.
11920        //
11921        // If the settings aren't null, sync them up with what we've just derived.
11922        // note that apkRoot isn't stored in the package settings.
11923        if (pkgSetting != null) {
11924            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11925            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11926        }
11927    }
11928
11929    /**
11930     * Deduces the ABI of a bundled app and sets the relevant fields on the
11931     * parsed pkg object.
11932     *
11933     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11934     *        under which system libraries are installed.
11935     * @param apkName the name of the installed package.
11936     */
11937    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11938        final File codeFile = new File(pkg.codePath);
11939
11940        final boolean has64BitLibs;
11941        final boolean has32BitLibs;
11942        if (isApkFile(codeFile)) {
11943            // Monolithic install
11944            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11945            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11946        } else {
11947            // Cluster install
11948            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11949            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11950                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11951                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11952                has64BitLibs = (new File(rootDir, isa)).exists();
11953            } else {
11954                has64BitLibs = false;
11955            }
11956            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11957                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11958                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11959                has32BitLibs = (new File(rootDir, isa)).exists();
11960            } else {
11961                has32BitLibs = false;
11962            }
11963        }
11964
11965        if (has64BitLibs && !has32BitLibs) {
11966            // The package has 64 bit libs, but not 32 bit libs. Its primary
11967            // ABI should be 64 bit. We can safely assume here that the bundled
11968            // native libraries correspond to the most preferred ABI in the list.
11969
11970            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11971            pkg.applicationInfo.secondaryCpuAbi = null;
11972        } else if (has32BitLibs && !has64BitLibs) {
11973            // The package has 32 bit libs but not 64 bit libs. Its primary
11974            // ABI should be 32 bit.
11975
11976            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11977            pkg.applicationInfo.secondaryCpuAbi = null;
11978        } else if (has32BitLibs && has64BitLibs) {
11979            // The application has both 64 and 32 bit bundled libraries. We check
11980            // here that the app declares multiArch support, and warn if it doesn't.
11981            //
11982            // We will be lenient here and record both ABIs. The primary will be the
11983            // ABI that's higher on the list, i.e, a device that's configured to prefer
11984            // 64 bit apps will see a 64 bit primary ABI,
11985
11986            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11987                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11988            }
11989
11990            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11991                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11992                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11993            } else {
11994                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11995                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11996            }
11997        } else {
11998            pkg.applicationInfo.primaryCpuAbi = null;
11999            pkg.applicationInfo.secondaryCpuAbi = null;
12000        }
12001    }
12002
12003    private void killApplication(String pkgName, int appId, String reason) {
12004        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12005    }
12006
12007    private void killApplication(String pkgName, int appId, int userId, String reason) {
12008        // Request the ActivityManager to kill the process(only for existing packages)
12009        // so that we do not end up in a confused state while the user is still using the older
12010        // version of the application while the new one gets installed.
12011        final long token = Binder.clearCallingIdentity();
12012        try {
12013            IActivityManager am = ActivityManager.getService();
12014            if (am != null) {
12015                try {
12016                    am.killApplication(pkgName, appId, userId, reason);
12017                } catch (RemoteException e) {
12018                }
12019            }
12020        } finally {
12021            Binder.restoreCallingIdentity(token);
12022        }
12023    }
12024
12025    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12026        // Remove the parent package setting
12027        PackageSetting ps = (PackageSetting) pkg.mExtras;
12028        if (ps != null) {
12029            removePackageLI(ps, chatty);
12030        }
12031        // Remove the child package setting
12032        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12033        for (int i = 0; i < childCount; i++) {
12034            PackageParser.Package childPkg = pkg.childPackages.get(i);
12035            ps = (PackageSetting) childPkg.mExtras;
12036            if (ps != null) {
12037                removePackageLI(ps, chatty);
12038            }
12039        }
12040    }
12041
12042    void removePackageLI(PackageSetting ps, boolean chatty) {
12043        if (DEBUG_INSTALL) {
12044            if (chatty)
12045                Log.d(TAG, "Removing package " + ps.name);
12046        }
12047
12048        // writer
12049        synchronized (mPackages) {
12050            mPackages.remove(ps.name);
12051            final PackageParser.Package pkg = ps.pkg;
12052            if (pkg != null) {
12053                cleanPackageDataStructuresLILPw(pkg, chatty);
12054            }
12055        }
12056    }
12057
12058    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12059        if (DEBUG_INSTALL) {
12060            if (chatty)
12061                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12062        }
12063
12064        // writer
12065        synchronized (mPackages) {
12066            // Remove the parent package
12067            mPackages.remove(pkg.applicationInfo.packageName);
12068            cleanPackageDataStructuresLILPw(pkg, chatty);
12069
12070            // Remove the child packages
12071            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12072            for (int i = 0; i < childCount; i++) {
12073                PackageParser.Package childPkg = pkg.childPackages.get(i);
12074                mPackages.remove(childPkg.applicationInfo.packageName);
12075                cleanPackageDataStructuresLILPw(childPkg, chatty);
12076            }
12077        }
12078    }
12079
12080    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12081        int N = pkg.providers.size();
12082        StringBuilder r = null;
12083        int i;
12084        for (i=0; i<N; i++) {
12085            PackageParser.Provider p = pkg.providers.get(i);
12086            mProviders.removeProvider(p);
12087            if (p.info.authority == null) {
12088
12089                /* There was another ContentProvider with this authority when
12090                 * this app was installed so this authority is null,
12091                 * Ignore it as we don't have to unregister the provider.
12092                 */
12093                continue;
12094            }
12095            String names[] = p.info.authority.split(";");
12096            for (int j = 0; j < names.length; j++) {
12097                if (mProvidersByAuthority.get(names[j]) == p) {
12098                    mProvidersByAuthority.remove(names[j]);
12099                    if (DEBUG_REMOVE) {
12100                        if (chatty)
12101                            Log.d(TAG, "Unregistered content provider: " + names[j]
12102                                    + ", className = " + p.info.name + ", isSyncable = "
12103                                    + p.info.isSyncable);
12104                    }
12105                }
12106            }
12107            if (DEBUG_REMOVE && chatty) {
12108                if (r == null) {
12109                    r = new StringBuilder(256);
12110                } else {
12111                    r.append(' ');
12112                }
12113                r.append(p.info.name);
12114            }
12115        }
12116        if (r != null) {
12117            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12118        }
12119
12120        N = pkg.services.size();
12121        r = null;
12122        for (i=0; i<N; i++) {
12123            PackageParser.Service s = pkg.services.get(i);
12124            mServices.removeService(s);
12125            if (chatty) {
12126                if (r == null) {
12127                    r = new StringBuilder(256);
12128                } else {
12129                    r.append(' ');
12130                }
12131                r.append(s.info.name);
12132            }
12133        }
12134        if (r != null) {
12135            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12136        }
12137
12138        N = pkg.receivers.size();
12139        r = null;
12140        for (i=0; i<N; i++) {
12141            PackageParser.Activity a = pkg.receivers.get(i);
12142            mReceivers.removeActivity(a, "receiver");
12143            if (DEBUG_REMOVE && chatty) {
12144                if (r == null) {
12145                    r = new StringBuilder(256);
12146                } else {
12147                    r.append(' ');
12148                }
12149                r.append(a.info.name);
12150            }
12151        }
12152        if (r != null) {
12153            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12154        }
12155
12156        N = pkg.activities.size();
12157        r = null;
12158        for (i=0; i<N; i++) {
12159            PackageParser.Activity a = pkg.activities.get(i);
12160            mActivities.removeActivity(a, "activity");
12161            if (DEBUG_REMOVE && chatty) {
12162                if (r == null) {
12163                    r = new StringBuilder(256);
12164                } else {
12165                    r.append(' ');
12166                }
12167                r.append(a.info.name);
12168            }
12169        }
12170        if (r != null) {
12171            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12172        }
12173
12174        mPermissionManager.removeAllPermissions(pkg, chatty);
12175
12176        N = pkg.instrumentation.size();
12177        r = null;
12178        for (i=0; i<N; i++) {
12179            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12180            mInstrumentation.remove(a.getComponentName());
12181            if (DEBUG_REMOVE && chatty) {
12182                if (r == null) {
12183                    r = new StringBuilder(256);
12184                } else {
12185                    r.append(' ');
12186                }
12187                r.append(a.info.name);
12188            }
12189        }
12190        if (r != null) {
12191            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12192        }
12193
12194        r = null;
12195        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12196            // Only system apps can hold shared libraries.
12197            if (pkg.libraryNames != null) {
12198                for (i = 0; i < pkg.libraryNames.size(); i++) {
12199                    String name = pkg.libraryNames.get(i);
12200                    if (removeSharedLibraryLPw(name, 0)) {
12201                        if (DEBUG_REMOVE && chatty) {
12202                            if (r == null) {
12203                                r = new StringBuilder(256);
12204                            } else {
12205                                r.append(' ');
12206                            }
12207                            r.append(name);
12208                        }
12209                    }
12210                }
12211            }
12212        }
12213
12214        r = null;
12215
12216        // Any package can hold static shared libraries.
12217        if (pkg.staticSharedLibName != null) {
12218            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12219                if (DEBUG_REMOVE && chatty) {
12220                    if (r == null) {
12221                        r = new StringBuilder(256);
12222                    } else {
12223                        r.append(' ');
12224                    }
12225                    r.append(pkg.staticSharedLibName);
12226                }
12227            }
12228        }
12229
12230        if (r != null) {
12231            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12232        }
12233    }
12234
12235
12236    final class ActivityIntentResolver
12237            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12238        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12239                boolean defaultOnly, int userId) {
12240            if (!sUserManager.exists(userId)) return null;
12241            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12242            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12243        }
12244
12245        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12246                int userId) {
12247            if (!sUserManager.exists(userId)) return null;
12248            mFlags = flags;
12249            return super.queryIntent(intent, resolvedType,
12250                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12251                    userId);
12252        }
12253
12254        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12255                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12256            if (!sUserManager.exists(userId)) return null;
12257            if (packageActivities == null) {
12258                return null;
12259            }
12260            mFlags = flags;
12261            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12262            final int N = packageActivities.size();
12263            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12264                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12265
12266            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12267            for (int i = 0; i < N; ++i) {
12268                intentFilters = packageActivities.get(i).intents;
12269                if (intentFilters != null && intentFilters.size() > 0) {
12270                    PackageParser.ActivityIntentInfo[] array =
12271                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12272                    intentFilters.toArray(array);
12273                    listCut.add(array);
12274                }
12275            }
12276            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12277        }
12278
12279        /**
12280         * Finds a privileged activity that matches the specified activity names.
12281         */
12282        private PackageParser.Activity findMatchingActivity(
12283                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12284            for (PackageParser.Activity sysActivity : activityList) {
12285                if (sysActivity.info.name.equals(activityInfo.name)) {
12286                    return sysActivity;
12287                }
12288                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12289                    return sysActivity;
12290                }
12291                if (sysActivity.info.targetActivity != null) {
12292                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12293                        return sysActivity;
12294                    }
12295                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12296                        return sysActivity;
12297                    }
12298                }
12299            }
12300            return null;
12301        }
12302
12303        public class IterGenerator<E> {
12304            public Iterator<E> generate(ActivityIntentInfo info) {
12305                return null;
12306            }
12307        }
12308
12309        public class ActionIterGenerator extends IterGenerator<String> {
12310            @Override
12311            public Iterator<String> generate(ActivityIntentInfo info) {
12312                return info.actionsIterator();
12313            }
12314        }
12315
12316        public class CategoriesIterGenerator extends IterGenerator<String> {
12317            @Override
12318            public Iterator<String> generate(ActivityIntentInfo info) {
12319                return info.categoriesIterator();
12320            }
12321        }
12322
12323        public class SchemesIterGenerator extends IterGenerator<String> {
12324            @Override
12325            public Iterator<String> generate(ActivityIntentInfo info) {
12326                return info.schemesIterator();
12327            }
12328        }
12329
12330        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12331            @Override
12332            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12333                return info.authoritiesIterator();
12334            }
12335        }
12336
12337        /**
12338         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12339         * MODIFIED. Do not pass in a list that should not be changed.
12340         */
12341        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12342                IterGenerator<T> generator, Iterator<T> searchIterator) {
12343            // loop through the set of actions; every one must be found in the intent filter
12344            while (searchIterator.hasNext()) {
12345                // we must have at least one filter in the list to consider a match
12346                if (intentList.size() == 0) {
12347                    break;
12348                }
12349
12350                final T searchAction = searchIterator.next();
12351
12352                // loop through the set of intent filters
12353                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12354                while (intentIter.hasNext()) {
12355                    final ActivityIntentInfo intentInfo = intentIter.next();
12356                    boolean selectionFound = false;
12357
12358                    // loop through the intent filter's selection criteria; at least one
12359                    // of them must match the searched criteria
12360                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12361                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12362                        final T intentSelection = intentSelectionIter.next();
12363                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12364                            selectionFound = true;
12365                            break;
12366                        }
12367                    }
12368
12369                    // the selection criteria wasn't found in this filter's set; this filter
12370                    // is not a potential match
12371                    if (!selectionFound) {
12372                        intentIter.remove();
12373                    }
12374                }
12375            }
12376        }
12377
12378        private boolean isProtectedAction(ActivityIntentInfo filter) {
12379            final Iterator<String> actionsIter = filter.actionsIterator();
12380            while (actionsIter != null && actionsIter.hasNext()) {
12381                final String filterAction = actionsIter.next();
12382                if (PROTECTED_ACTIONS.contains(filterAction)) {
12383                    return true;
12384                }
12385            }
12386            return false;
12387        }
12388
12389        /**
12390         * Adjusts the priority of the given intent filter according to policy.
12391         * <p>
12392         * <ul>
12393         * <li>The priority for non privileged applications is capped to '0'</li>
12394         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12395         * <li>The priority for unbundled updates to privileged applications is capped to the
12396         *      priority defined on the system partition</li>
12397         * </ul>
12398         * <p>
12399         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12400         * allowed to obtain any priority on any action.
12401         */
12402        private void adjustPriority(
12403                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12404            // nothing to do; priority is fine as-is
12405            if (intent.getPriority() <= 0) {
12406                return;
12407            }
12408
12409            final ActivityInfo activityInfo = intent.activity.info;
12410            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12411
12412            final boolean privilegedApp =
12413                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12414            if (!privilegedApp) {
12415                // non-privileged applications can never define a priority >0
12416                if (DEBUG_FILTERS) {
12417                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12418                            + " package: " + applicationInfo.packageName
12419                            + " activity: " + intent.activity.className
12420                            + " origPrio: " + intent.getPriority());
12421                }
12422                intent.setPriority(0);
12423                return;
12424            }
12425
12426            if (systemActivities == null) {
12427                // the system package is not disabled; we're parsing the system partition
12428                if (isProtectedAction(intent)) {
12429                    if (mDeferProtectedFilters) {
12430                        // We can't deal with these just yet. No component should ever obtain a
12431                        // >0 priority for a protected actions, with ONE exception -- the setup
12432                        // wizard. The setup wizard, however, cannot be known until we're able to
12433                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12434                        // until all intent filters have been processed. Chicken, meet egg.
12435                        // Let the filter temporarily have a high priority and rectify the
12436                        // priorities after all system packages have been scanned.
12437                        mProtectedFilters.add(intent);
12438                        if (DEBUG_FILTERS) {
12439                            Slog.i(TAG, "Protected action; save for later;"
12440                                    + " package: " + applicationInfo.packageName
12441                                    + " activity: " + intent.activity.className
12442                                    + " origPrio: " + intent.getPriority());
12443                        }
12444                        return;
12445                    } else {
12446                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12447                            Slog.i(TAG, "No setup wizard;"
12448                                + " All protected intents capped to priority 0");
12449                        }
12450                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12451                            if (DEBUG_FILTERS) {
12452                                Slog.i(TAG, "Found setup wizard;"
12453                                    + " allow priority " + intent.getPriority() + ";"
12454                                    + " package: " + intent.activity.info.packageName
12455                                    + " activity: " + intent.activity.className
12456                                    + " priority: " + intent.getPriority());
12457                            }
12458                            // setup wizard gets whatever it wants
12459                            return;
12460                        }
12461                        if (DEBUG_FILTERS) {
12462                            Slog.i(TAG, "Protected action; cap priority to 0;"
12463                                    + " package: " + intent.activity.info.packageName
12464                                    + " activity: " + intent.activity.className
12465                                    + " origPrio: " + intent.getPriority());
12466                        }
12467                        intent.setPriority(0);
12468                        return;
12469                    }
12470                }
12471                // privileged apps on the system image get whatever priority they request
12472                return;
12473            }
12474
12475            // privileged app unbundled update ... try to find the same activity
12476            final PackageParser.Activity foundActivity =
12477                    findMatchingActivity(systemActivities, activityInfo);
12478            if (foundActivity == null) {
12479                // this is a new activity; it cannot obtain >0 priority
12480                if (DEBUG_FILTERS) {
12481                    Slog.i(TAG, "New activity; cap priority to 0;"
12482                            + " package: " + applicationInfo.packageName
12483                            + " activity: " + intent.activity.className
12484                            + " origPrio: " + intent.getPriority());
12485                }
12486                intent.setPriority(0);
12487                return;
12488            }
12489
12490            // found activity, now check for filter equivalence
12491
12492            // a shallow copy is enough; we modify the list, not its contents
12493            final List<ActivityIntentInfo> intentListCopy =
12494                    new ArrayList<>(foundActivity.intents);
12495            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12496
12497            // find matching action subsets
12498            final Iterator<String> actionsIterator = intent.actionsIterator();
12499            if (actionsIterator != null) {
12500                getIntentListSubset(
12501                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12502                if (intentListCopy.size() == 0) {
12503                    // no more intents to match; we're not equivalent
12504                    if (DEBUG_FILTERS) {
12505                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12506                                + " package: " + applicationInfo.packageName
12507                                + " activity: " + intent.activity.className
12508                                + " origPrio: " + intent.getPriority());
12509                    }
12510                    intent.setPriority(0);
12511                    return;
12512                }
12513            }
12514
12515            // find matching category subsets
12516            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12517            if (categoriesIterator != null) {
12518                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12519                        categoriesIterator);
12520                if (intentListCopy.size() == 0) {
12521                    // no more intents to match; we're not equivalent
12522                    if (DEBUG_FILTERS) {
12523                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12524                                + " package: " + applicationInfo.packageName
12525                                + " activity: " + intent.activity.className
12526                                + " origPrio: " + intent.getPriority());
12527                    }
12528                    intent.setPriority(0);
12529                    return;
12530                }
12531            }
12532
12533            // find matching schemes subsets
12534            final Iterator<String> schemesIterator = intent.schemesIterator();
12535            if (schemesIterator != null) {
12536                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12537                        schemesIterator);
12538                if (intentListCopy.size() == 0) {
12539                    // no more intents to match; we're not equivalent
12540                    if (DEBUG_FILTERS) {
12541                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12542                                + " package: " + applicationInfo.packageName
12543                                + " activity: " + intent.activity.className
12544                                + " origPrio: " + intent.getPriority());
12545                    }
12546                    intent.setPriority(0);
12547                    return;
12548                }
12549            }
12550
12551            // find matching authorities subsets
12552            final Iterator<IntentFilter.AuthorityEntry>
12553                    authoritiesIterator = intent.authoritiesIterator();
12554            if (authoritiesIterator != null) {
12555                getIntentListSubset(intentListCopy,
12556                        new AuthoritiesIterGenerator(),
12557                        authoritiesIterator);
12558                if (intentListCopy.size() == 0) {
12559                    // no more intents to match; we're not equivalent
12560                    if (DEBUG_FILTERS) {
12561                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12562                                + " package: " + applicationInfo.packageName
12563                                + " activity: " + intent.activity.className
12564                                + " origPrio: " + intent.getPriority());
12565                    }
12566                    intent.setPriority(0);
12567                    return;
12568                }
12569            }
12570
12571            // we found matching filter(s); app gets the max priority of all intents
12572            int cappedPriority = 0;
12573            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12574                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12575            }
12576            if (intent.getPriority() > cappedPriority) {
12577                if (DEBUG_FILTERS) {
12578                    Slog.i(TAG, "Found matching filter(s);"
12579                            + " cap priority to " + cappedPriority + ";"
12580                            + " package: " + applicationInfo.packageName
12581                            + " activity: " + intent.activity.className
12582                            + " origPrio: " + intent.getPriority());
12583                }
12584                intent.setPriority(cappedPriority);
12585                return;
12586            }
12587            // all this for nothing; the requested priority was <= what was on the system
12588        }
12589
12590        public final void addActivity(PackageParser.Activity a, String type) {
12591            mActivities.put(a.getComponentName(), a);
12592            if (DEBUG_SHOW_INFO)
12593                Log.v(
12594                TAG, "  " + type + " " +
12595                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12596            if (DEBUG_SHOW_INFO)
12597                Log.v(TAG, "    Class=" + a.info.name);
12598            final int NI = a.intents.size();
12599            for (int j=0; j<NI; j++) {
12600                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12601                if ("activity".equals(type)) {
12602                    final PackageSetting ps =
12603                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12604                    final List<PackageParser.Activity> systemActivities =
12605                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12606                    adjustPriority(systemActivities, intent);
12607                }
12608                if (DEBUG_SHOW_INFO) {
12609                    Log.v(TAG, "    IntentFilter:");
12610                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12611                }
12612                if (!intent.debugCheck()) {
12613                    Log.w(TAG, "==> For Activity " + a.info.name);
12614                }
12615                addFilter(intent);
12616            }
12617        }
12618
12619        public final void removeActivity(PackageParser.Activity a, String type) {
12620            mActivities.remove(a.getComponentName());
12621            if (DEBUG_SHOW_INFO) {
12622                Log.v(TAG, "  " + type + " "
12623                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12624                                : a.info.name) + ":");
12625                Log.v(TAG, "    Class=" + a.info.name);
12626            }
12627            final int NI = a.intents.size();
12628            for (int j=0; j<NI; j++) {
12629                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12630                if (DEBUG_SHOW_INFO) {
12631                    Log.v(TAG, "    IntentFilter:");
12632                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12633                }
12634                removeFilter(intent);
12635            }
12636        }
12637
12638        @Override
12639        protected boolean allowFilterResult(
12640                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12641            ActivityInfo filterAi = filter.activity.info;
12642            for (int i=dest.size()-1; i>=0; i--) {
12643                ActivityInfo destAi = dest.get(i).activityInfo;
12644                if (destAi.name == filterAi.name
12645                        && destAi.packageName == filterAi.packageName) {
12646                    return false;
12647                }
12648            }
12649            return true;
12650        }
12651
12652        @Override
12653        protected ActivityIntentInfo[] newArray(int size) {
12654            return new ActivityIntentInfo[size];
12655        }
12656
12657        @Override
12658        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12659            if (!sUserManager.exists(userId)) return true;
12660            PackageParser.Package p = filter.activity.owner;
12661            if (p != null) {
12662                PackageSetting ps = (PackageSetting)p.mExtras;
12663                if (ps != null) {
12664                    // System apps are never considered stopped for purposes of
12665                    // filtering, because there may be no way for the user to
12666                    // actually re-launch them.
12667                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12668                            && ps.getStopped(userId);
12669                }
12670            }
12671            return false;
12672        }
12673
12674        @Override
12675        protected boolean isPackageForFilter(String packageName,
12676                PackageParser.ActivityIntentInfo info) {
12677            return packageName.equals(info.activity.owner.packageName);
12678        }
12679
12680        @Override
12681        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12682                int match, int userId) {
12683            if (!sUserManager.exists(userId)) return null;
12684            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12685                return null;
12686            }
12687            final PackageParser.Activity activity = info.activity;
12688            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12689            if (ps == null) {
12690                return null;
12691            }
12692            final PackageUserState userState = ps.readUserState(userId);
12693            ActivityInfo ai =
12694                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12695            if (ai == null) {
12696                return null;
12697            }
12698            final boolean matchExplicitlyVisibleOnly =
12699                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12700            final boolean matchVisibleToInstantApp =
12701                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12702            final boolean componentVisible =
12703                    matchVisibleToInstantApp
12704                    && info.isVisibleToInstantApp()
12705                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12706            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12707            // throw out filters that aren't visible to ephemeral apps
12708            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12709                return null;
12710            }
12711            // throw out instant app filters if we're not explicitly requesting them
12712            if (!matchInstantApp && userState.instantApp) {
12713                return null;
12714            }
12715            // throw out instant app filters if updates are available; will trigger
12716            // instant app resolution
12717            if (userState.instantApp && ps.isUpdateAvailable()) {
12718                return null;
12719            }
12720            final ResolveInfo res = new ResolveInfo();
12721            res.activityInfo = ai;
12722            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12723                res.filter = info;
12724            }
12725            if (info != null) {
12726                res.handleAllWebDataURI = info.handleAllWebDataURI();
12727            }
12728            res.priority = info.getPriority();
12729            res.preferredOrder = activity.owner.mPreferredOrder;
12730            //System.out.println("Result: " + res.activityInfo.className +
12731            //                   " = " + res.priority);
12732            res.match = match;
12733            res.isDefault = info.hasDefault;
12734            res.labelRes = info.labelRes;
12735            res.nonLocalizedLabel = info.nonLocalizedLabel;
12736            if (userNeedsBadging(userId)) {
12737                res.noResourceId = true;
12738            } else {
12739                res.icon = info.icon;
12740            }
12741            res.iconResourceId = info.icon;
12742            res.system = res.activityInfo.applicationInfo.isSystemApp();
12743            res.isInstantAppAvailable = userState.instantApp;
12744            return res;
12745        }
12746
12747        @Override
12748        protected void sortResults(List<ResolveInfo> results) {
12749            Collections.sort(results, mResolvePrioritySorter);
12750        }
12751
12752        @Override
12753        protected void dumpFilter(PrintWriter out, String prefix,
12754                PackageParser.ActivityIntentInfo filter) {
12755            out.print(prefix); out.print(
12756                    Integer.toHexString(System.identityHashCode(filter.activity)));
12757                    out.print(' ');
12758                    filter.activity.printComponentShortName(out);
12759                    out.print(" filter ");
12760                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12761        }
12762
12763        @Override
12764        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12765            return filter.activity;
12766        }
12767
12768        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12769            PackageParser.Activity activity = (PackageParser.Activity)label;
12770            out.print(prefix); out.print(
12771                    Integer.toHexString(System.identityHashCode(activity)));
12772                    out.print(' ');
12773                    activity.printComponentShortName(out);
12774            if (count > 1) {
12775                out.print(" ("); out.print(count); out.print(" filters)");
12776            }
12777            out.println();
12778        }
12779
12780        // Keys are String (activity class name), values are Activity.
12781        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12782                = new ArrayMap<ComponentName, PackageParser.Activity>();
12783        private int mFlags;
12784    }
12785
12786    private final class ServiceIntentResolver
12787            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12788        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12789                boolean defaultOnly, int userId) {
12790            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12791            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12792        }
12793
12794        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12795                int userId) {
12796            if (!sUserManager.exists(userId)) return null;
12797            mFlags = flags;
12798            return super.queryIntent(intent, resolvedType,
12799                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12800                    userId);
12801        }
12802
12803        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12804                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12805            if (!sUserManager.exists(userId)) return null;
12806            if (packageServices == null) {
12807                return null;
12808            }
12809            mFlags = flags;
12810            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12811            final int N = packageServices.size();
12812            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12813                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12814
12815            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12816            for (int i = 0; i < N; ++i) {
12817                intentFilters = packageServices.get(i).intents;
12818                if (intentFilters != null && intentFilters.size() > 0) {
12819                    PackageParser.ServiceIntentInfo[] array =
12820                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12821                    intentFilters.toArray(array);
12822                    listCut.add(array);
12823                }
12824            }
12825            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12826        }
12827
12828        public final void addService(PackageParser.Service s) {
12829            mServices.put(s.getComponentName(), s);
12830            if (DEBUG_SHOW_INFO) {
12831                Log.v(TAG, "  "
12832                        + (s.info.nonLocalizedLabel != null
12833                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12834                Log.v(TAG, "    Class=" + s.info.name);
12835            }
12836            final int NI = s.intents.size();
12837            int j;
12838            for (j=0; j<NI; j++) {
12839                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12840                if (DEBUG_SHOW_INFO) {
12841                    Log.v(TAG, "    IntentFilter:");
12842                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12843                }
12844                if (!intent.debugCheck()) {
12845                    Log.w(TAG, "==> For Service " + s.info.name);
12846                }
12847                addFilter(intent);
12848            }
12849        }
12850
12851        public final void removeService(PackageParser.Service s) {
12852            mServices.remove(s.getComponentName());
12853            if (DEBUG_SHOW_INFO) {
12854                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12855                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12856                Log.v(TAG, "    Class=" + s.info.name);
12857            }
12858            final int NI = s.intents.size();
12859            int j;
12860            for (j=0; j<NI; j++) {
12861                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12862                if (DEBUG_SHOW_INFO) {
12863                    Log.v(TAG, "    IntentFilter:");
12864                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12865                }
12866                removeFilter(intent);
12867            }
12868        }
12869
12870        @Override
12871        protected boolean allowFilterResult(
12872                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12873            ServiceInfo filterSi = filter.service.info;
12874            for (int i=dest.size()-1; i>=0; i--) {
12875                ServiceInfo destAi = dest.get(i).serviceInfo;
12876                if (destAi.name == filterSi.name
12877                        && destAi.packageName == filterSi.packageName) {
12878                    return false;
12879                }
12880            }
12881            return true;
12882        }
12883
12884        @Override
12885        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12886            return new PackageParser.ServiceIntentInfo[size];
12887        }
12888
12889        @Override
12890        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12891            if (!sUserManager.exists(userId)) return true;
12892            PackageParser.Package p = filter.service.owner;
12893            if (p != null) {
12894                PackageSetting ps = (PackageSetting)p.mExtras;
12895                if (ps != null) {
12896                    // System apps are never considered stopped for purposes of
12897                    // filtering, because there may be no way for the user to
12898                    // actually re-launch them.
12899                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12900                            && ps.getStopped(userId);
12901                }
12902            }
12903            return false;
12904        }
12905
12906        @Override
12907        protected boolean isPackageForFilter(String packageName,
12908                PackageParser.ServiceIntentInfo info) {
12909            return packageName.equals(info.service.owner.packageName);
12910        }
12911
12912        @Override
12913        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12914                int match, int userId) {
12915            if (!sUserManager.exists(userId)) return null;
12916            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12917            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12918                return null;
12919            }
12920            final PackageParser.Service service = info.service;
12921            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12922            if (ps == null) {
12923                return null;
12924            }
12925            final PackageUserState userState = ps.readUserState(userId);
12926            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12927                    userState, userId);
12928            if (si == null) {
12929                return null;
12930            }
12931            final boolean matchVisibleToInstantApp =
12932                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12933            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12934            // throw out filters that aren't visible to ephemeral apps
12935            if (matchVisibleToInstantApp
12936                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12937                return null;
12938            }
12939            // throw out ephemeral filters if we're not explicitly requesting them
12940            if (!isInstantApp && userState.instantApp) {
12941                return null;
12942            }
12943            // throw out instant app filters if updates are available; will trigger
12944            // instant app resolution
12945            if (userState.instantApp && ps.isUpdateAvailable()) {
12946                return null;
12947            }
12948            final ResolveInfo res = new ResolveInfo();
12949            res.serviceInfo = si;
12950            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12951                res.filter = filter;
12952            }
12953            res.priority = info.getPriority();
12954            res.preferredOrder = service.owner.mPreferredOrder;
12955            res.match = match;
12956            res.isDefault = info.hasDefault;
12957            res.labelRes = info.labelRes;
12958            res.nonLocalizedLabel = info.nonLocalizedLabel;
12959            res.icon = info.icon;
12960            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12961            return res;
12962        }
12963
12964        @Override
12965        protected void sortResults(List<ResolveInfo> results) {
12966            Collections.sort(results, mResolvePrioritySorter);
12967        }
12968
12969        @Override
12970        protected void dumpFilter(PrintWriter out, String prefix,
12971                PackageParser.ServiceIntentInfo filter) {
12972            out.print(prefix); out.print(
12973                    Integer.toHexString(System.identityHashCode(filter.service)));
12974                    out.print(' ');
12975                    filter.service.printComponentShortName(out);
12976                    out.print(" filter ");
12977                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12978                    if (filter.service.info.permission != null) {
12979                        out.print(" permission "); out.println(filter.service.info.permission);
12980                    } else {
12981                        out.println();
12982                    }
12983        }
12984
12985        @Override
12986        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12987            return filter.service;
12988        }
12989
12990        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12991            PackageParser.Service service = (PackageParser.Service)label;
12992            out.print(prefix); out.print(
12993                    Integer.toHexString(System.identityHashCode(service)));
12994                    out.print(' ');
12995                    service.printComponentShortName(out);
12996            if (count > 1) {
12997                out.print(" ("); out.print(count); out.print(" filters)");
12998            }
12999            out.println();
13000        }
13001
13002//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13003//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13004//            final List<ResolveInfo> retList = Lists.newArrayList();
13005//            while (i.hasNext()) {
13006//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13007//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13008//                    retList.add(resolveInfo);
13009//                }
13010//            }
13011//            return retList;
13012//        }
13013
13014        // Keys are String (activity class name), values are Activity.
13015        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13016                = new ArrayMap<ComponentName, PackageParser.Service>();
13017        private int mFlags;
13018    }
13019
13020    private final class ProviderIntentResolver
13021            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13022        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13023                boolean defaultOnly, int userId) {
13024            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13025            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13026        }
13027
13028        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13029                int userId) {
13030            if (!sUserManager.exists(userId))
13031                return null;
13032            mFlags = flags;
13033            return super.queryIntent(intent, resolvedType,
13034                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13035                    userId);
13036        }
13037
13038        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13039                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13040            if (!sUserManager.exists(userId))
13041                return null;
13042            if (packageProviders == null) {
13043                return null;
13044            }
13045            mFlags = flags;
13046            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13047            final int N = packageProviders.size();
13048            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13049                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13050
13051            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13052            for (int i = 0; i < N; ++i) {
13053                intentFilters = packageProviders.get(i).intents;
13054                if (intentFilters != null && intentFilters.size() > 0) {
13055                    PackageParser.ProviderIntentInfo[] array =
13056                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13057                    intentFilters.toArray(array);
13058                    listCut.add(array);
13059                }
13060            }
13061            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13062        }
13063
13064        public final void addProvider(PackageParser.Provider p) {
13065            if (mProviders.containsKey(p.getComponentName())) {
13066                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13067                return;
13068            }
13069
13070            mProviders.put(p.getComponentName(), p);
13071            if (DEBUG_SHOW_INFO) {
13072                Log.v(TAG, "  "
13073                        + (p.info.nonLocalizedLabel != null
13074                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13075                Log.v(TAG, "    Class=" + p.info.name);
13076            }
13077            final int NI = p.intents.size();
13078            int j;
13079            for (j = 0; j < NI; j++) {
13080                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13081                if (DEBUG_SHOW_INFO) {
13082                    Log.v(TAG, "    IntentFilter:");
13083                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13084                }
13085                if (!intent.debugCheck()) {
13086                    Log.w(TAG, "==> For Provider " + p.info.name);
13087                }
13088                addFilter(intent);
13089            }
13090        }
13091
13092        public final void removeProvider(PackageParser.Provider p) {
13093            mProviders.remove(p.getComponentName());
13094            if (DEBUG_SHOW_INFO) {
13095                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13096                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13097                Log.v(TAG, "    Class=" + p.info.name);
13098            }
13099            final int NI = p.intents.size();
13100            int j;
13101            for (j = 0; j < NI; j++) {
13102                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13103                if (DEBUG_SHOW_INFO) {
13104                    Log.v(TAG, "    IntentFilter:");
13105                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13106                }
13107                removeFilter(intent);
13108            }
13109        }
13110
13111        @Override
13112        protected boolean allowFilterResult(
13113                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13114            ProviderInfo filterPi = filter.provider.info;
13115            for (int i = dest.size() - 1; i >= 0; i--) {
13116                ProviderInfo destPi = dest.get(i).providerInfo;
13117                if (destPi.name == filterPi.name
13118                        && destPi.packageName == filterPi.packageName) {
13119                    return false;
13120                }
13121            }
13122            return true;
13123        }
13124
13125        @Override
13126        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13127            return new PackageParser.ProviderIntentInfo[size];
13128        }
13129
13130        @Override
13131        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13132            if (!sUserManager.exists(userId))
13133                return true;
13134            PackageParser.Package p = filter.provider.owner;
13135            if (p != null) {
13136                PackageSetting ps = (PackageSetting) p.mExtras;
13137                if (ps != null) {
13138                    // System apps are never considered stopped for purposes of
13139                    // filtering, because there may be no way for the user to
13140                    // actually re-launch them.
13141                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13142                            && ps.getStopped(userId);
13143                }
13144            }
13145            return false;
13146        }
13147
13148        @Override
13149        protected boolean isPackageForFilter(String packageName,
13150                PackageParser.ProviderIntentInfo info) {
13151            return packageName.equals(info.provider.owner.packageName);
13152        }
13153
13154        @Override
13155        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13156                int match, int userId) {
13157            if (!sUserManager.exists(userId))
13158                return null;
13159            final PackageParser.ProviderIntentInfo info = filter;
13160            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13161                return null;
13162            }
13163            final PackageParser.Provider provider = info.provider;
13164            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13165            if (ps == null) {
13166                return null;
13167            }
13168            final PackageUserState userState = ps.readUserState(userId);
13169            final boolean matchVisibleToInstantApp =
13170                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13171            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13172            // throw out filters that aren't visible to instant applications
13173            if (matchVisibleToInstantApp
13174                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13175                return null;
13176            }
13177            // throw out instant application filters if we're not explicitly requesting them
13178            if (!isInstantApp && userState.instantApp) {
13179                return null;
13180            }
13181            // throw out instant application filters if updates are available; will trigger
13182            // instant application resolution
13183            if (userState.instantApp && ps.isUpdateAvailable()) {
13184                return null;
13185            }
13186            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13187                    userState, userId);
13188            if (pi == null) {
13189                return null;
13190            }
13191            final ResolveInfo res = new ResolveInfo();
13192            res.providerInfo = pi;
13193            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13194                res.filter = filter;
13195            }
13196            res.priority = info.getPriority();
13197            res.preferredOrder = provider.owner.mPreferredOrder;
13198            res.match = match;
13199            res.isDefault = info.hasDefault;
13200            res.labelRes = info.labelRes;
13201            res.nonLocalizedLabel = info.nonLocalizedLabel;
13202            res.icon = info.icon;
13203            res.system = res.providerInfo.applicationInfo.isSystemApp();
13204            return res;
13205        }
13206
13207        @Override
13208        protected void sortResults(List<ResolveInfo> results) {
13209            Collections.sort(results, mResolvePrioritySorter);
13210        }
13211
13212        @Override
13213        protected void dumpFilter(PrintWriter out, String prefix,
13214                PackageParser.ProviderIntentInfo filter) {
13215            out.print(prefix);
13216            out.print(
13217                    Integer.toHexString(System.identityHashCode(filter.provider)));
13218            out.print(' ');
13219            filter.provider.printComponentShortName(out);
13220            out.print(" filter ");
13221            out.println(Integer.toHexString(System.identityHashCode(filter)));
13222        }
13223
13224        @Override
13225        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13226            return filter.provider;
13227        }
13228
13229        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13230            PackageParser.Provider provider = (PackageParser.Provider)label;
13231            out.print(prefix); out.print(
13232                    Integer.toHexString(System.identityHashCode(provider)));
13233                    out.print(' ');
13234                    provider.printComponentShortName(out);
13235            if (count > 1) {
13236                out.print(" ("); out.print(count); out.print(" filters)");
13237            }
13238            out.println();
13239        }
13240
13241        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13242                = new ArrayMap<ComponentName, PackageParser.Provider>();
13243        private int mFlags;
13244    }
13245
13246    static final class InstantAppIntentResolver
13247            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13248            AuxiliaryResolveInfo.AuxiliaryFilter> {
13249        /**
13250         * The result that has the highest defined order. Ordering applies on a
13251         * per-package basis. Mapping is from package name to Pair of order and
13252         * EphemeralResolveInfo.
13253         * <p>
13254         * NOTE: This is implemented as a field variable for convenience and efficiency.
13255         * By having a field variable, we're able to track filter ordering as soon as
13256         * a non-zero order is defined. Otherwise, multiple loops across the result set
13257         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13258         * this needs to be contained entirely within {@link #filterResults}.
13259         */
13260        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13261
13262        @Override
13263        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13264            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13265        }
13266
13267        @Override
13268        protected boolean isPackageForFilter(String packageName,
13269                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13270            return true;
13271        }
13272
13273        @Override
13274        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13275                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13276            if (!sUserManager.exists(userId)) {
13277                return null;
13278            }
13279            final String packageName = responseObj.resolveInfo.getPackageName();
13280            final Integer order = responseObj.getOrder();
13281            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13282                    mOrderResult.get(packageName);
13283            // ordering is enabled and this item's order isn't high enough
13284            if (lastOrderResult != null && lastOrderResult.first >= order) {
13285                return null;
13286            }
13287            final InstantAppResolveInfo res = responseObj.resolveInfo;
13288            if (order > 0) {
13289                // non-zero order, enable ordering
13290                mOrderResult.put(packageName, new Pair<>(order, res));
13291            }
13292            return responseObj;
13293        }
13294
13295        @Override
13296        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13297            // only do work if ordering is enabled [most of the time it won't be]
13298            if (mOrderResult.size() == 0) {
13299                return;
13300            }
13301            int resultSize = results.size();
13302            for (int i = 0; i < resultSize; i++) {
13303                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13304                final String packageName = info.getPackageName();
13305                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13306                if (savedInfo == null) {
13307                    // package doesn't having ordering
13308                    continue;
13309                }
13310                if (savedInfo.second == info) {
13311                    // circled back to the highest ordered item; remove from order list
13312                    mOrderResult.remove(packageName);
13313                    if (mOrderResult.size() == 0) {
13314                        // no more ordered items
13315                        break;
13316                    }
13317                    continue;
13318                }
13319                // item has a worse order, remove it from the result list
13320                results.remove(i);
13321                resultSize--;
13322                i--;
13323            }
13324        }
13325    }
13326
13327    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13328            new Comparator<ResolveInfo>() {
13329        public int compare(ResolveInfo r1, ResolveInfo r2) {
13330            int v1 = r1.priority;
13331            int v2 = r2.priority;
13332            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13333            if (v1 != v2) {
13334                return (v1 > v2) ? -1 : 1;
13335            }
13336            v1 = r1.preferredOrder;
13337            v2 = r2.preferredOrder;
13338            if (v1 != v2) {
13339                return (v1 > v2) ? -1 : 1;
13340            }
13341            if (r1.isDefault != r2.isDefault) {
13342                return r1.isDefault ? -1 : 1;
13343            }
13344            v1 = r1.match;
13345            v2 = r2.match;
13346            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13347            if (v1 != v2) {
13348                return (v1 > v2) ? -1 : 1;
13349            }
13350            if (r1.system != r2.system) {
13351                return r1.system ? -1 : 1;
13352            }
13353            if (r1.activityInfo != null) {
13354                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13355            }
13356            if (r1.serviceInfo != null) {
13357                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13358            }
13359            if (r1.providerInfo != null) {
13360                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13361            }
13362            return 0;
13363        }
13364    };
13365
13366    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13367            new Comparator<ProviderInfo>() {
13368        public int compare(ProviderInfo p1, ProviderInfo p2) {
13369            final int v1 = p1.initOrder;
13370            final int v2 = p2.initOrder;
13371            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13372        }
13373    };
13374
13375    @Override
13376    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13377            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13378            final int[] userIds, int[] instantUserIds) {
13379        mHandler.post(new Runnable() {
13380            @Override
13381            public void run() {
13382                try {
13383                    final IActivityManager am = ActivityManager.getService();
13384                    if (am == null) return;
13385                    final int[] resolvedUserIds;
13386                    if (userIds == null) {
13387                        resolvedUserIds = am.getRunningUserIds();
13388                    } else {
13389                        resolvedUserIds = userIds;
13390                    }
13391                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13392                            resolvedUserIds, false);
13393                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13394                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13395                                instantUserIds, true);
13396                    }
13397                } catch (RemoteException ex) {
13398                }
13399            }
13400        });
13401    }
13402
13403    @Override
13404    public void notifyPackageAdded(String packageName) {
13405        final PackageListObserver[] observers;
13406        synchronized (mPackages) {
13407            if (mPackageListObservers.size() == 0) {
13408                return;
13409            }
13410            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13411        }
13412        for (int i = observers.length - 1; i >= 0; --i) {
13413            observers[i].onPackageAdded(packageName);
13414        }
13415    }
13416
13417    @Override
13418    public void notifyPackageRemoved(String packageName) {
13419        final PackageListObserver[] observers;
13420        synchronized (mPackages) {
13421            if (mPackageListObservers.size() == 0) {
13422                return;
13423            }
13424            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13425        }
13426        for (int i = observers.length - 1; i >= 0; --i) {
13427            observers[i].onPackageRemoved(packageName);
13428        }
13429    }
13430
13431    /**
13432     * Sends a broadcast for the given action.
13433     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13434     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13435     * the system and applications allowed to see instant applications to receive package
13436     * lifecycle events for instant applications.
13437     */
13438    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13439            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13440            int[] userIds, boolean isInstantApp)
13441                    throws RemoteException {
13442        for (int id : userIds) {
13443            final Intent intent = new Intent(action,
13444                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13445            final String[] requiredPermissions =
13446                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13447            if (extras != null) {
13448                intent.putExtras(extras);
13449            }
13450            if (targetPkg != null) {
13451                intent.setPackage(targetPkg);
13452            }
13453            // Modify the UID when posting to other users
13454            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13455            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13456                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13457                intent.putExtra(Intent.EXTRA_UID, uid);
13458            }
13459            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13460            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13461            if (DEBUG_BROADCASTS) {
13462                RuntimeException here = new RuntimeException("here");
13463                here.fillInStackTrace();
13464                Slog.d(TAG, "Sending to user " + id + ": "
13465                        + intent.toShortString(false, true, false, false)
13466                        + " " + intent.getExtras(), here);
13467            }
13468            am.broadcastIntent(null, intent, null, finishedReceiver,
13469                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13470                    null, finishedReceiver != null, false, id);
13471        }
13472    }
13473
13474    /**
13475     * Check if the external storage media is available. This is true if there
13476     * is a mounted external storage medium or if the external storage is
13477     * emulated.
13478     */
13479    private boolean isExternalMediaAvailable() {
13480        return mMediaMounted || Environment.isExternalStorageEmulated();
13481    }
13482
13483    @Override
13484    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13485        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13486            return null;
13487        }
13488        if (!isExternalMediaAvailable()) {
13489                // If the external storage is no longer mounted at this point,
13490                // the caller may not have been able to delete all of this
13491                // packages files and can not delete any more.  Bail.
13492            return null;
13493        }
13494        synchronized (mPackages) {
13495            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13496            if (lastPackage != null) {
13497                pkgs.remove(lastPackage);
13498            }
13499            if (pkgs.size() > 0) {
13500                return pkgs.get(0);
13501            }
13502        }
13503        return null;
13504    }
13505
13506    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13507        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13508                userId, andCode ? 1 : 0, packageName);
13509        if (mSystemReady) {
13510            msg.sendToTarget();
13511        } else {
13512            if (mPostSystemReadyMessages == null) {
13513                mPostSystemReadyMessages = new ArrayList<>();
13514            }
13515            mPostSystemReadyMessages.add(msg);
13516        }
13517    }
13518
13519    void startCleaningPackages() {
13520        // reader
13521        if (!isExternalMediaAvailable()) {
13522            return;
13523        }
13524        synchronized (mPackages) {
13525            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13526                return;
13527            }
13528        }
13529        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13530        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13531        IActivityManager am = ActivityManager.getService();
13532        if (am != null) {
13533            int dcsUid = -1;
13534            synchronized (mPackages) {
13535                if (!mDefaultContainerWhitelisted) {
13536                    mDefaultContainerWhitelisted = true;
13537                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13538                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13539                }
13540            }
13541            try {
13542                if (dcsUid > 0) {
13543                    am.backgroundWhitelistUid(dcsUid);
13544                }
13545                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13546                        UserHandle.USER_SYSTEM);
13547            } catch (RemoteException e) {
13548            }
13549        }
13550    }
13551
13552    /**
13553     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13554     * it is acting on behalf on an enterprise or the user).
13555     *
13556     * Note that the ordering of the conditionals in this method is important. The checks we perform
13557     * are as follows, in this order:
13558     *
13559     * 1) If the install is being performed by a system app, we can trust the app to have set the
13560     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13561     *    what it is.
13562     * 2) If the install is being performed by a device or profile owner app, the install reason
13563     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13564     *    set the install reason correctly. If the app targets an older SDK version where install
13565     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13566     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13567     * 3) In all other cases, the install is being performed by a regular app that is neither part
13568     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13569     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13570     *    set to enterprise policy and if so, change it to unknown instead.
13571     */
13572    private int fixUpInstallReason(String installerPackageName, int installerUid,
13573            int installReason) {
13574        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13575                == PERMISSION_GRANTED) {
13576            // If the install is being performed by a system app, we trust that app to have set the
13577            // install reason correctly.
13578            return installReason;
13579        }
13580
13581        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13582            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13583        if (dpm != null) {
13584            ComponentName owner = null;
13585            try {
13586                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13587                if (owner == null) {
13588                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13589                }
13590            } catch (RemoteException e) {
13591            }
13592            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13593                // If the install is being performed by a device or profile owner, the install
13594                // reason should be enterprise policy.
13595                return PackageManager.INSTALL_REASON_POLICY;
13596            }
13597        }
13598
13599        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13600            // If the install is being performed by a regular app (i.e. neither system app nor
13601            // device or profile owner), we have no reason to believe that the app is acting on
13602            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13603            // change it to unknown instead.
13604            return PackageManager.INSTALL_REASON_UNKNOWN;
13605        }
13606
13607        // If the install is being performed by a regular app and the install reason was set to any
13608        // value but enterprise policy, leave the install reason unchanged.
13609        return installReason;
13610    }
13611
13612    void installStage(String packageName, File stagedDir,
13613            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13614            String installerPackageName, int installerUid, UserHandle user,
13615            PackageParser.SigningDetails signingDetails) {
13616        if (DEBUG_INSTANT) {
13617            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13618                Slog.d(TAG, "Ephemeral install of " + packageName);
13619            }
13620        }
13621        final VerificationInfo verificationInfo = new VerificationInfo(
13622                sessionParams.originatingUri, sessionParams.referrerUri,
13623                sessionParams.originatingUid, installerUid);
13624
13625        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13626
13627        final Message msg = mHandler.obtainMessage(INIT_COPY);
13628        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13629                sessionParams.installReason);
13630        final InstallParams params = new InstallParams(origin, null, observer,
13631                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13632                verificationInfo, user, sessionParams.abiOverride,
13633                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13634        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13635        msg.obj = params;
13636
13637        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13638                System.identityHashCode(msg.obj));
13639        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13640                System.identityHashCode(msg.obj));
13641
13642        mHandler.sendMessage(msg);
13643    }
13644
13645    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13646            int userId) {
13647        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13648        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13649        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13650        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13651        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13652                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13653
13654        // Send a session commit broadcast
13655        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13656        info.installReason = pkgSetting.getInstallReason(userId);
13657        info.appPackageName = packageName;
13658        sendSessionCommitBroadcast(info, userId);
13659    }
13660
13661    @Override
13662    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13663            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13664        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13665            return;
13666        }
13667        Bundle extras = new Bundle(1);
13668        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13669        final int uid = UserHandle.getUid(
13670                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13671        extras.putInt(Intent.EXTRA_UID, uid);
13672
13673        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13674                packageName, extras, 0, null, null, userIds, instantUserIds);
13675        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13676            mHandler.post(() -> {
13677                        for (int userId : userIds) {
13678                            sendBootCompletedBroadcastToSystemApp(
13679                                    packageName, includeStopped, userId);
13680                        }
13681                    }
13682            );
13683        }
13684    }
13685
13686    /**
13687     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13688     * automatically without needing an explicit launch.
13689     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13690     */
13691    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13692            int userId) {
13693        // If user is not running, the app didn't miss any broadcast
13694        if (!mUserManagerInternal.isUserRunning(userId)) {
13695            return;
13696        }
13697        final IActivityManager am = ActivityManager.getService();
13698        try {
13699            // Deliver LOCKED_BOOT_COMPLETED first
13700            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13701                    .setPackage(packageName);
13702            if (includeStopped) {
13703                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13704            }
13705            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13706            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13707                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13708
13709            // Deliver BOOT_COMPLETED only if user is unlocked
13710            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13711                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13712                if (includeStopped) {
13713                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13714                }
13715                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13716                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13717            }
13718        } catch (RemoteException e) {
13719            throw e.rethrowFromSystemServer();
13720        }
13721    }
13722
13723    @Override
13724    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13725            int userId) {
13726        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13727        PackageSetting pkgSetting;
13728        final int callingUid = Binder.getCallingUid();
13729        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13730                true /* requireFullPermission */, true /* checkShell */,
13731                "setApplicationHiddenSetting for user " + userId);
13732
13733        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13734            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13735            return false;
13736        }
13737
13738        long callingId = Binder.clearCallingIdentity();
13739        try {
13740            boolean sendAdded = false;
13741            boolean sendRemoved = false;
13742            // writer
13743            synchronized (mPackages) {
13744                pkgSetting = mSettings.mPackages.get(packageName);
13745                if (pkgSetting == null) {
13746                    return false;
13747                }
13748                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13749                    return false;
13750                }
13751                // Do not allow "android" is being disabled
13752                if ("android".equals(packageName)) {
13753                    Slog.w(TAG, "Cannot hide package: android");
13754                    return false;
13755                }
13756                // Cannot hide static shared libs as they are considered
13757                // a part of the using app (emulating static linking). Also
13758                // static libs are installed always on internal storage.
13759                PackageParser.Package pkg = mPackages.get(packageName);
13760                if (pkg != null && pkg.staticSharedLibName != null) {
13761                    Slog.w(TAG, "Cannot hide package: " + packageName
13762                            + " providing static shared library: "
13763                            + pkg.staticSharedLibName);
13764                    return false;
13765                }
13766                // Only allow protected packages to hide themselves.
13767                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13768                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13769                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13770                    return false;
13771                }
13772
13773                if (pkgSetting.getHidden(userId) != hidden) {
13774                    pkgSetting.setHidden(hidden, userId);
13775                    mSettings.writePackageRestrictionsLPr(userId);
13776                    if (hidden) {
13777                        sendRemoved = true;
13778                    } else {
13779                        sendAdded = true;
13780                    }
13781                }
13782            }
13783            if (sendAdded) {
13784                sendPackageAddedForUser(packageName, pkgSetting, userId);
13785                return true;
13786            }
13787            if (sendRemoved) {
13788                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13789                        "hiding pkg");
13790                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13791                return true;
13792            }
13793        } finally {
13794            Binder.restoreCallingIdentity(callingId);
13795        }
13796        return false;
13797    }
13798
13799    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13800            int userId) {
13801        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13802        info.removedPackage = packageName;
13803        info.installerPackageName = pkgSetting.installerPackageName;
13804        info.removedUsers = new int[] {userId};
13805        info.broadcastUsers = new int[] {userId};
13806        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13807        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13808    }
13809
13810    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13811        if (pkgList.length > 0) {
13812            Bundle extras = new Bundle(1);
13813            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13814
13815            sendPackageBroadcast(
13816                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13817                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13818                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13819                    new int[] {userId}, null);
13820        }
13821    }
13822
13823    /**
13824     * Returns true if application is not found or there was an error. Otherwise it returns
13825     * the hidden state of the package for the given user.
13826     */
13827    @Override
13828    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13829        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13830        final int callingUid = Binder.getCallingUid();
13831        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13832                true /* requireFullPermission */, false /* checkShell */,
13833                "getApplicationHidden for user " + userId);
13834        PackageSetting ps;
13835        long callingId = Binder.clearCallingIdentity();
13836        try {
13837            // writer
13838            synchronized (mPackages) {
13839                ps = mSettings.mPackages.get(packageName);
13840                if (ps == null) {
13841                    return true;
13842                }
13843                if (filterAppAccessLPr(ps, callingUid, userId)) {
13844                    return true;
13845                }
13846                return ps.getHidden(userId);
13847            }
13848        } finally {
13849            Binder.restoreCallingIdentity(callingId);
13850        }
13851    }
13852
13853    /**
13854     * @hide
13855     */
13856    @Override
13857    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13858            int installReason) {
13859        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13860                null);
13861        PackageSetting pkgSetting;
13862        final int callingUid = Binder.getCallingUid();
13863        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13864                true /* requireFullPermission */, true /* checkShell */,
13865                "installExistingPackage for user " + userId);
13866        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13867            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13868        }
13869
13870        long callingId = Binder.clearCallingIdentity();
13871        try {
13872            boolean installed = false;
13873            final boolean instantApp =
13874                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13875            final boolean fullApp =
13876                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13877
13878            // writer
13879            synchronized (mPackages) {
13880                pkgSetting = mSettings.mPackages.get(packageName);
13881                if (pkgSetting == null) {
13882                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13883                }
13884                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13885                    // only allow the existing package to be used if it's installed as a full
13886                    // application for at least one user
13887                    boolean installAllowed = false;
13888                    for (int checkUserId : sUserManager.getUserIds()) {
13889                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13890                        if (installAllowed) {
13891                            break;
13892                        }
13893                    }
13894                    if (!installAllowed) {
13895                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13896                    }
13897                }
13898                if (!pkgSetting.getInstalled(userId)) {
13899                    pkgSetting.setInstalled(true, userId);
13900                    pkgSetting.setHidden(false, userId);
13901                    pkgSetting.setInstallReason(installReason, userId);
13902                    mSettings.writePackageRestrictionsLPr(userId);
13903                    mSettings.writeKernelMappingLPr(pkgSetting);
13904                    installed = true;
13905                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13906                    // upgrade app from instant to full; we don't allow app downgrade
13907                    installed = true;
13908                }
13909                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13910            }
13911
13912            if (installed) {
13913                if (pkgSetting.pkg != null) {
13914                    synchronized (mInstallLock) {
13915                        // We don't need to freeze for a brand new install
13916                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13917                    }
13918                }
13919                sendPackageAddedForUser(packageName, pkgSetting, userId);
13920                synchronized (mPackages) {
13921                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13922                }
13923            }
13924        } finally {
13925            Binder.restoreCallingIdentity(callingId);
13926        }
13927
13928        return PackageManager.INSTALL_SUCCEEDED;
13929    }
13930
13931    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13932            boolean instantApp, boolean fullApp) {
13933        // no state specified; do nothing
13934        if (!instantApp && !fullApp) {
13935            return;
13936        }
13937        if (userId != UserHandle.USER_ALL) {
13938            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13939                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13940            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13941                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13942            }
13943        } else {
13944            for (int currentUserId : sUserManager.getUserIds()) {
13945                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13946                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13947                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13948                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13949                }
13950            }
13951        }
13952    }
13953
13954    boolean isUserRestricted(int userId, String restrictionKey) {
13955        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13956        if (restrictions.getBoolean(restrictionKey, false)) {
13957            Log.w(TAG, "User is restricted: " + restrictionKey);
13958            return true;
13959        }
13960        return false;
13961    }
13962
13963    @Override
13964    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13965            PersistableBundle appExtras, PersistableBundle launcherExtras, String callingPackage,
13966            int userId) {
13967        try {
13968            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
13969        } catch (SecurityException e) {
13970            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
13971                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
13972                            + Manifest.permission.MANAGE_USERS);
13973        }
13974        final int callingUid = Binder.getCallingUid();
13975        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13976                true /* requireFullPermission */, true /* checkShell */,
13977                "setPackagesSuspended for user " + userId);
13978        if (callingUid != Process.ROOT_UID &&
13979                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
13980            throw new IllegalArgumentException("callingPackage " + callingPackage + " does not"
13981                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
13982        }
13983
13984        if (ArrayUtils.isEmpty(packageNames)) {
13985            return packageNames;
13986        }
13987
13988        // List of package names for whom the suspended state has changed.
13989        final 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        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13993        final long callingId = Binder.clearCallingIdentity();
13994        try {
13995            synchronized (mPackages) {
13996                for (int i = 0; i < packageNames.length; i++) {
13997                    final String packageName = packageNames[i];
13998                    if (packageName == callingPackage) {
13999                        Slog.w(TAG, "Calling package: " + callingPackage + "trying to "
14000                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14001                        unactionedPackages.add(packageName);
14002                        continue;
14003                    }
14004                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14005                    if (pkgSetting == null
14006                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14007                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14008                                + "\". Skipping suspending/un-suspending.");
14009                        unactionedPackages.add(packageName);
14010                        continue;
14011                    }
14012                    if (pkgSetting.getSuspended(userId) != suspended) {
14013                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14014                            unactionedPackages.add(packageName);
14015                            continue;
14016                        }
14017                        pkgSetting.setSuspended(suspended, callingPackage, appExtras,
14018                                launcherExtras, userId);
14019                        changedPackages.add(packageName);
14020                    }
14021                }
14022            }
14023        } finally {
14024            Binder.restoreCallingIdentity(callingId);
14025        }
14026        // TODO (b/75036698): Also send each package a broadcast when suspended state changed
14027        if (!changedPackages.isEmpty()) {
14028            sendPackagesSuspendedForUser(changedPackages.toArray(
14029                    new String[changedPackages.size()]), userId, suspended);
14030            synchronized (mPackages) {
14031                scheduleWritePackageRestrictionsLocked(userId);
14032            }
14033        }
14034
14035        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14036    }
14037
14038    @Override
14039    public PersistableBundle getPackageSuspendedAppExtras(String packageName, int userId) {
14040        final int callingUid = Binder.getCallingUid();
14041        if (getPackageUid(packageName, 0, userId) != callingUid) {
14042            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14043        }
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            final PackageUserState packageUserState = ps.readUserState(userId);
14050            return packageUserState.suspended ? packageUserState.suspendedAppExtras : null;
14051        }
14052    }
14053
14054    @Override
14055    public void setSuspendedPackageAppExtras(String packageName, PersistableBundle appExtras,
14056            int userId) {
14057        final int callingUid = Binder.getCallingUid();
14058        mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14059        synchronized (mPackages) {
14060            final PackageSetting ps = mSettings.mPackages.get(packageName);
14061            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14062                throw new IllegalArgumentException("Unknown target package: " + packageName);
14063            }
14064            final PackageUserState packageUserState = ps.readUserState(userId);
14065            if (packageUserState.suspended) {
14066                // TODO (b/75036698): Also send this package a broadcast with the new app extras
14067                packageUserState.suspendedAppExtras = appExtras;
14068            }
14069        }
14070    }
14071
14072    @Override
14073    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14074        final int callingUid = Binder.getCallingUid();
14075        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14076                true /* requireFullPermission */, false /* checkShell */,
14077                "isPackageSuspendedForUser for user " + userId);
14078        if (getPackageUid(packageName, 0, userId) != callingUid) {
14079            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14080        }
14081        synchronized (mPackages) {
14082            final PackageSetting ps = mSettings.mPackages.get(packageName);
14083            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14084                throw new IllegalArgumentException("Unknown target package: " + packageName);
14085            }
14086            return ps.getSuspended(userId);
14087        }
14088    }
14089
14090    void onSuspendingPackageRemoved(String packageName, int userId) {
14091        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14092                : new int[] {userId};
14093        synchronized (mPackages) {
14094            for (PackageSetting ps : mSettings.mPackages.values()) {
14095                for (int user : userIds) {
14096                    final PackageUserState pus = ps.readUserState(user);
14097                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14098                        ps.setSuspended(false, null, null, null, user);
14099                    }
14100                }
14101            }
14102        }
14103    }
14104
14105    @GuardedBy("mPackages")
14106    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14107        if (isPackageDeviceAdmin(packageName, userId)) {
14108            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14109                    + "\": has an active device admin");
14110            return false;
14111        }
14112
14113        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14114        if (packageName.equals(activeLauncherPackageName)) {
14115            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14116                    + "\": contains the active launcher");
14117            return false;
14118        }
14119
14120        if (packageName.equals(mRequiredInstallerPackage)) {
14121            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14122                    + "\": required for package installation");
14123            return false;
14124        }
14125
14126        if (packageName.equals(mRequiredUninstallerPackage)) {
14127            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14128                    + "\": required for package uninstallation");
14129            return false;
14130        }
14131
14132        if (packageName.equals(mRequiredVerifierPackage)) {
14133            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14134                    + "\": required for package verification");
14135            return false;
14136        }
14137
14138        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14139            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14140                    + "\": is the default dialer");
14141            return false;
14142        }
14143
14144        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14145            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14146                    + "\": protected package");
14147            return false;
14148        }
14149
14150        // Cannot suspend static shared libs as they are considered
14151        // a part of the using app (emulating static linking). Also
14152        // static libs are installed always on internal storage.
14153        PackageParser.Package pkg = mPackages.get(packageName);
14154        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14155            Slog.w(TAG, "Cannot suspend package: " + packageName
14156                    + " providing static shared library: "
14157                    + pkg.staticSharedLibName);
14158            return false;
14159        }
14160
14161        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14162            Slog.w(TAG, "Cannot suspend package: " + packageName);
14163            return false;
14164        }
14165
14166        return true;
14167    }
14168
14169    private String getActiveLauncherPackageName(int userId) {
14170        Intent intent = new Intent(Intent.ACTION_MAIN);
14171        intent.addCategory(Intent.CATEGORY_HOME);
14172        ResolveInfo resolveInfo = resolveIntent(
14173                intent,
14174                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14175                PackageManager.MATCH_DEFAULT_ONLY,
14176                userId);
14177
14178        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14179    }
14180
14181    private String getDefaultDialerPackageName(int userId) {
14182        synchronized (mPackages) {
14183            return mSettings.getDefaultDialerPackageNameLPw(userId);
14184        }
14185    }
14186
14187    @Override
14188    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14189        mContext.enforceCallingOrSelfPermission(
14190                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14191                "Only package verification agents can verify applications");
14192
14193        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14194        final PackageVerificationResponse response = new PackageVerificationResponse(
14195                verificationCode, Binder.getCallingUid());
14196        msg.arg1 = id;
14197        msg.obj = response;
14198        mHandler.sendMessage(msg);
14199    }
14200
14201    @Override
14202    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14203            long millisecondsToDelay) {
14204        mContext.enforceCallingOrSelfPermission(
14205                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14206                "Only package verification agents can extend verification timeouts");
14207
14208        final PackageVerificationState state = mPendingVerification.get(id);
14209        final PackageVerificationResponse response = new PackageVerificationResponse(
14210                verificationCodeAtTimeout, Binder.getCallingUid());
14211
14212        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14213            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14214        }
14215        if (millisecondsToDelay < 0) {
14216            millisecondsToDelay = 0;
14217        }
14218        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14219                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14220            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14221        }
14222
14223        if ((state != null) && !state.timeoutExtended()) {
14224            state.extendTimeout();
14225
14226            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14227            msg.arg1 = id;
14228            msg.obj = response;
14229            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14230        }
14231    }
14232
14233    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14234            int verificationCode, UserHandle user) {
14235        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14236        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14237        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14238        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14239        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14240
14241        mContext.sendBroadcastAsUser(intent, user,
14242                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14243    }
14244
14245    private ComponentName matchComponentForVerifier(String packageName,
14246            List<ResolveInfo> receivers) {
14247        ActivityInfo targetReceiver = null;
14248
14249        final int NR = receivers.size();
14250        for (int i = 0; i < NR; i++) {
14251            final ResolveInfo info = receivers.get(i);
14252            if (info.activityInfo == null) {
14253                continue;
14254            }
14255
14256            if (packageName.equals(info.activityInfo.packageName)) {
14257                targetReceiver = info.activityInfo;
14258                break;
14259            }
14260        }
14261
14262        if (targetReceiver == null) {
14263            return null;
14264        }
14265
14266        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14267    }
14268
14269    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14270            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14271        if (pkgInfo.verifiers.length == 0) {
14272            return null;
14273        }
14274
14275        final int N = pkgInfo.verifiers.length;
14276        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14277        for (int i = 0; i < N; i++) {
14278            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14279
14280            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14281                    receivers);
14282            if (comp == null) {
14283                continue;
14284            }
14285
14286            final int verifierUid = getUidForVerifier(verifierInfo);
14287            if (verifierUid == -1) {
14288                continue;
14289            }
14290
14291            if (DEBUG_VERIFY) {
14292                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14293                        + " with the correct signature");
14294            }
14295            sufficientVerifiers.add(comp);
14296            verificationState.addSufficientVerifier(verifierUid);
14297        }
14298
14299        return sufficientVerifiers;
14300    }
14301
14302    private int getUidForVerifier(VerifierInfo verifierInfo) {
14303        synchronized (mPackages) {
14304            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14305            if (pkg == null) {
14306                return -1;
14307            } else if (pkg.mSigningDetails.signatures.length != 1) {
14308                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14309                        + " has more than one signature; ignoring");
14310                return -1;
14311            }
14312
14313            /*
14314             * If the public key of the package's signature does not match
14315             * our expected public key, then this is a different package and
14316             * we should skip.
14317             */
14318
14319            final byte[] expectedPublicKey;
14320            try {
14321                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14322                final PublicKey publicKey = verifierSig.getPublicKey();
14323                expectedPublicKey = publicKey.getEncoded();
14324            } catch (CertificateException e) {
14325                return -1;
14326            }
14327
14328            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14329
14330            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14331                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14332                        + " does not have the expected public key; ignoring");
14333                return -1;
14334            }
14335
14336            return pkg.applicationInfo.uid;
14337        }
14338    }
14339
14340    @Override
14341    public void finishPackageInstall(int token, boolean didLaunch) {
14342        enforceSystemOrRoot("Only the system is allowed to finish installs");
14343
14344        if (DEBUG_INSTALL) {
14345            Slog.v(TAG, "BM finishing package install for " + token);
14346        }
14347        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14348
14349        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14350        mHandler.sendMessage(msg);
14351    }
14352
14353    /**
14354     * Get the verification agent timeout.  Used for both the APK verifier and the
14355     * intent filter verifier.
14356     *
14357     * @return verification timeout in milliseconds
14358     */
14359    private long getVerificationTimeout() {
14360        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14361                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14362                DEFAULT_VERIFICATION_TIMEOUT);
14363    }
14364
14365    /**
14366     * Get the default verification agent response code.
14367     *
14368     * @return default verification response code
14369     */
14370    private int getDefaultVerificationResponse(UserHandle user) {
14371        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14372            return PackageManager.VERIFICATION_REJECT;
14373        }
14374        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14375                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14376                DEFAULT_VERIFICATION_RESPONSE);
14377    }
14378
14379    /**
14380     * Check whether or not package verification has been enabled.
14381     *
14382     * @return true if verification should be performed
14383     */
14384    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14385        if (!DEFAULT_VERIFY_ENABLE) {
14386            return false;
14387        }
14388
14389        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14390
14391        // Check if installing from ADB
14392        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14393            // Do not run verification in a test harness environment
14394            if (ActivityManager.isRunningInTestHarness()) {
14395                return false;
14396            }
14397            if (ensureVerifyAppsEnabled) {
14398                return true;
14399            }
14400            // Check if the developer does not want package verification for ADB installs
14401            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14402                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14403                return false;
14404            }
14405        } else {
14406            // only when not installed from ADB, skip verification for instant apps when
14407            // the installer and verifier are the same.
14408            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14409                if (mInstantAppInstallerActivity != null
14410                        && mInstantAppInstallerActivity.packageName.equals(
14411                                mRequiredVerifierPackage)) {
14412                    try {
14413                        mContext.getSystemService(AppOpsManager.class)
14414                                .checkPackage(installerUid, mRequiredVerifierPackage);
14415                        if (DEBUG_VERIFY) {
14416                            Slog.i(TAG, "disable verification for instant app");
14417                        }
14418                        return false;
14419                    } catch (SecurityException ignore) { }
14420                }
14421            }
14422        }
14423
14424        if (ensureVerifyAppsEnabled) {
14425            return true;
14426        }
14427
14428        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14429                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14430    }
14431
14432    @Override
14433    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14434            throws RemoteException {
14435        mContext.enforceCallingOrSelfPermission(
14436                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14437                "Only intentfilter verification agents can verify applications");
14438
14439        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14440        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14441                Binder.getCallingUid(), verificationCode, failedDomains);
14442        msg.arg1 = id;
14443        msg.obj = response;
14444        mHandler.sendMessage(msg);
14445    }
14446
14447    @Override
14448    public int getIntentVerificationStatus(String packageName, int userId) {
14449        final int callingUid = Binder.getCallingUid();
14450        if (UserHandle.getUserId(callingUid) != userId) {
14451            mContext.enforceCallingOrSelfPermission(
14452                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14453                    "getIntentVerificationStatus" + userId);
14454        }
14455        if (getInstantAppPackageName(callingUid) != null) {
14456            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14457        }
14458        synchronized (mPackages) {
14459            final PackageSetting ps = mSettings.mPackages.get(packageName);
14460            if (ps == null
14461                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14462                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14463            }
14464            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14465        }
14466    }
14467
14468    @Override
14469    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14470        mContext.enforceCallingOrSelfPermission(
14471                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14472
14473        boolean result = false;
14474        synchronized (mPackages) {
14475            final PackageSetting ps = mSettings.mPackages.get(packageName);
14476            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14477                return false;
14478            }
14479            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14480        }
14481        if (result) {
14482            scheduleWritePackageRestrictionsLocked(userId);
14483        }
14484        return result;
14485    }
14486
14487    @Override
14488    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14489            String packageName) {
14490        final int callingUid = Binder.getCallingUid();
14491        if (getInstantAppPackageName(callingUid) != null) {
14492            return ParceledListSlice.emptyList();
14493        }
14494        synchronized (mPackages) {
14495            final PackageSetting ps = mSettings.mPackages.get(packageName);
14496            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14497                return ParceledListSlice.emptyList();
14498            }
14499            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14500        }
14501    }
14502
14503    @Override
14504    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14505        if (TextUtils.isEmpty(packageName)) {
14506            return ParceledListSlice.emptyList();
14507        }
14508        final int callingUid = Binder.getCallingUid();
14509        final int callingUserId = UserHandle.getUserId(callingUid);
14510        synchronized (mPackages) {
14511            PackageParser.Package pkg = mPackages.get(packageName);
14512            if (pkg == null || pkg.activities == null) {
14513                return ParceledListSlice.emptyList();
14514            }
14515            if (pkg.mExtras == null) {
14516                return ParceledListSlice.emptyList();
14517            }
14518            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14519            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14520                return ParceledListSlice.emptyList();
14521            }
14522            final int count = pkg.activities.size();
14523            ArrayList<IntentFilter> result = new ArrayList<>();
14524            for (int n=0; n<count; n++) {
14525                PackageParser.Activity activity = pkg.activities.get(n);
14526                if (activity.intents != null && activity.intents.size() > 0) {
14527                    result.addAll(activity.intents);
14528                }
14529            }
14530            return new ParceledListSlice<>(result);
14531        }
14532    }
14533
14534    @Override
14535    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14536        mContext.enforceCallingOrSelfPermission(
14537                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14538        if (UserHandle.getCallingUserId() != userId) {
14539            mContext.enforceCallingOrSelfPermission(
14540                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14541        }
14542
14543        synchronized (mPackages) {
14544            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14545            if (packageName != null) {
14546                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14547                        packageName, userId);
14548            }
14549            return result;
14550        }
14551    }
14552
14553    @Override
14554    public String getDefaultBrowserPackageName(int userId) {
14555        if (UserHandle.getCallingUserId() != userId) {
14556            mContext.enforceCallingOrSelfPermission(
14557                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14558        }
14559        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14560            return null;
14561        }
14562        synchronized (mPackages) {
14563            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14564        }
14565    }
14566
14567    /**
14568     * Get the "allow unknown sources" setting.
14569     *
14570     * @return the current "allow unknown sources" setting
14571     */
14572    private int getUnknownSourcesSettings() {
14573        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14574                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14575                -1);
14576    }
14577
14578    @Override
14579    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14580        final int callingUid = Binder.getCallingUid();
14581        if (getInstantAppPackageName(callingUid) != null) {
14582            return;
14583        }
14584        // writer
14585        synchronized (mPackages) {
14586            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14587            if (targetPackageSetting == null
14588                    || filterAppAccessLPr(
14589                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14590                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14591            }
14592
14593            PackageSetting installerPackageSetting;
14594            if (installerPackageName != null) {
14595                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14596                if (installerPackageSetting == null) {
14597                    throw new IllegalArgumentException("Unknown installer package: "
14598                            + installerPackageName);
14599                }
14600            } else {
14601                installerPackageSetting = null;
14602            }
14603
14604            Signature[] callerSignature;
14605            Object obj = mSettings.getUserIdLPr(callingUid);
14606            if (obj != null) {
14607                if (obj instanceof SharedUserSetting) {
14608                    callerSignature =
14609                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14610                } else if (obj instanceof PackageSetting) {
14611                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14612                } else {
14613                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14614                }
14615            } else {
14616                throw new SecurityException("Unknown calling UID: " + callingUid);
14617            }
14618
14619            // Verify: can't set installerPackageName to a package that is
14620            // not signed with the same cert as the caller.
14621            if (installerPackageSetting != null) {
14622                if (compareSignatures(callerSignature,
14623                        installerPackageSetting.signatures.mSigningDetails.signatures)
14624                        != PackageManager.SIGNATURE_MATCH) {
14625                    throw new SecurityException(
14626                            "Caller does not have same cert as new installer package "
14627                            + installerPackageName);
14628                }
14629            }
14630
14631            // Verify: if target already has an installer package, it must
14632            // be signed with the same cert as the caller.
14633            if (targetPackageSetting.installerPackageName != null) {
14634                PackageSetting setting = mSettings.mPackages.get(
14635                        targetPackageSetting.installerPackageName);
14636                // If the currently set package isn't valid, then it's always
14637                // okay to change it.
14638                if (setting != null) {
14639                    if (compareSignatures(callerSignature,
14640                            setting.signatures.mSigningDetails.signatures)
14641                            != PackageManager.SIGNATURE_MATCH) {
14642                        throw new SecurityException(
14643                                "Caller does not have same cert as old installer package "
14644                                + targetPackageSetting.installerPackageName);
14645                    }
14646                }
14647            }
14648
14649            // Okay!
14650            targetPackageSetting.installerPackageName = installerPackageName;
14651            if (installerPackageName != null) {
14652                mSettings.mInstallerPackages.add(installerPackageName);
14653            }
14654            scheduleWriteSettingsLocked();
14655        }
14656    }
14657
14658    @Override
14659    public void setApplicationCategoryHint(String packageName, int categoryHint,
14660            String callerPackageName) {
14661        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14662            throw new SecurityException("Instant applications don't have access to this method");
14663        }
14664        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14665                callerPackageName);
14666        synchronized (mPackages) {
14667            PackageSetting ps = mSettings.mPackages.get(packageName);
14668            if (ps == null) {
14669                throw new IllegalArgumentException("Unknown target package " + packageName);
14670            }
14671            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14672                throw new IllegalArgumentException("Unknown target package " + packageName);
14673            }
14674            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14675                throw new IllegalArgumentException("Calling package " + callerPackageName
14676                        + " is not installer for " + packageName);
14677            }
14678
14679            if (ps.categoryHint != categoryHint) {
14680                ps.categoryHint = categoryHint;
14681                scheduleWriteSettingsLocked();
14682            }
14683        }
14684    }
14685
14686    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14687        // Queue up an async operation since the package installation may take a little while.
14688        mHandler.post(new Runnable() {
14689            public void run() {
14690                mHandler.removeCallbacks(this);
14691                 // Result object to be returned
14692                PackageInstalledInfo res = new PackageInstalledInfo();
14693                res.setReturnCode(currentStatus);
14694                res.uid = -1;
14695                res.pkg = null;
14696                res.removedInfo = null;
14697                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14698                    args.doPreInstall(res.returnCode);
14699                    synchronized (mInstallLock) {
14700                        installPackageTracedLI(args, res);
14701                    }
14702                    args.doPostInstall(res.returnCode, res.uid);
14703                }
14704
14705                // A restore should be performed at this point if (a) the install
14706                // succeeded, (b) the operation is not an update, and (c) the new
14707                // package has not opted out of backup participation.
14708                final boolean update = res.removedInfo != null
14709                        && res.removedInfo.removedPackage != null;
14710                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14711                boolean doRestore = !update
14712                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14713
14714                // Set up the post-install work request bookkeeping.  This will be used
14715                // and cleaned up by the post-install event handling regardless of whether
14716                // there's a restore pass performed.  Token values are >= 1.
14717                int token;
14718                if (mNextInstallToken < 0) mNextInstallToken = 1;
14719                token = mNextInstallToken++;
14720
14721                PostInstallData data = new PostInstallData(args, res);
14722                mRunningInstalls.put(token, data);
14723                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14724
14725                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14726                    // Pass responsibility to the Backup Manager.  It will perform a
14727                    // restore if appropriate, then pass responsibility back to the
14728                    // Package Manager to run the post-install observer callbacks
14729                    // and broadcasts.
14730                    IBackupManager bm = IBackupManager.Stub.asInterface(
14731                            ServiceManager.getService(Context.BACKUP_SERVICE));
14732                    if (bm != null) {
14733                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14734                                + " to BM for possible restore");
14735                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14736                        try {
14737                            // TODO: http://b/22388012
14738                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14739                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14740                            } else {
14741                                doRestore = false;
14742                            }
14743                        } catch (RemoteException e) {
14744                            // can't happen; the backup manager is local
14745                        } catch (Exception e) {
14746                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14747                            doRestore = false;
14748                        }
14749                    } else {
14750                        Slog.e(TAG, "Backup Manager not found!");
14751                        doRestore = false;
14752                    }
14753                }
14754
14755                if (!doRestore) {
14756                    // No restore possible, or the Backup Manager was mysteriously not
14757                    // available -- just fire the post-install work request directly.
14758                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14759
14760                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14761
14762                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14763                    mHandler.sendMessage(msg);
14764                }
14765            }
14766        });
14767    }
14768
14769    /**
14770     * Callback from PackageSettings whenever an app is first transitioned out of the
14771     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14772     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14773     * here whether the app is the target of an ongoing install, and only send the
14774     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14775     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14776     * handling.
14777     */
14778    void notifyFirstLaunch(final String packageName, final String installerPackage,
14779            final int userId) {
14780        // Serialize this with the rest of the install-process message chain.  In the
14781        // restore-at-install case, this Runnable will necessarily run before the
14782        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14783        // are coherent.  In the non-restore case, the app has already completed install
14784        // and been launched through some other means, so it is not in a problematic
14785        // state for observers to see the FIRST_LAUNCH signal.
14786        mHandler.post(new Runnable() {
14787            @Override
14788            public void run() {
14789                for (int i = 0; i < mRunningInstalls.size(); i++) {
14790                    final PostInstallData data = mRunningInstalls.valueAt(i);
14791                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14792                        continue;
14793                    }
14794                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14795                        // right package; but is it for the right user?
14796                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14797                            if (userId == data.res.newUsers[uIndex]) {
14798                                if (DEBUG_BACKUP) {
14799                                    Slog.i(TAG, "Package " + packageName
14800                                            + " being restored so deferring FIRST_LAUNCH");
14801                                }
14802                                return;
14803                            }
14804                        }
14805                    }
14806                }
14807                // didn't find it, so not being restored
14808                if (DEBUG_BACKUP) {
14809                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14810                }
14811                final boolean isInstantApp = isInstantApp(packageName, userId);
14812                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14813                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14814                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14815            }
14816        });
14817    }
14818
14819    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14820            int[] userIds, int[] instantUserIds) {
14821        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14822                installerPkg, null, userIds, instantUserIds);
14823    }
14824
14825    private abstract class HandlerParams {
14826        private static final int MAX_RETRIES = 4;
14827
14828        /**
14829         * Number of times startCopy() has been attempted and had a non-fatal
14830         * error.
14831         */
14832        private int mRetries = 0;
14833
14834        /** User handle for the user requesting the information or installation. */
14835        private final UserHandle mUser;
14836        String traceMethod;
14837        int traceCookie;
14838
14839        HandlerParams(UserHandle user) {
14840            mUser = user;
14841        }
14842
14843        UserHandle getUser() {
14844            return mUser;
14845        }
14846
14847        HandlerParams setTraceMethod(String traceMethod) {
14848            this.traceMethod = traceMethod;
14849            return this;
14850        }
14851
14852        HandlerParams setTraceCookie(int traceCookie) {
14853            this.traceCookie = traceCookie;
14854            return this;
14855        }
14856
14857        final boolean startCopy() {
14858            boolean res;
14859            try {
14860                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14861
14862                if (++mRetries > MAX_RETRIES) {
14863                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14864                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14865                    handleServiceError();
14866                    return false;
14867                } else {
14868                    handleStartCopy();
14869                    res = true;
14870                }
14871            } catch (RemoteException e) {
14872                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14873                mHandler.sendEmptyMessage(MCS_RECONNECT);
14874                res = false;
14875            }
14876            handleReturnCode();
14877            return res;
14878        }
14879
14880        final void serviceError() {
14881            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14882            handleServiceError();
14883            handleReturnCode();
14884        }
14885
14886        abstract void handleStartCopy() throws RemoteException;
14887        abstract void handleServiceError();
14888        abstract void handleReturnCode();
14889    }
14890
14891    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14892        for (File path : paths) {
14893            try {
14894                mcs.clearDirectory(path.getAbsolutePath());
14895            } catch (RemoteException e) {
14896            }
14897        }
14898    }
14899
14900    static class OriginInfo {
14901        /**
14902         * Location where install is coming from, before it has been
14903         * copied/renamed into place. This could be a single monolithic APK
14904         * file, or a cluster directory. This location may be untrusted.
14905         */
14906        final File file;
14907
14908        /**
14909         * Flag indicating that {@link #file} or {@link #cid} has already been
14910         * staged, meaning downstream users don't need to defensively copy the
14911         * contents.
14912         */
14913        final boolean staged;
14914
14915        /**
14916         * Flag indicating that {@link #file} or {@link #cid} is an already
14917         * installed app that is being moved.
14918         */
14919        final boolean existing;
14920
14921        final String resolvedPath;
14922        final File resolvedFile;
14923
14924        static OriginInfo fromNothing() {
14925            return new OriginInfo(null, false, false);
14926        }
14927
14928        static OriginInfo fromUntrustedFile(File file) {
14929            return new OriginInfo(file, false, false);
14930        }
14931
14932        static OriginInfo fromExistingFile(File file) {
14933            return new OriginInfo(file, false, true);
14934        }
14935
14936        static OriginInfo fromStagedFile(File file) {
14937            return new OriginInfo(file, true, false);
14938        }
14939
14940        private OriginInfo(File file, boolean staged, boolean existing) {
14941            this.file = file;
14942            this.staged = staged;
14943            this.existing = existing;
14944
14945            if (file != null) {
14946                resolvedPath = file.getAbsolutePath();
14947                resolvedFile = file;
14948            } else {
14949                resolvedPath = null;
14950                resolvedFile = null;
14951            }
14952        }
14953    }
14954
14955    static class MoveInfo {
14956        final int moveId;
14957        final String fromUuid;
14958        final String toUuid;
14959        final String packageName;
14960        final String dataAppName;
14961        final int appId;
14962        final String seinfo;
14963        final int targetSdkVersion;
14964
14965        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14966                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14967            this.moveId = moveId;
14968            this.fromUuid = fromUuid;
14969            this.toUuid = toUuid;
14970            this.packageName = packageName;
14971            this.dataAppName = dataAppName;
14972            this.appId = appId;
14973            this.seinfo = seinfo;
14974            this.targetSdkVersion = targetSdkVersion;
14975        }
14976    }
14977
14978    static class VerificationInfo {
14979        /** A constant used to indicate that a uid value is not present. */
14980        public static final int NO_UID = -1;
14981
14982        /** URI referencing where the package was downloaded from. */
14983        final Uri originatingUri;
14984
14985        /** HTTP referrer URI associated with the originatingURI. */
14986        final Uri referrer;
14987
14988        /** UID of the application that the install request originated from. */
14989        final int originatingUid;
14990
14991        /** UID of application requesting the install */
14992        final int installerUid;
14993
14994        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14995            this.originatingUri = originatingUri;
14996            this.referrer = referrer;
14997            this.originatingUid = originatingUid;
14998            this.installerUid = installerUid;
14999        }
15000    }
15001
15002    class InstallParams extends HandlerParams {
15003        final OriginInfo origin;
15004        final MoveInfo move;
15005        final IPackageInstallObserver2 observer;
15006        int installFlags;
15007        final String installerPackageName;
15008        final String volumeUuid;
15009        private InstallArgs mArgs;
15010        private int mRet;
15011        final String packageAbiOverride;
15012        final String[] grantedRuntimePermissions;
15013        final VerificationInfo verificationInfo;
15014        final PackageParser.SigningDetails signingDetails;
15015        final int installReason;
15016
15017        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15018                int installFlags, String installerPackageName, String volumeUuid,
15019                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15020                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15021            super(user);
15022            this.origin = origin;
15023            this.move = move;
15024            this.observer = observer;
15025            this.installFlags = installFlags;
15026            this.installerPackageName = installerPackageName;
15027            this.volumeUuid = volumeUuid;
15028            this.verificationInfo = verificationInfo;
15029            this.packageAbiOverride = packageAbiOverride;
15030            this.grantedRuntimePermissions = grantedPermissions;
15031            this.signingDetails = signingDetails;
15032            this.installReason = installReason;
15033        }
15034
15035        @Override
15036        public String toString() {
15037            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15038                    + " file=" + origin.file + "}";
15039        }
15040
15041        private int installLocationPolicy(PackageInfoLite pkgLite) {
15042            String packageName = pkgLite.packageName;
15043            int installLocation = pkgLite.installLocation;
15044            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15045            // reader
15046            synchronized (mPackages) {
15047                // Currently installed package which the new package is attempting to replace or
15048                // null if no such package is installed.
15049                PackageParser.Package installedPkg = mPackages.get(packageName);
15050                // Package which currently owns the data which the new package will own if installed.
15051                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15052                // will be null whereas dataOwnerPkg will contain information about the package
15053                // which was uninstalled while keeping its data.
15054                PackageParser.Package dataOwnerPkg = installedPkg;
15055                if (dataOwnerPkg  == null) {
15056                    PackageSetting ps = mSettings.mPackages.get(packageName);
15057                    if (ps != null) {
15058                        dataOwnerPkg = ps.pkg;
15059                    }
15060                }
15061
15062                if (dataOwnerPkg != null) {
15063                    // If installed, the package will get access to data left on the device by its
15064                    // predecessor. As a security measure, this is permited only if this is not a
15065                    // version downgrade or if the predecessor package is marked as debuggable and
15066                    // a downgrade is explicitly requested.
15067                    //
15068                    // On debuggable platform builds, downgrades are permitted even for
15069                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15070                    // not offer security guarantees and thus it's OK to disable some security
15071                    // mechanisms to make debugging/testing easier on those builds. However, even on
15072                    // debuggable builds downgrades of packages are permitted only if requested via
15073                    // installFlags. This is because we aim to keep the behavior of debuggable
15074                    // platform builds as close as possible to the behavior of non-debuggable
15075                    // platform builds.
15076                    final boolean downgradeRequested =
15077                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15078                    final boolean packageDebuggable =
15079                                (dataOwnerPkg.applicationInfo.flags
15080                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15081                    final boolean downgradePermitted =
15082                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15083                    if (!downgradePermitted) {
15084                        try {
15085                            checkDowngrade(dataOwnerPkg, pkgLite);
15086                        } catch (PackageManagerException e) {
15087                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15088                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15089                        }
15090                    }
15091                }
15092
15093                if (installedPkg != null) {
15094                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15095                        // Check for updated system application.
15096                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15097                            if (onSd) {
15098                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15099                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15100                            }
15101                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15102                        } else {
15103                            if (onSd) {
15104                                // Install flag overrides everything.
15105                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15106                            }
15107                            // If current upgrade specifies particular preference
15108                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15109                                // Application explicitly specified internal.
15110                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15111                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15112                                // App explictly prefers external. Let policy decide
15113                            } else {
15114                                // Prefer previous location
15115                                if (isExternal(installedPkg)) {
15116                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15117                                }
15118                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15119                            }
15120                        }
15121                    } else {
15122                        // Invalid install. Return error code
15123                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15124                    }
15125                }
15126            }
15127            // All the special cases have been taken care of.
15128            // Return result based on recommended install location.
15129            if (onSd) {
15130                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15131            }
15132            return pkgLite.recommendedInstallLocation;
15133        }
15134
15135        /*
15136         * Invoke remote method to get package information and install
15137         * location values. Override install location based on default
15138         * policy if needed and then create install arguments based
15139         * on the install location.
15140         */
15141        public void handleStartCopy() throws RemoteException {
15142            int ret = PackageManager.INSTALL_SUCCEEDED;
15143
15144            // If we're already staged, we've firmly committed to an install location
15145            if (origin.staged) {
15146                if (origin.file != null) {
15147                    installFlags |= PackageManager.INSTALL_INTERNAL;
15148                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15149                } else {
15150                    throw new IllegalStateException("Invalid stage location");
15151                }
15152            }
15153
15154            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15155            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15156            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15157            PackageInfoLite pkgLite = null;
15158
15159            if (onInt && onSd) {
15160                // Check if both bits are set.
15161                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15162                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15163            } else if (onSd && ephemeral) {
15164                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15165                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15166            } else {
15167                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15168                        packageAbiOverride);
15169
15170                if (DEBUG_INSTANT && ephemeral) {
15171                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15172                }
15173
15174                /*
15175                 * If we have too little free space, try to free cache
15176                 * before giving up.
15177                 */
15178                if (!origin.staged && pkgLite.recommendedInstallLocation
15179                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15180                    // TODO: focus freeing disk space on the target device
15181                    final StorageManager storage = StorageManager.from(mContext);
15182                    final long lowThreshold = storage.getStorageLowBytes(
15183                            Environment.getDataDirectory());
15184
15185                    final long sizeBytes = mContainerService.calculateInstalledSize(
15186                            origin.resolvedPath, packageAbiOverride);
15187
15188                    try {
15189                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15190                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15191                                installFlags, packageAbiOverride);
15192                    } catch (InstallerException e) {
15193                        Slog.w(TAG, "Failed to free cache", e);
15194                    }
15195
15196                    /*
15197                     * The cache free must have deleted the file we
15198                     * downloaded to install.
15199                     *
15200                     * TODO: fix the "freeCache" call to not delete
15201                     *       the file we care about.
15202                     */
15203                    if (pkgLite.recommendedInstallLocation
15204                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15205                        pkgLite.recommendedInstallLocation
15206                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15207                    }
15208                }
15209            }
15210
15211            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15212                int loc = pkgLite.recommendedInstallLocation;
15213                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15214                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15215                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15216                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15217                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15218                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15219                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15220                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15221                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15222                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15223                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15224                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15225                } else {
15226                    // Override with defaults if needed.
15227                    loc = installLocationPolicy(pkgLite);
15228                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15229                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15230                    } else if (!onSd && !onInt) {
15231                        // Override install location with flags
15232                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15233                            // Set the flag to install on external media.
15234                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15235                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15236                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15237                            if (DEBUG_INSTANT) {
15238                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15239                            }
15240                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15241                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15242                                    |PackageManager.INSTALL_INTERNAL);
15243                        } else {
15244                            // Make sure the flag for installing on external
15245                            // media is unset
15246                            installFlags |= PackageManager.INSTALL_INTERNAL;
15247                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15248                        }
15249                    }
15250                }
15251            }
15252
15253            final InstallArgs args = createInstallArgs(this);
15254            mArgs = args;
15255
15256            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15257                // TODO: http://b/22976637
15258                // Apps installed for "all" users use the device owner to verify the app
15259                UserHandle verifierUser = getUser();
15260                if (verifierUser == UserHandle.ALL) {
15261                    verifierUser = UserHandle.SYSTEM;
15262                }
15263
15264                /*
15265                 * Determine if we have any installed package verifiers. If we
15266                 * do, then we'll defer to them to verify the packages.
15267                 */
15268                final int requiredUid = mRequiredVerifierPackage == null ? -1
15269                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15270                                verifierUser.getIdentifier());
15271                final int installerUid =
15272                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15273                if (!origin.existing && requiredUid != -1
15274                        && isVerificationEnabled(
15275                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15276                    final Intent verification = new Intent(
15277                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15278                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15279                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15280                            PACKAGE_MIME_TYPE);
15281                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15282
15283                    // Query all live verifiers based on current user state
15284                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15285                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15286                            false /*allowDynamicSplits*/);
15287
15288                    if (DEBUG_VERIFY) {
15289                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15290                                + verification.toString() + " with " + pkgLite.verifiers.length
15291                                + " optional verifiers");
15292                    }
15293
15294                    final int verificationId = mPendingVerificationToken++;
15295
15296                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15297
15298                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15299                            installerPackageName);
15300
15301                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15302                            installFlags);
15303
15304                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15305                            pkgLite.packageName);
15306
15307                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15308                            pkgLite.versionCode);
15309
15310                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15311                            pkgLite.getLongVersionCode());
15312
15313                    if (verificationInfo != null) {
15314                        if (verificationInfo.originatingUri != null) {
15315                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15316                                    verificationInfo.originatingUri);
15317                        }
15318                        if (verificationInfo.referrer != null) {
15319                            verification.putExtra(Intent.EXTRA_REFERRER,
15320                                    verificationInfo.referrer);
15321                        }
15322                        if (verificationInfo.originatingUid >= 0) {
15323                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15324                                    verificationInfo.originatingUid);
15325                        }
15326                        if (verificationInfo.installerUid >= 0) {
15327                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15328                                    verificationInfo.installerUid);
15329                        }
15330                    }
15331
15332                    final PackageVerificationState verificationState = new PackageVerificationState(
15333                            requiredUid, args);
15334
15335                    mPendingVerification.append(verificationId, verificationState);
15336
15337                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15338                            receivers, verificationState);
15339
15340                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15341                    final long idleDuration = getVerificationTimeout();
15342
15343                    /*
15344                     * If any sufficient verifiers were listed in the package
15345                     * manifest, attempt to ask them.
15346                     */
15347                    if (sufficientVerifiers != null) {
15348                        final int N = sufficientVerifiers.size();
15349                        if (N == 0) {
15350                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15351                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15352                        } else {
15353                            for (int i = 0; i < N; i++) {
15354                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15355                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15356                                        verifierComponent.getPackageName(), idleDuration,
15357                                        verifierUser.getIdentifier(), false, "package verifier");
15358
15359                                final Intent sufficientIntent = new Intent(verification);
15360                                sufficientIntent.setComponent(verifierComponent);
15361                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15362                            }
15363                        }
15364                    }
15365
15366                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15367                            mRequiredVerifierPackage, receivers);
15368                    if (ret == PackageManager.INSTALL_SUCCEEDED
15369                            && mRequiredVerifierPackage != null) {
15370                        Trace.asyncTraceBegin(
15371                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15372                        /*
15373                         * Send the intent to the required verification agent,
15374                         * but only start the verification timeout after the
15375                         * target BroadcastReceivers have run.
15376                         */
15377                        verification.setComponent(requiredVerifierComponent);
15378                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15379                                mRequiredVerifierPackage, idleDuration,
15380                                verifierUser.getIdentifier(), false, "package verifier");
15381                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15382                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15383                                new BroadcastReceiver() {
15384                                    @Override
15385                                    public void onReceive(Context context, Intent intent) {
15386                                        final Message msg = mHandler
15387                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15388                                        msg.arg1 = verificationId;
15389                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15390                                    }
15391                                }, null, 0, null, null);
15392
15393                        /*
15394                         * We don't want the copy to proceed until verification
15395                         * succeeds, so null out this field.
15396                         */
15397                        mArgs = null;
15398                    }
15399                } else {
15400                    /*
15401                     * No package verification is enabled, so immediately start
15402                     * the remote call to initiate copy using temporary file.
15403                     */
15404                    ret = args.copyApk(mContainerService, true);
15405                }
15406            }
15407
15408            mRet = ret;
15409        }
15410
15411        @Override
15412        void handleReturnCode() {
15413            // If mArgs is null, then MCS couldn't be reached. When it
15414            // reconnects, it will try again to install. At that point, this
15415            // will succeed.
15416            if (mArgs != null) {
15417                processPendingInstall(mArgs, mRet);
15418            }
15419        }
15420
15421        @Override
15422        void handleServiceError() {
15423            mArgs = createInstallArgs(this);
15424            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15425        }
15426    }
15427
15428    private InstallArgs createInstallArgs(InstallParams params) {
15429        if (params.move != null) {
15430            return new MoveInstallArgs(params);
15431        } else {
15432            return new FileInstallArgs(params);
15433        }
15434    }
15435
15436    /**
15437     * Create args that describe an existing installed package. Typically used
15438     * when cleaning up old installs, or used as a move source.
15439     */
15440    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15441            String resourcePath, String[] instructionSets) {
15442        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15443    }
15444
15445    static abstract class InstallArgs {
15446        /** @see InstallParams#origin */
15447        final OriginInfo origin;
15448        /** @see InstallParams#move */
15449        final MoveInfo move;
15450
15451        final IPackageInstallObserver2 observer;
15452        // Always refers to PackageManager flags only
15453        final int installFlags;
15454        final String installerPackageName;
15455        final String volumeUuid;
15456        final UserHandle user;
15457        final String abiOverride;
15458        final String[] installGrantPermissions;
15459        /** If non-null, drop an async trace when the install completes */
15460        final String traceMethod;
15461        final int traceCookie;
15462        final PackageParser.SigningDetails signingDetails;
15463        final int installReason;
15464
15465        // The list of instruction sets supported by this app. This is currently
15466        // only used during the rmdex() phase to clean up resources. We can get rid of this
15467        // if we move dex files under the common app path.
15468        /* nullable */ String[] instructionSets;
15469
15470        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15471                int installFlags, String installerPackageName, String volumeUuid,
15472                UserHandle user, String[] instructionSets,
15473                String abiOverride, String[] installGrantPermissions,
15474                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15475                int installReason) {
15476            this.origin = origin;
15477            this.move = move;
15478            this.installFlags = installFlags;
15479            this.observer = observer;
15480            this.installerPackageName = installerPackageName;
15481            this.volumeUuid = volumeUuid;
15482            this.user = user;
15483            this.instructionSets = instructionSets;
15484            this.abiOverride = abiOverride;
15485            this.installGrantPermissions = installGrantPermissions;
15486            this.traceMethod = traceMethod;
15487            this.traceCookie = traceCookie;
15488            this.signingDetails = signingDetails;
15489            this.installReason = installReason;
15490        }
15491
15492        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15493        abstract int doPreInstall(int status);
15494
15495        /**
15496         * Rename package into final resting place. All paths on the given
15497         * scanned package should be updated to reflect the rename.
15498         */
15499        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15500        abstract int doPostInstall(int status, int uid);
15501
15502        /** @see PackageSettingBase#codePathString */
15503        abstract String getCodePath();
15504        /** @see PackageSettingBase#resourcePathString */
15505        abstract String getResourcePath();
15506
15507        // Need installer lock especially for dex file removal.
15508        abstract void cleanUpResourcesLI();
15509        abstract boolean doPostDeleteLI(boolean delete);
15510
15511        /**
15512         * Called before the source arguments are copied. This is used mostly
15513         * for MoveParams when it needs to read the source file to put it in the
15514         * destination.
15515         */
15516        int doPreCopy() {
15517            return PackageManager.INSTALL_SUCCEEDED;
15518        }
15519
15520        /**
15521         * Called after the source arguments are copied. This is used mostly for
15522         * MoveParams when it needs to read the source file to put it in the
15523         * destination.
15524         */
15525        int doPostCopy(int uid) {
15526            return PackageManager.INSTALL_SUCCEEDED;
15527        }
15528
15529        protected boolean isFwdLocked() {
15530            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15531        }
15532
15533        protected boolean isExternalAsec() {
15534            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15535        }
15536
15537        protected boolean isEphemeral() {
15538            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15539        }
15540
15541        UserHandle getUser() {
15542            return user;
15543        }
15544    }
15545
15546    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15547        if (!allCodePaths.isEmpty()) {
15548            if (instructionSets == null) {
15549                throw new IllegalStateException("instructionSet == null");
15550            }
15551            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15552            for (String codePath : allCodePaths) {
15553                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15554                    try {
15555                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15556                    } catch (InstallerException ignored) {
15557                    }
15558                }
15559            }
15560        }
15561    }
15562
15563    /**
15564     * Logic to handle installation of non-ASEC applications, including copying
15565     * and renaming logic.
15566     */
15567    class FileInstallArgs extends InstallArgs {
15568        private File codeFile;
15569        private File resourceFile;
15570
15571        // Example topology:
15572        // /data/app/com.example/base.apk
15573        // /data/app/com.example/split_foo.apk
15574        // /data/app/com.example/lib/arm/libfoo.so
15575        // /data/app/com.example/lib/arm64/libfoo.so
15576        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15577
15578        /** New install */
15579        FileInstallArgs(InstallParams params) {
15580            super(params.origin, params.move, params.observer, params.installFlags,
15581                    params.installerPackageName, params.volumeUuid,
15582                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15583                    params.grantedRuntimePermissions,
15584                    params.traceMethod, params.traceCookie, params.signingDetails,
15585                    params.installReason);
15586            if (isFwdLocked()) {
15587                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15588            }
15589        }
15590
15591        /** Existing install */
15592        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15593            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15594                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15595                    PackageManager.INSTALL_REASON_UNKNOWN);
15596            this.codeFile = (codePath != null) ? new File(codePath) : null;
15597            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15598        }
15599
15600        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15601            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15602            try {
15603                return doCopyApk(imcs, temp);
15604            } finally {
15605                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15606            }
15607        }
15608
15609        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15610            if (origin.staged) {
15611                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15612                codeFile = origin.file;
15613                resourceFile = origin.file;
15614                return PackageManager.INSTALL_SUCCEEDED;
15615            }
15616
15617            try {
15618                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15619                final File tempDir =
15620                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15621                codeFile = tempDir;
15622                resourceFile = tempDir;
15623            } catch (IOException e) {
15624                Slog.w(TAG, "Failed to create copy file: " + e);
15625                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15626            }
15627
15628            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15629                @Override
15630                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15631                    if (!FileUtils.isValidExtFilename(name)) {
15632                        throw new IllegalArgumentException("Invalid filename: " + name);
15633                    }
15634                    try {
15635                        final File file = new File(codeFile, name);
15636                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15637                                O_RDWR | O_CREAT, 0644);
15638                        Os.chmod(file.getAbsolutePath(), 0644);
15639                        return new ParcelFileDescriptor(fd);
15640                    } catch (ErrnoException e) {
15641                        throw new RemoteException("Failed to open: " + e.getMessage());
15642                    }
15643                }
15644            };
15645
15646            int ret = PackageManager.INSTALL_SUCCEEDED;
15647            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15648            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15649                Slog.e(TAG, "Failed to copy package");
15650                return ret;
15651            }
15652
15653            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15654            NativeLibraryHelper.Handle handle = null;
15655            try {
15656                handle = NativeLibraryHelper.Handle.create(codeFile);
15657                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15658                        abiOverride);
15659            } catch (IOException e) {
15660                Slog.e(TAG, "Copying native libraries failed", e);
15661                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15662            } finally {
15663                IoUtils.closeQuietly(handle);
15664            }
15665
15666            return ret;
15667        }
15668
15669        int doPreInstall(int status) {
15670            if (status != PackageManager.INSTALL_SUCCEEDED) {
15671                cleanUp();
15672            }
15673            return status;
15674        }
15675
15676        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15677            if (status != PackageManager.INSTALL_SUCCEEDED) {
15678                cleanUp();
15679                return false;
15680            }
15681
15682            final File targetDir = codeFile.getParentFile();
15683            final File beforeCodeFile = codeFile;
15684            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15685
15686            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15687            try {
15688                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15689            } catch (ErrnoException e) {
15690                Slog.w(TAG, "Failed to rename", e);
15691                return false;
15692            }
15693
15694            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15695                Slog.w(TAG, "Failed to restorecon");
15696                return false;
15697            }
15698
15699            // Reflect the rename internally
15700            codeFile = afterCodeFile;
15701            resourceFile = afterCodeFile;
15702
15703            // Reflect the rename in scanned details
15704            try {
15705                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15706            } catch (IOException e) {
15707                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15708                return false;
15709            }
15710            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15711                    afterCodeFile, pkg.baseCodePath));
15712            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15713                    afterCodeFile, pkg.splitCodePaths));
15714
15715            // Reflect the rename in app info
15716            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15717            pkg.setApplicationInfoCodePath(pkg.codePath);
15718            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15719            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15720            pkg.setApplicationInfoResourcePath(pkg.codePath);
15721            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15722            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15723
15724            return true;
15725        }
15726
15727        int doPostInstall(int status, int uid) {
15728            if (status != PackageManager.INSTALL_SUCCEEDED) {
15729                cleanUp();
15730            }
15731            return status;
15732        }
15733
15734        @Override
15735        String getCodePath() {
15736            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15737        }
15738
15739        @Override
15740        String getResourcePath() {
15741            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15742        }
15743
15744        private boolean cleanUp() {
15745            if (codeFile == null || !codeFile.exists()) {
15746                return false;
15747            }
15748
15749            removeCodePathLI(codeFile);
15750
15751            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15752                resourceFile.delete();
15753            }
15754
15755            return true;
15756        }
15757
15758        void cleanUpResourcesLI() {
15759            // Try enumerating all code paths before deleting
15760            List<String> allCodePaths = Collections.EMPTY_LIST;
15761            if (codeFile != null && codeFile.exists()) {
15762                try {
15763                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15764                    allCodePaths = pkg.getAllCodePaths();
15765                } catch (PackageParserException e) {
15766                    // Ignored; we tried our best
15767                }
15768            }
15769
15770            cleanUp();
15771            removeDexFiles(allCodePaths, instructionSets);
15772        }
15773
15774        boolean doPostDeleteLI(boolean delete) {
15775            // XXX err, shouldn't we respect the delete flag?
15776            cleanUpResourcesLI();
15777            return true;
15778        }
15779    }
15780
15781    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15782            PackageManagerException {
15783        if (copyRet < 0) {
15784            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15785                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15786                throw new PackageManagerException(copyRet, message);
15787            }
15788        }
15789    }
15790
15791    /**
15792     * Extract the StorageManagerService "container ID" from the full code path of an
15793     * .apk.
15794     */
15795    static String cidFromCodePath(String fullCodePath) {
15796        int eidx = fullCodePath.lastIndexOf("/");
15797        String subStr1 = fullCodePath.substring(0, eidx);
15798        int sidx = subStr1.lastIndexOf("/");
15799        return subStr1.substring(sidx+1, eidx);
15800    }
15801
15802    /**
15803     * Logic to handle movement of existing installed applications.
15804     */
15805    class MoveInstallArgs extends InstallArgs {
15806        private File codeFile;
15807        private File resourceFile;
15808
15809        /** New install */
15810        MoveInstallArgs(InstallParams params) {
15811            super(params.origin, params.move, params.observer, params.installFlags,
15812                    params.installerPackageName, params.volumeUuid,
15813                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15814                    params.grantedRuntimePermissions,
15815                    params.traceMethod, params.traceCookie, params.signingDetails,
15816                    params.installReason);
15817        }
15818
15819        int copyApk(IMediaContainerService imcs, boolean temp) {
15820            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15821                    + move.fromUuid + " to " + move.toUuid);
15822            synchronized (mInstaller) {
15823                try {
15824                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15825                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15826                } catch (InstallerException e) {
15827                    Slog.w(TAG, "Failed to move app", e);
15828                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15829                }
15830            }
15831
15832            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15833            resourceFile = codeFile;
15834            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15835
15836            return PackageManager.INSTALL_SUCCEEDED;
15837        }
15838
15839        int doPreInstall(int status) {
15840            if (status != PackageManager.INSTALL_SUCCEEDED) {
15841                cleanUp(move.toUuid);
15842            }
15843            return status;
15844        }
15845
15846        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15847            if (status != PackageManager.INSTALL_SUCCEEDED) {
15848                cleanUp(move.toUuid);
15849                return false;
15850            }
15851
15852            // Reflect the move in app info
15853            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15854            pkg.setApplicationInfoCodePath(pkg.codePath);
15855            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15856            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15857            pkg.setApplicationInfoResourcePath(pkg.codePath);
15858            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15859            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15860
15861            return true;
15862        }
15863
15864        int doPostInstall(int status, int uid) {
15865            if (status == PackageManager.INSTALL_SUCCEEDED) {
15866                cleanUp(move.fromUuid);
15867            } else {
15868                cleanUp(move.toUuid);
15869            }
15870            return status;
15871        }
15872
15873        @Override
15874        String getCodePath() {
15875            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15876        }
15877
15878        @Override
15879        String getResourcePath() {
15880            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15881        }
15882
15883        private boolean cleanUp(String volumeUuid) {
15884            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15885                    move.dataAppName);
15886            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15887            final int[] userIds = sUserManager.getUserIds();
15888            synchronized (mInstallLock) {
15889                // Clean up both app data and code
15890                // All package moves are frozen until finished
15891                for (int userId : userIds) {
15892                    try {
15893                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15894                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15895                    } catch (InstallerException e) {
15896                        Slog.w(TAG, String.valueOf(e));
15897                    }
15898                }
15899                removeCodePathLI(codeFile);
15900            }
15901            return true;
15902        }
15903
15904        void cleanUpResourcesLI() {
15905            throw new UnsupportedOperationException();
15906        }
15907
15908        boolean doPostDeleteLI(boolean delete) {
15909            throw new UnsupportedOperationException();
15910        }
15911    }
15912
15913    static String getAsecPackageName(String packageCid) {
15914        int idx = packageCid.lastIndexOf("-");
15915        if (idx == -1) {
15916            return packageCid;
15917        }
15918        return packageCid.substring(0, idx);
15919    }
15920
15921    // Utility method used to create code paths based on package name and available index.
15922    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15923        String idxStr = "";
15924        int idx = 1;
15925        // Fall back to default value of idx=1 if prefix is not
15926        // part of oldCodePath
15927        if (oldCodePath != null) {
15928            String subStr = oldCodePath;
15929            // Drop the suffix right away
15930            if (suffix != null && subStr.endsWith(suffix)) {
15931                subStr = subStr.substring(0, subStr.length() - suffix.length());
15932            }
15933            // If oldCodePath already contains prefix find out the
15934            // ending index to either increment or decrement.
15935            int sidx = subStr.lastIndexOf(prefix);
15936            if (sidx != -1) {
15937                subStr = subStr.substring(sidx + prefix.length());
15938                if (subStr != null) {
15939                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15940                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15941                    }
15942                    try {
15943                        idx = Integer.parseInt(subStr);
15944                        if (idx <= 1) {
15945                            idx++;
15946                        } else {
15947                            idx--;
15948                        }
15949                    } catch(NumberFormatException e) {
15950                    }
15951                }
15952            }
15953        }
15954        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15955        return prefix + idxStr;
15956    }
15957
15958    private File getNextCodePath(File targetDir, String packageName) {
15959        File result;
15960        SecureRandom random = new SecureRandom();
15961        byte[] bytes = new byte[16];
15962        do {
15963            random.nextBytes(bytes);
15964            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15965            result = new File(targetDir, packageName + "-" + suffix);
15966        } while (result.exists());
15967        return result;
15968    }
15969
15970    // Utility method that returns the relative package path with respect
15971    // to the installation directory. Like say for /data/data/com.test-1.apk
15972    // string com.test-1 is returned.
15973    static String deriveCodePathName(String codePath) {
15974        if (codePath == null) {
15975            return null;
15976        }
15977        final File codeFile = new File(codePath);
15978        final String name = codeFile.getName();
15979        if (codeFile.isDirectory()) {
15980            return name;
15981        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15982            final int lastDot = name.lastIndexOf('.');
15983            return name.substring(0, lastDot);
15984        } else {
15985            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15986            return null;
15987        }
15988    }
15989
15990    static class PackageInstalledInfo {
15991        String name;
15992        int uid;
15993        // The set of users that originally had this package installed.
15994        int[] origUsers;
15995        // The set of users that now have this package installed.
15996        int[] newUsers;
15997        PackageParser.Package pkg;
15998        int returnCode;
15999        String returnMsg;
16000        String installerPackageName;
16001        PackageRemovedInfo removedInfo;
16002        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16003
16004        public void setError(int code, String msg) {
16005            setReturnCode(code);
16006            setReturnMessage(msg);
16007            Slog.w(TAG, msg);
16008        }
16009
16010        public void setError(String msg, PackageParserException e) {
16011            setReturnCode(e.error);
16012            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16013            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16014            for (int i = 0; i < childCount; i++) {
16015                addedChildPackages.valueAt(i).setError(msg, e);
16016            }
16017            Slog.w(TAG, msg, e);
16018        }
16019
16020        public void setError(String msg, PackageManagerException e) {
16021            returnCode = e.error;
16022            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16023            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16024            for (int i = 0; i < childCount; i++) {
16025                addedChildPackages.valueAt(i).setError(msg, e);
16026            }
16027            Slog.w(TAG, msg, e);
16028        }
16029
16030        public void setReturnCode(int returnCode) {
16031            this.returnCode = returnCode;
16032            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16033            for (int i = 0; i < childCount; i++) {
16034                addedChildPackages.valueAt(i).returnCode = returnCode;
16035            }
16036        }
16037
16038        private void setReturnMessage(String returnMsg) {
16039            this.returnMsg = returnMsg;
16040            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16041            for (int i = 0; i < childCount; i++) {
16042                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16043            }
16044        }
16045
16046        // In some error cases we want to convey more info back to the observer
16047        String origPackage;
16048        String origPermission;
16049    }
16050
16051    /*
16052     * Install a non-existing package.
16053     */
16054    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16055            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16056            String volumeUuid, PackageInstalledInfo res, int installReason) {
16057        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16058
16059        // Remember this for later, in case we need to rollback this install
16060        String pkgName = pkg.packageName;
16061
16062        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16063
16064        synchronized(mPackages) {
16065            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16066            if (renamedPackage != null) {
16067                // A package with the same name is already installed, though
16068                // it has been renamed to an older name.  The package we
16069                // are trying to install should be installed as an update to
16070                // the existing one, but that has not been requested, so bail.
16071                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16072                        + " without first uninstalling package running as "
16073                        + renamedPackage);
16074                return;
16075            }
16076            if (mPackages.containsKey(pkgName)) {
16077                // Don't allow installation over an existing package with the same name.
16078                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16079                        + " without first uninstalling.");
16080                return;
16081            }
16082        }
16083
16084        try {
16085            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16086                    System.currentTimeMillis(), user);
16087
16088            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16089
16090            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16091                prepareAppDataAfterInstallLIF(newPackage);
16092
16093            } else {
16094                // Remove package from internal structures, but keep around any
16095                // data that might have already existed
16096                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16097                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16098            }
16099        } catch (PackageManagerException e) {
16100            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16101        }
16102
16103        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16104    }
16105
16106    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16107        try (DigestInputStream digestStream =
16108                new DigestInputStream(new FileInputStream(file), digest)) {
16109            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16110        }
16111    }
16112
16113    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16114            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16115            PackageInstalledInfo res, int installReason) {
16116        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16117
16118        final PackageParser.Package oldPackage;
16119        final PackageSetting ps;
16120        final String pkgName = pkg.packageName;
16121        final int[] allUsers;
16122        final int[] installedUsers;
16123
16124        synchronized(mPackages) {
16125            oldPackage = mPackages.get(pkgName);
16126            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16127
16128            // don't allow upgrade to target a release SDK from a pre-release SDK
16129            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16130                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16131            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16132                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16133            if (oldTargetsPreRelease
16134                    && !newTargetsPreRelease
16135                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16136                Slog.w(TAG, "Can't install package targeting released sdk");
16137                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16138                return;
16139            }
16140
16141            ps = mSettings.mPackages.get(pkgName);
16142
16143            // verify signatures are valid
16144            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16145            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16146                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16147                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16148                            "New package not signed by keys specified by upgrade-keysets: "
16149                                    + pkgName);
16150                    return;
16151                }
16152            } else {
16153
16154                // default to original signature matching
16155                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16156                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16157                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16158                            "New package has a different signature: " + pkgName);
16159                    return;
16160                }
16161            }
16162
16163            // don't allow a system upgrade unless the upgrade hash matches
16164            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16165                byte[] digestBytes = null;
16166                try {
16167                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16168                    updateDigest(digest, new File(pkg.baseCodePath));
16169                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16170                        for (String path : pkg.splitCodePaths) {
16171                            updateDigest(digest, new File(path));
16172                        }
16173                    }
16174                    digestBytes = digest.digest();
16175                } catch (NoSuchAlgorithmException | IOException e) {
16176                    res.setError(INSTALL_FAILED_INVALID_APK,
16177                            "Could not compute hash: " + pkgName);
16178                    return;
16179                }
16180                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16181                    res.setError(INSTALL_FAILED_INVALID_APK,
16182                            "New package fails restrict-update check: " + pkgName);
16183                    return;
16184                }
16185                // retain upgrade restriction
16186                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16187            }
16188
16189            // Check for shared user id changes
16190            String invalidPackageName =
16191                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16192            if (invalidPackageName != null) {
16193                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16194                        "Package " + invalidPackageName + " tried to change user "
16195                                + oldPackage.mSharedUserId);
16196                return;
16197            }
16198
16199            // check if the new package supports all of the abis which the old package supports
16200            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16201            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16202            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16203                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16204                        "Update to package " + pkgName + " doesn't support multi arch");
16205                return;
16206            }
16207
16208            // In case of rollback, remember per-user/profile install state
16209            allUsers = sUserManager.getUserIds();
16210            installedUsers = ps.queryInstalledUsers(allUsers, true);
16211
16212            // don't allow an upgrade from full to ephemeral
16213            if (isInstantApp) {
16214                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16215                    for (int currentUser : allUsers) {
16216                        if (!ps.getInstantApp(currentUser)) {
16217                            // can't downgrade from full to instant
16218                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16219                                    + " for user: " + currentUser);
16220                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16221                            return;
16222                        }
16223                    }
16224                } else if (!ps.getInstantApp(user.getIdentifier())) {
16225                    // can't downgrade from full to instant
16226                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16227                            + " for user: " + user.getIdentifier());
16228                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16229                    return;
16230                }
16231            }
16232        }
16233
16234        // Update what is removed
16235        res.removedInfo = new PackageRemovedInfo(this);
16236        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16237        res.removedInfo.removedPackage = oldPackage.packageName;
16238        res.removedInfo.installerPackageName = ps.installerPackageName;
16239        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16240        res.removedInfo.isUpdate = true;
16241        res.removedInfo.origUsers = installedUsers;
16242        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16243        for (int i = 0; i < installedUsers.length; i++) {
16244            final int userId = installedUsers[i];
16245            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16246        }
16247
16248        final int childCount = (oldPackage.childPackages != null)
16249                ? oldPackage.childPackages.size() : 0;
16250        for (int i = 0; i < childCount; i++) {
16251            boolean childPackageUpdated = false;
16252            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16253            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16254            if (res.addedChildPackages != null) {
16255                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16256                if (childRes != null) {
16257                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16258                    childRes.removedInfo.removedPackage = childPkg.packageName;
16259                    if (childPs != null) {
16260                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16261                    }
16262                    childRes.removedInfo.isUpdate = true;
16263                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16264                    childPackageUpdated = true;
16265                }
16266            }
16267            if (!childPackageUpdated) {
16268                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16269                childRemovedRes.removedPackage = childPkg.packageName;
16270                if (childPs != null) {
16271                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16272                }
16273                childRemovedRes.isUpdate = false;
16274                childRemovedRes.dataRemoved = true;
16275                synchronized (mPackages) {
16276                    if (childPs != null) {
16277                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16278                    }
16279                }
16280                if (res.removedInfo.removedChildPackages == null) {
16281                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16282                }
16283                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16284            }
16285        }
16286
16287        boolean sysPkg = (isSystemApp(oldPackage));
16288        if (sysPkg) {
16289            // Set the system/privileged/oem/vendor/product flags as needed
16290            final boolean privileged =
16291                    (oldPackage.applicationInfo.privateFlags
16292                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16293            final boolean oem =
16294                    (oldPackage.applicationInfo.privateFlags
16295                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16296            final boolean vendor =
16297                    (oldPackage.applicationInfo.privateFlags
16298                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16299            final boolean product =
16300                    (oldPackage.applicationInfo.privateFlags
16301                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16302            final @ParseFlags int systemParseFlags = parseFlags;
16303            final @ScanFlags int systemScanFlags = scanFlags
16304                    | SCAN_AS_SYSTEM
16305                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16306                    | (oem ? SCAN_AS_OEM : 0)
16307                    | (vendor ? SCAN_AS_VENDOR : 0)
16308                    | (product ? SCAN_AS_PRODUCT : 0);
16309
16310            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16311                    user, allUsers, installerPackageName, res, installReason);
16312        } else {
16313            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16314                    user, allUsers, installerPackageName, res, installReason);
16315        }
16316    }
16317
16318    @Override
16319    public List<String> getPreviousCodePaths(String packageName) {
16320        final int callingUid = Binder.getCallingUid();
16321        final List<String> result = new ArrayList<>();
16322        if (getInstantAppPackageName(callingUid) != null) {
16323            return result;
16324        }
16325        final PackageSetting ps = mSettings.mPackages.get(packageName);
16326        if (ps != null
16327                && ps.oldCodePaths != null
16328                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16329            result.addAll(ps.oldCodePaths);
16330        }
16331        return result;
16332    }
16333
16334    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16335            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16336            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16337            String installerPackageName, PackageInstalledInfo res, int installReason) {
16338        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16339                + deletedPackage);
16340
16341        String pkgName = deletedPackage.packageName;
16342        boolean deletedPkg = true;
16343        boolean addedPkg = false;
16344        boolean updatedSettings = false;
16345        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16346        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16347                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16348
16349        final long origUpdateTime = (pkg.mExtras != null)
16350                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16351
16352        // First delete the existing package while retaining the data directory
16353        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16354                res.removedInfo, true, pkg)) {
16355            // If the existing package wasn't successfully deleted
16356            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16357            deletedPkg = false;
16358        } else {
16359            // Successfully deleted the old package; proceed with replace.
16360
16361            // If deleted package lived in a container, give users a chance to
16362            // relinquish resources before killing.
16363            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16364                if (DEBUG_INSTALL) {
16365                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16366                }
16367                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16368                final ArrayList<String> pkgList = new ArrayList<String>(1);
16369                pkgList.add(deletedPackage.applicationInfo.packageName);
16370                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16371            }
16372
16373            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16374                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16375
16376            try {
16377                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16378                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16379                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16380                        installReason);
16381
16382                // Update the in-memory copy of the previous code paths.
16383                PackageSetting ps = mSettings.mPackages.get(pkgName);
16384                if (!killApp) {
16385                    if (ps.oldCodePaths == null) {
16386                        ps.oldCodePaths = new ArraySet<>();
16387                    }
16388                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16389                    if (deletedPackage.splitCodePaths != null) {
16390                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16391                    }
16392                } else {
16393                    ps.oldCodePaths = null;
16394                }
16395                if (ps.childPackageNames != null) {
16396                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16397                        final String childPkgName = ps.childPackageNames.get(i);
16398                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16399                        childPs.oldCodePaths = ps.oldCodePaths;
16400                    }
16401                }
16402                // set instant app status, but, only if it's explicitly specified
16403                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16404                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16405                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16406                prepareAppDataAfterInstallLIF(newPackage);
16407                addedPkg = true;
16408                mDexManager.notifyPackageUpdated(newPackage.packageName,
16409                        newPackage.baseCodePath, newPackage.splitCodePaths);
16410            } catch (PackageManagerException e) {
16411                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16412            }
16413        }
16414
16415        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16416            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16417
16418            // Revert all internal state mutations and added folders for the failed install
16419            if (addedPkg) {
16420                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16421                        res.removedInfo, true, null);
16422            }
16423
16424            // Restore the old package
16425            if (deletedPkg) {
16426                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16427                File restoreFile = new File(deletedPackage.codePath);
16428                // Parse old package
16429                boolean oldExternal = isExternal(deletedPackage);
16430                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16431                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16432                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16433                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16434                try {
16435                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16436                            null);
16437                } catch (PackageManagerException e) {
16438                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16439                            + e.getMessage());
16440                    return;
16441                }
16442
16443                synchronized (mPackages) {
16444                    // Ensure the installer package name up to date
16445                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16446
16447                    // Update permissions for restored package
16448                    mPermissionManager.updatePermissions(
16449                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16450                            mPermissionCallback);
16451
16452                    mSettings.writeLPr();
16453                }
16454
16455                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16456            }
16457        } else {
16458            synchronized (mPackages) {
16459                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16460                if (ps != null) {
16461                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16462                    if (res.removedInfo.removedChildPackages != null) {
16463                        final int childCount = res.removedInfo.removedChildPackages.size();
16464                        // Iterate in reverse as we may modify the collection
16465                        for (int i = childCount - 1; i >= 0; i--) {
16466                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16467                            if (res.addedChildPackages.containsKey(childPackageName)) {
16468                                res.removedInfo.removedChildPackages.removeAt(i);
16469                            } else {
16470                                PackageRemovedInfo childInfo = res.removedInfo
16471                                        .removedChildPackages.valueAt(i);
16472                                childInfo.removedForAllUsers = mPackages.get(
16473                                        childInfo.removedPackage) == null;
16474                            }
16475                        }
16476                    }
16477                }
16478            }
16479        }
16480    }
16481
16482    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16483            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16484            final @ScanFlags int scanFlags, UserHandle user,
16485            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16486            int installReason) {
16487        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16488                + ", old=" + deletedPackage);
16489
16490        final boolean disabledSystem;
16491
16492        // Remove existing system package
16493        removePackageLI(deletedPackage, true);
16494
16495        synchronized (mPackages) {
16496            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16497        }
16498        if (!disabledSystem) {
16499            // We didn't need to disable the .apk as a current system package,
16500            // which means we are replacing another update that is already
16501            // installed.  We need to make sure to delete the older one's .apk.
16502            res.removedInfo.args = createInstallArgsForExisting(0,
16503                    deletedPackage.applicationInfo.getCodePath(),
16504                    deletedPackage.applicationInfo.getResourcePath(),
16505                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16506        } else {
16507            res.removedInfo.args = null;
16508        }
16509
16510        // Successfully disabled the old package. Now proceed with re-installation
16511        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16512                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16513
16514        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16515        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16516                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16517
16518        PackageParser.Package newPackage = null;
16519        try {
16520            // Add the package to the internal data structures
16521            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16522
16523            // Set the update and install times
16524            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16525            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16526                    System.currentTimeMillis());
16527
16528            // Update the package dynamic state if succeeded
16529            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16530                // Now that the install succeeded make sure we remove data
16531                // directories for any child package the update removed.
16532                final int deletedChildCount = (deletedPackage.childPackages != null)
16533                        ? deletedPackage.childPackages.size() : 0;
16534                final int newChildCount = (newPackage.childPackages != null)
16535                        ? newPackage.childPackages.size() : 0;
16536                for (int i = 0; i < deletedChildCount; i++) {
16537                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16538                    boolean childPackageDeleted = true;
16539                    for (int j = 0; j < newChildCount; j++) {
16540                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16541                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16542                            childPackageDeleted = false;
16543                            break;
16544                        }
16545                    }
16546                    if (childPackageDeleted) {
16547                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16548                                deletedChildPkg.packageName);
16549                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16550                            PackageRemovedInfo removedChildRes = res.removedInfo
16551                                    .removedChildPackages.get(deletedChildPkg.packageName);
16552                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16553                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16554                        }
16555                    }
16556                }
16557
16558                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16559                        installReason);
16560                prepareAppDataAfterInstallLIF(newPackage);
16561
16562                mDexManager.notifyPackageUpdated(newPackage.packageName,
16563                            newPackage.baseCodePath, newPackage.splitCodePaths);
16564            }
16565        } catch (PackageManagerException e) {
16566            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16567            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16568        }
16569
16570        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16571            // Re installation failed. Restore old information
16572            // Remove new pkg information
16573            if (newPackage != null) {
16574                removeInstalledPackageLI(newPackage, true);
16575            }
16576            // Add back the old system package
16577            try {
16578                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16579            } catch (PackageManagerException e) {
16580                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16581            }
16582
16583            synchronized (mPackages) {
16584                if (disabledSystem) {
16585                    enableSystemPackageLPw(deletedPackage);
16586                }
16587
16588                // Ensure the installer package name up to date
16589                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16590
16591                // Update permissions for restored package
16592                mPermissionManager.updatePermissions(
16593                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16594                        mPermissionCallback);
16595
16596                mSettings.writeLPr();
16597            }
16598
16599            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16600                    + " after failed upgrade");
16601        }
16602    }
16603
16604    /**
16605     * Checks whether the parent or any of the child packages have a change shared
16606     * user. For a package to be a valid update the shred users of the parent and
16607     * the children should match. We may later support changing child shared users.
16608     * @param oldPkg The updated package.
16609     * @param newPkg The update package.
16610     * @return The shared user that change between the versions.
16611     */
16612    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16613            PackageParser.Package newPkg) {
16614        // Check parent shared user
16615        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16616            return newPkg.packageName;
16617        }
16618        // Check child shared users
16619        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16620        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16621        for (int i = 0; i < newChildCount; i++) {
16622            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16623            // If this child was present, did it have the same shared user?
16624            for (int j = 0; j < oldChildCount; j++) {
16625                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16626                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16627                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16628                    return newChildPkg.packageName;
16629                }
16630            }
16631        }
16632        return null;
16633    }
16634
16635    private void removeNativeBinariesLI(PackageSetting ps) {
16636        // Remove the lib path for the parent package
16637        if (ps != null) {
16638            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16639            // Remove the lib path for the child packages
16640            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16641            for (int i = 0; i < childCount; i++) {
16642                PackageSetting childPs = null;
16643                synchronized (mPackages) {
16644                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16645                }
16646                if (childPs != null) {
16647                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16648                            .legacyNativeLibraryPathString);
16649                }
16650            }
16651        }
16652    }
16653
16654    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16655        // Enable the parent package
16656        mSettings.enableSystemPackageLPw(pkg.packageName);
16657        // Enable the child packages
16658        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16659        for (int i = 0; i < childCount; i++) {
16660            PackageParser.Package childPkg = pkg.childPackages.get(i);
16661            mSettings.enableSystemPackageLPw(childPkg.packageName);
16662        }
16663    }
16664
16665    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16666            PackageParser.Package newPkg) {
16667        // Disable the parent package (parent always replaced)
16668        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16669        // Disable the child packages
16670        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16671        for (int i = 0; i < childCount; i++) {
16672            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16673            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16674            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16675        }
16676        return disabled;
16677    }
16678
16679    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16680            String installerPackageName) {
16681        // Enable the parent package
16682        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16683        // Enable the child packages
16684        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16685        for (int i = 0; i < childCount; i++) {
16686            PackageParser.Package childPkg = pkg.childPackages.get(i);
16687            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16688        }
16689    }
16690
16691    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16692            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16693        // Update the parent package setting
16694        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16695                res, user, installReason);
16696        // Update the child packages setting
16697        final int childCount = (newPackage.childPackages != null)
16698                ? newPackage.childPackages.size() : 0;
16699        for (int i = 0; i < childCount; i++) {
16700            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16701            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16702            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16703                    childRes.origUsers, childRes, user, installReason);
16704        }
16705    }
16706
16707    private void updateSettingsInternalLI(PackageParser.Package pkg,
16708            String installerPackageName, int[] allUsers, int[] installedForUsers,
16709            PackageInstalledInfo res, UserHandle user, int installReason) {
16710        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16711
16712        final String pkgName = pkg.packageName;
16713
16714        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16715        synchronized (mPackages) {
16716// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16717            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16718                    mPermissionCallback);
16719            // For system-bundled packages, we assume that installing an upgraded version
16720            // of the package implies that the user actually wants to run that new code,
16721            // so we enable the package.
16722            PackageSetting ps = mSettings.mPackages.get(pkgName);
16723            final int userId = user.getIdentifier();
16724            if (ps != null) {
16725                if (isSystemApp(pkg)) {
16726                    if (DEBUG_INSTALL) {
16727                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16728                    }
16729                    // Enable system package for requested users
16730                    if (res.origUsers != null) {
16731                        for (int origUserId : res.origUsers) {
16732                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16733                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16734                                        origUserId, installerPackageName);
16735                            }
16736                        }
16737                    }
16738                    // Also convey the prior install/uninstall state
16739                    if (allUsers != null && installedForUsers != null) {
16740                        for (int currentUserId : allUsers) {
16741                            final boolean installed = ArrayUtils.contains(
16742                                    installedForUsers, currentUserId);
16743                            if (DEBUG_INSTALL) {
16744                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16745                            }
16746                            ps.setInstalled(installed, currentUserId);
16747                        }
16748                        // these install state changes will be persisted in the
16749                        // upcoming call to mSettings.writeLPr().
16750                    }
16751                }
16752                // It's implied that when a user requests installation, they want the app to be
16753                // installed and enabled.
16754                if (userId != UserHandle.USER_ALL) {
16755                    ps.setInstalled(true, userId);
16756                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16757                } else {
16758                    for (int currentUserId : sUserManager.getUserIds()) {
16759                        ps.setInstalled(true, currentUserId);
16760                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16761                                installerPackageName);
16762                    }
16763                }
16764
16765                // When replacing an existing package, preserve the original install reason for all
16766                // users that had the package installed before.
16767                final Set<Integer> previousUserIds = new ArraySet<>();
16768                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16769                    final int installReasonCount = res.removedInfo.installReasons.size();
16770                    for (int i = 0; i < installReasonCount; i++) {
16771                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16772                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16773                        ps.setInstallReason(previousInstallReason, previousUserId);
16774                        previousUserIds.add(previousUserId);
16775                    }
16776                }
16777
16778                // Set install reason for users that are having the package newly installed.
16779                if (userId == UserHandle.USER_ALL) {
16780                    for (int currentUserId : sUserManager.getUserIds()) {
16781                        if (!previousUserIds.contains(currentUserId)) {
16782                            ps.setInstallReason(installReason, currentUserId);
16783                        }
16784                    }
16785                } else if (!previousUserIds.contains(userId)) {
16786                    ps.setInstallReason(installReason, userId);
16787                }
16788                mSettings.writeKernelMappingLPr(ps);
16789            }
16790            res.name = pkgName;
16791            res.uid = pkg.applicationInfo.uid;
16792            res.pkg = pkg;
16793            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16794            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16795            //to update install status
16796            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16797            mSettings.writeLPr();
16798            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16799        }
16800
16801        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16802    }
16803
16804    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16805        try {
16806            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16807            installPackageLI(args, res);
16808        } finally {
16809            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16810        }
16811    }
16812
16813    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16814        final int installFlags = args.installFlags;
16815        final String installerPackageName = args.installerPackageName;
16816        final String volumeUuid = args.volumeUuid;
16817        final File tmpPackageFile = new File(args.getCodePath());
16818        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16819        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16820                || (args.volumeUuid != null));
16821        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16822        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16823        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16824        final boolean virtualPreload =
16825                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16826        boolean replace = false;
16827        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16828        if (args.move != null) {
16829            // moving a complete application; perform an initial scan on the new install location
16830            scanFlags |= SCAN_INITIAL;
16831        }
16832        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16833            scanFlags |= SCAN_DONT_KILL_APP;
16834        }
16835        if (instantApp) {
16836            scanFlags |= SCAN_AS_INSTANT_APP;
16837        }
16838        if (fullApp) {
16839            scanFlags |= SCAN_AS_FULL_APP;
16840        }
16841        if (virtualPreload) {
16842            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16843        }
16844
16845        // Result object to be returned
16846        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16847        res.installerPackageName = installerPackageName;
16848
16849        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16850
16851        // Sanity check
16852        if (instantApp && (forwardLocked || onExternal)) {
16853            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16854                    + " external=" + onExternal);
16855            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16856            return;
16857        }
16858
16859        // Retrieve PackageSettings and parse package
16860        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16861                | PackageParser.PARSE_ENFORCE_CODE
16862                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16863                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16864                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16865        PackageParser pp = new PackageParser();
16866        pp.setSeparateProcesses(mSeparateProcesses);
16867        pp.setDisplayMetrics(mMetrics);
16868        pp.setCallback(mPackageParserCallback);
16869
16870        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16871        final PackageParser.Package pkg;
16872        try {
16873            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16874            DexMetadataHelper.validatePackageDexMetadata(pkg);
16875        } catch (PackageParserException e) {
16876            res.setError("Failed parse during installPackageLI", e);
16877            return;
16878        } finally {
16879            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16880        }
16881
16882        // Instant apps have several additional install-time checks.
16883        if (instantApp) {
16884            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16885                Slog.w(TAG,
16886                        "Instant app package " + pkg.packageName + " does not target at least O");
16887                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16888                        "Instant app package must target at least O");
16889                return;
16890            }
16891            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16892                Slog.w(TAG, "Instant app package " + pkg.packageName
16893                        + " does not target targetSandboxVersion 2");
16894                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16895                        "Instant app package must use targetSandboxVersion 2");
16896                return;
16897            }
16898            if (pkg.mSharedUserId != null) {
16899                Slog.w(TAG, "Instant app package " + pkg.packageName
16900                        + " may not declare sharedUserId.");
16901                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16902                        "Instant app package may not declare a sharedUserId");
16903                return;
16904            }
16905        }
16906
16907        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16908            // Static shared libraries have synthetic package names
16909            renameStaticSharedLibraryPackage(pkg);
16910
16911            // No static shared libs on external storage
16912            if (onExternal) {
16913                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16914                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16915                        "Packages declaring static-shared libs cannot be updated");
16916                return;
16917            }
16918        }
16919
16920        // If we are installing a clustered package add results for the children
16921        if (pkg.childPackages != null) {
16922            synchronized (mPackages) {
16923                final int childCount = pkg.childPackages.size();
16924                for (int i = 0; i < childCount; i++) {
16925                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16926                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16927                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16928                    childRes.pkg = childPkg;
16929                    childRes.name = childPkg.packageName;
16930                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16931                    if (childPs != null) {
16932                        childRes.origUsers = childPs.queryInstalledUsers(
16933                                sUserManager.getUserIds(), true);
16934                    }
16935                    if ((mPackages.containsKey(childPkg.packageName))) {
16936                        childRes.removedInfo = new PackageRemovedInfo(this);
16937                        childRes.removedInfo.removedPackage = childPkg.packageName;
16938                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16939                    }
16940                    if (res.addedChildPackages == null) {
16941                        res.addedChildPackages = new ArrayMap<>();
16942                    }
16943                    res.addedChildPackages.put(childPkg.packageName, childRes);
16944                }
16945            }
16946        }
16947
16948        // If package doesn't declare API override, mark that we have an install
16949        // time CPU ABI override.
16950        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16951            pkg.cpuAbiOverride = args.abiOverride;
16952        }
16953
16954        String pkgName = res.name = pkg.packageName;
16955        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16956            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16957                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16958                return;
16959            }
16960        }
16961
16962        try {
16963            // either use what we've been given or parse directly from the APK
16964            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16965                pkg.setSigningDetails(args.signingDetails);
16966            } else {
16967                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16968            }
16969        } catch (PackageParserException e) {
16970            res.setError("Failed collect during installPackageLI", e);
16971            return;
16972        }
16973
16974        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16975                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16976            Slog.w(TAG, "Instant app package " + pkg.packageName
16977                    + " is not signed with at least APK Signature Scheme v2");
16978            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16979                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16980            return;
16981        }
16982
16983        // Get rid of all references to package scan path via parser.
16984        pp = null;
16985        String oldCodePath = null;
16986        boolean systemApp = false;
16987        synchronized (mPackages) {
16988            // Check if installing already existing package
16989            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16990                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16991                if (pkg.mOriginalPackages != null
16992                        && pkg.mOriginalPackages.contains(oldName)
16993                        && mPackages.containsKey(oldName)) {
16994                    // This package is derived from an original package,
16995                    // and this device has been updating from that original
16996                    // name.  We must continue using the original name, so
16997                    // rename the new package here.
16998                    pkg.setPackageName(oldName);
16999                    pkgName = pkg.packageName;
17000                    replace = true;
17001                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17002                            + oldName + " pkgName=" + pkgName);
17003                } else if (mPackages.containsKey(pkgName)) {
17004                    // This package, under its official name, already exists
17005                    // on the device; we should replace it.
17006                    replace = true;
17007                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17008                }
17009
17010                // Child packages are installed through the parent package
17011                if (pkg.parentPackage != null) {
17012                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17013                            "Package " + pkg.packageName + " is child of package "
17014                                    + pkg.parentPackage.parentPackage + ". Child packages "
17015                                    + "can be updated only through the parent package.");
17016                    return;
17017                }
17018
17019                if (replace) {
17020                    // Prevent apps opting out from runtime permissions
17021                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17022                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17023                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17024                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17025                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17026                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17027                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17028                                        + " doesn't support runtime permissions but the old"
17029                                        + " target SDK " + oldTargetSdk + " does.");
17030                        return;
17031                    }
17032                    // Prevent persistent apps from being updated
17033                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17034                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17035                                "Package " + oldPackage.packageName + " is a persistent app. "
17036                                        + "Persistent apps are not updateable.");
17037                        return;
17038                    }
17039                    // Prevent apps from downgrading their targetSandbox.
17040                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17041                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17042                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17043                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17044                                "Package " + pkg.packageName + " new target sandbox "
17045                                + newTargetSandbox + " is incompatible with the previous value of"
17046                                + oldTargetSandbox + ".");
17047                        return;
17048                    }
17049
17050                    // Prevent installing of child packages
17051                    if (oldPackage.parentPackage != null) {
17052                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17053                                "Package " + pkg.packageName + " is child of package "
17054                                        + oldPackage.parentPackage + ". Child packages "
17055                                        + "can be updated only through the parent package.");
17056                        return;
17057                    }
17058                }
17059            }
17060
17061            PackageSetting ps = mSettings.mPackages.get(pkgName);
17062            if (ps != null) {
17063                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17064
17065                // Static shared libs have same package with different versions where
17066                // we internally use a synthetic package name to allow multiple versions
17067                // of the same package, therefore we need to compare signatures against
17068                // the package setting for the latest library version.
17069                PackageSetting signatureCheckPs = ps;
17070                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17071                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17072                    if (libraryEntry != null) {
17073                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17074                    }
17075                }
17076
17077                // Quick sanity check that we're signed correctly if updating;
17078                // we'll check this again later when scanning, but we want to
17079                // bail early here before tripping over redefined permissions.
17080                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17081                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17082                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17083                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17084                                + pkg.packageName + " upgrade keys do not match the "
17085                                + "previously installed version");
17086                        return;
17087                    }
17088                } else {
17089                    try {
17090                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17091                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17092                        // We don't care about disabledPkgSetting on install for now.
17093                        final boolean compatMatch = verifySignatures(
17094                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17095                                compareRecover);
17096                        // The new KeySets will be re-added later in the scanning process.
17097                        if (compatMatch) {
17098                            synchronized (mPackages) {
17099                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17100                            }
17101                        }
17102                    } catch (PackageManagerException e) {
17103                        res.setError(e.error, e.getMessage());
17104                        return;
17105                    }
17106                }
17107
17108                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17109                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17110                    systemApp = (ps.pkg.applicationInfo.flags &
17111                            ApplicationInfo.FLAG_SYSTEM) != 0;
17112                }
17113                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17114            }
17115
17116            int N = pkg.permissions.size();
17117            for (int i = N-1; i >= 0; i--) {
17118                final PackageParser.Permission perm = pkg.permissions.get(i);
17119                final BasePermission bp =
17120                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17121
17122                // Don't allow anyone but the system to define ephemeral permissions.
17123                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17124                        && !systemApp) {
17125                    Slog.w(TAG, "Non-System package " + pkg.packageName
17126                            + " attempting to delcare ephemeral permission "
17127                            + perm.info.name + "; Removing ephemeral.");
17128                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17129                }
17130
17131                // Check whether the newly-scanned package wants to define an already-defined perm
17132                if (bp != null) {
17133                    // If the defining package is signed with our cert, it's okay.  This
17134                    // also includes the "updating the same package" case, of course.
17135                    // "updating same package" could also involve key-rotation.
17136                    final boolean sigsOk;
17137                    final String sourcePackageName = bp.getSourcePackageName();
17138                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17139                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17140                    if (sourcePackageName.equals(pkg.packageName)
17141                            && (ksms.shouldCheckUpgradeKeySetLocked(
17142                                    sourcePackageSetting, scanFlags))) {
17143                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17144                    } else {
17145
17146                        // in the event of signing certificate rotation, we need to see if the
17147                        // package's certificate has rotated from the current one, or if it is an
17148                        // older certificate with which the current is ok with sharing permissions
17149                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17150                                        pkg.mSigningDetails,
17151                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17152                            sigsOk = true;
17153                        } else if (pkg.mSigningDetails.checkCapability(
17154                                        sourcePackageSetting.signatures.mSigningDetails,
17155                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17156
17157                            // the scanned package checks out, has signing certificate rotation
17158                            // history, and is newer; bring it over
17159                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17160                            sigsOk = true;
17161                        } else {
17162                            sigsOk = false;
17163                        }
17164                    }
17165                    if (!sigsOk) {
17166                        // If the owning package is the system itself, we log but allow
17167                        // install to proceed; we fail the install on all other permission
17168                        // redefinitions.
17169                        if (!sourcePackageName.equals("android")) {
17170                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17171                                    + pkg.packageName + " attempting to redeclare permission "
17172                                    + perm.info.name + " already owned by " + sourcePackageName);
17173                            res.origPermission = perm.info.name;
17174                            res.origPackage = sourcePackageName;
17175                            return;
17176                        } else {
17177                            Slog.w(TAG, "Package " + pkg.packageName
17178                                    + " attempting to redeclare system permission "
17179                                    + perm.info.name + "; ignoring new declaration");
17180                            pkg.permissions.remove(i);
17181                        }
17182                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17183                        // Prevent apps to change protection level to dangerous from any other
17184                        // type as this would allow a privilege escalation where an app adds a
17185                        // normal/signature permission in other app's group and later redefines
17186                        // it as dangerous leading to the group auto-grant.
17187                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17188                                == PermissionInfo.PROTECTION_DANGEROUS) {
17189                            if (bp != null && !bp.isRuntime()) {
17190                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17191                                        + "non-runtime permission " + perm.info.name
17192                                        + " to runtime; keeping old protection level");
17193                                perm.info.protectionLevel = bp.getProtectionLevel();
17194                            }
17195                        }
17196                    }
17197                }
17198            }
17199        }
17200
17201        if (systemApp) {
17202            if (onExternal) {
17203                // Abort update; system app can't be replaced with app on sdcard
17204                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17205                        "Cannot install updates to system apps on sdcard");
17206                return;
17207            } else if (instantApp) {
17208                // Abort update; system app can't be replaced with an instant app
17209                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17210                        "Cannot update a system app with an instant app");
17211                return;
17212            }
17213        }
17214
17215        if (args.move != null) {
17216            // We did an in-place move, so dex is ready to roll
17217            scanFlags |= SCAN_NO_DEX;
17218            scanFlags |= SCAN_MOVE;
17219
17220            synchronized (mPackages) {
17221                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17222                if (ps == null) {
17223                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17224                            "Missing settings for moved package " + pkgName);
17225                }
17226
17227                // We moved the entire application as-is, so bring over the
17228                // previously derived ABI information.
17229                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17230                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17231            }
17232
17233        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17234            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17235            scanFlags |= SCAN_NO_DEX;
17236
17237            try {
17238                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17239                    args.abiOverride : pkg.cpuAbiOverride);
17240                final boolean extractNativeLibs = !pkg.isLibrary();
17241                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17242            } catch (PackageManagerException pme) {
17243                Slog.e(TAG, "Error deriving application ABI", pme);
17244                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17245                return;
17246            }
17247
17248            // Shared libraries for the package need to be updated.
17249            synchronized (mPackages) {
17250                try {
17251                    updateSharedLibrariesLPr(pkg, null);
17252                } catch (PackageManagerException e) {
17253                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17254                }
17255            }
17256        }
17257
17258        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17259            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17260            return;
17261        }
17262
17263        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17264            String apkPath = null;
17265            synchronized (mPackages) {
17266                // Note that if the attacker managed to skip verify setup, for example by tampering
17267                // with the package settings, upon reboot we will do full apk verification when
17268                // verity is not detected.
17269                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17270                if (ps != null && ps.isPrivileged()) {
17271                    apkPath = pkg.baseCodePath;
17272                }
17273            }
17274
17275            if (apkPath != null) {
17276                final VerityUtils.SetupResult result =
17277                        VerityUtils.generateApkVeritySetupData(apkPath);
17278                if (result.isOk()) {
17279                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17280                    FileDescriptor fd = result.getUnownedFileDescriptor();
17281                    try {
17282                        mInstaller.installApkVerity(apkPath, fd);
17283                    } catch (InstallerException e) {
17284                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17285                                "Failed to set up verity: " + e);
17286                        return;
17287                    } finally {
17288                        IoUtils.closeQuietly(fd);
17289                    }
17290                } else if (result.isFailed()) {
17291                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17292                    return;
17293                } else {
17294                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17295                    // reboot.
17296                }
17297            }
17298        }
17299
17300        if (!instantApp) {
17301            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17302        } else {
17303            if (DEBUG_DOMAIN_VERIFICATION) {
17304                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17305            }
17306        }
17307
17308        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17309                "installPackageLI")) {
17310            if (replace) {
17311                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17312                    // Static libs have a synthetic package name containing the version
17313                    // and cannot be updated as an update would get a new package name,
17314                    // unless this is the exact same version code which is useful for
17315                    // development.
17316                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17317                    if (existingPkg != null &&
17318                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17319                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17320                                + "static-shared libs cannot be updated");
17321                        return;
17322                    }
17323                }
17324                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17325                        installerPackageName, res, args.installReason);
17326            } else {
17327                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17328                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17329            }
17330        }
17331
17332        // Prepare the application profiles for the new code paths.
17333        // This needs to be done before invoking dexopt so that any install-time profile
17334        // can be used for optimizations.
17335        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17336
17337        // Check whether we need to dexopt the app.
17338        //
17339        // NOTE: it is IMPORTANT to call dexopt:
17340        //   - after doRename which will sync the package data from PackageParser.Package and its
17341        //     corresponding ApplicationInfo.
17342        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17343        //     uid of the application (pkg.applicationInfo.uid).
17344        //     This update happens in place!
17345        //
17346        // We only need to dexopt if the package meets ALL of the following conditions:
17347        //   1) it is not forward locked.
17348        //   2) it is not on on an external ASEC container.
17349        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17350        //
17351        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17352        // complete, so we skip this step during installation. Instead, we'll take extra time
17353        // the first time the instant app starts. It's preferred to do it this way to provide
17354        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17355        // middle of running an instant app. The default behaviour can be overridden
17356        // via gservices.
17357        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17358                && !forwardLocked
17359                && !pkg.applicationInfo.isExternalAsec()
17360                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17361                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17362
17363        if (performDexopt) {
17364            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17365            // Do not run PackageDexOptimizer through the local performDexOpt
17366            // method because `pkg` may not be in `mPackages` yet.
17367            //
17368            // Also, don't fail application installs if the dexopt step fails.
17369            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17370                    REASON_INSTALL,
17371                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17372                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17373            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17374                    null /* instructionSets */,
17375                    getOrCreateCompilerPackageStats(pkg),
17376                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17377                    dexoptOptions);
17378            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17379        }
17380
17381        // Notify BackgroundDexOptService that the package has been changed.
17382        // If this is an update of a package which used to fail to compile,
17383        // BackgroundDexOptService will remove it from its blacklist.
17384        // TODO: Layering violation
17385        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17386
17387        synchronized (mPackages) {
17388            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17389            if (ps != null) {
17390                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17391                ps.setUpdateAvailable(false /*updateAvailable*/);
17392            }
17393
17394            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17395            for (int i = 0; i < childCount; i++) {
17396                PackageParser.Package childPkg = pkg.childPackages.get(i);
17397                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17398                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17399                if (childPs != null) {
17400                    childRes.newUsers = childPs.queryInstalledUsers(
17401                            sUserManager.getUserIds(), true);
17402                }
17403            }
17404
17405            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17406                updateSequenceNumberLP(ps, res.newUsers);
17407                updateInstantAppInstallerLocked(pkgName);
17408            }
17409        }
17410    }
17411
17412    private void startIntentFilterVerifications(int userId, boolean replacing,
17413            PackageParser.Package pkg) {
17414        if (mIntentFilterVerifierComponent == null) {
17415            Slog.w(TAG, "No IntentFilter verification will not be done as "
17416                    + "there is no IntentFilterVerifier available!");
17417            return;
17418        }
17419
17420        final int verifierUid = getPackageUid(
17421                mIntentFilterVerifierComponent.getPackageName(),
17422                MATCH_DEBUG_TRIAGED_MISSING,
17423                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17424
17425        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17426        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17427        mHandler.sendMessage(msg);
17428
17429        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17430        for (int i = 0; i < childCount; i++) {
17431            PackageParser.Package childPkg = pkg.childPackages.get(i);
17432            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17433            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17434            mHandler.sendMessage(msg);
17435        }
17436    }
17437
17438    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17439            PackageParser.Package pkg) {
17440        int size = pkg.activities.size();
17441        if (size == 0) {
17442            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17443                    "No activity, so no need to verify any IntentFilter!");
17444            return;
17445        }
17446
17447        final boolean hasDomainURLs = hasDomainURLs(pkg);
17448        if (!hasDomainURLs) {
17449            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17450                    "No domain URLs, so no need to verify any IntentFilter!");
17451            return;
17452        }
17453
17454        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17455                + " if any IntentFilter from the " + size
17456                + " Activities needs verification ...");
17457
17458        int count = 0;
17459        final String packageName = pkg.packageName;
17460
17461        synchronized (mPackages) {
17462            // If this is a new install and we see that we've already run verification for this
17463            // package, we have nothing to do: it means the state was restored from backup.
17464            if (!replacing) {
17465                IntentFilterVerificationInfo ivi =
17466                        mSettings.getIntentFilterVerificationLPr(packageName);
17467                if (ivi != null) {
17468                    if (DEBUG_DOMAIN_VERIFICATION) {
17469                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17470                                + ivi.getStatusString());
17471                    }
17472                    return;
17473                }
17474            }
17475
17476            // If any filters need to be verified, then all need to be.
17477            boolean needToVerify = false;
17478            for (PackageParser.Activity a : pkg.activities) {
17479                for (ActivityIntentInfo filter : a.intents) {
17480                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17481                        if (DEBUG_DOMAIN_VERIFICATION) {
17482                            Slog.d(TAG,
17483                                    "Intent filter needs verification, so processing all filters");
17484                        }
17485                        needToVerify = true;
17486                        break;
17487                    }
17488                }
17489            }
17490
17491            if (needToVerify) {
17492                final int verificationId = mIntentFilterVerificationToken++;
17493                for (PackageParser.Activity a : pkg.activities) {
17494                    for (ActivityIntentInfo filter : a.intents) {
17495                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17496                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17497                                    "Verification needed for IntentFilter:" + filter.toString());
17498                            mIntentFilterVerifier.addOneIntentFilterVerification(
17499                                    verifierUid, userId, verificationId, filter, packageName);
17500                            count++;
17501                        }
17502                    }
17503                }
17504            }
17505        }
17506
17507        if (count > 0) {
17508            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17509                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17510                    +  " for userId:" + userId);
17511            mIntentFilterVerifier.startVerifications(userId);
17512        } else {
17513            if (DEBUG_DOMAIN_VERIFICATION) {
17514                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17515            }
17516        }
17517    }
17518
17519    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17520        final ComponentName cn  = filter.activity.getComponentName();
17521        final String packageName = cn.getPackageName();
17522
17523        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17524                packageName);
17525        if (ivi == null) {
17526            return true;
17527        }
17528        int status = ivi.getStatus();
17529        switch (status) {
17530            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17531            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17532                return true;
17533
17534            default:
17535                // Nothing to do
17536                return false;
17537        }
17538    }
17539
17540    private static boolean isMultiArch(ApplicationInfo info) {
17541        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17542    }
17543
17544    private static boolean isExternal(PackageParser.Package pkg) {
17545        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17546    }
17547
17548    private static boolean isExternal(PackageSetting ps) {
17549        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17550    }
17551
17552    private static boolean isSystemApp(PackageParser.Package pkg) {
17553        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17554    }
17555
17556    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17557        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17558    }
17559
17560    private static boolean isOemApp(PackageParser.Package pkg) {
17561        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17562    }
17563
17564    private static boolean isVendorApp(PackageParser.Package pkg) {
17565        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17566    }
17567
17568    private static boolean isProductApp(PackageParser.Package pkg) {
17569        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17570    }
17571
17572    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17573        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17574    }
17575
17576    private static boolean isSystemApp(PackageSetting ps) {
17577        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17578    }
17579
17580    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17581        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17582    }
17583
17584    private int packageFlagsToInstallFlags(PackageSetting ps) {
17585        int installFlags = 0;
17586        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17587            // This existing package was an external ASEC install when we have
17588            // the external flag without a UUID
17589            installFlags |= PackageManager.INSTALL_EXTERNAL;
17590        }
17591        if (ps.isForwardLocked()) {
17592            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17593        }
17594        return installFlags;
17595    }
17596
17597    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17598        if (isExternal(pkg)) {
17599            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17600                return mSettings.getExternalVersion();
17601            } else {
17602                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17603            }
17604        } else {
17605            return mSettings.getInternalVersion();
17606        }
17607    }
17608
17609    private void deleteTempPackageFiles() {
17610        final FilenameFilter filter = new FilenameFilter() {
17611            public boolean accept(File dir, String name) {
17612                return name.startsWith("vmdl") && name.endsWith(".tmp");
17613            }
17614        };
17615        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17616            file.delete();
17617        }
17618    }
17619
17620    @Override
17621    public void deletePackageAsUser(String packageName, int versionCode,
17622            IPackageDeleteObserver observer, int userId, int flags) {
17623        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17624                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17625    }
17626
17627    @Override
17628    public void deletePackageVersioned(VersionedPackage versionedPackage,
17629            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17630        final int callingUid = Binder.getCallingUid();
17631        mContext.enforceCallingOrSelfPermission(
17632                android.Manifest.permission.DELETE_PACKAGES, null);
17633        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17634        Preconditions.checkNotNull(versionedPackage);
17635        Preconditions.checkNotNull(observer);
17636        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17637                PackageManager.VERSION_CODE_HIGHEST,
17638                Long.MAX_VALUE, "versionCode must be >= -1");
17639
17640        final String packageName = versionedPackage.getPackageName();
17641        final long versionCode = versionedPackage.getLongVersionCode();
17642        final String internalPackageName;
17643        synchronized (mPackages) {
17644            // Normalize package name to handle renamed packages and static libs
17645            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17646        }
17647
17648        final int uid = Binder.getCallingUid();
17649        if (!isOrphaned(internalPackageName)
17650                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17651            try {
17652                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17653                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17654                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17655                observer.onUserActionRequired(intent);
17656            } catch (RemoteException re) {
17657            }
17658            return;
17659        }
17660        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17661        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17662        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17663            mContext.enforceCallingOrSelfPermission(
17664                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17665                    "deletePackage for user " + userId);
17666        }
17667
17668        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17669            try {
17670                observer.onPackageDeleted(packageName,
17671                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17672            } catch (RemoteException re) {
17673            }
17674            return;
17675        }
17676
17677        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17678            try {
17679                observer.onPackageDeleted(packageName,
17680                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17681            } catch (RemoteException re) {
17682            }
17683            return;
17684        }
17685
17686        if (DEBUG_REMOVE) {
17687            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17688                    + " deleteAllUsers: " + deleteAllUsers + " version="
17689                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17690                    ? "VERSION_CODE_HIGHEST" : versionCode));
17691        }
17692        // Queue up an async operation since the package deletion may take a little while.
17693        mHandler.post(new Runnable() {
17694            public void run() {
17695                mHandler.removeCallbacks(this);
17696                int returnCode;
17697                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17698                boolean doDeletePackage = true;
17699                if (ps != null) {
17700                    final boolean targetIsInstantApp =
17701                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17702                    doDeletePackage = !targetIsInstantApp
17703                            || canViewInstantApps;
17704                }
17705                if (doDeletePackage) {
17706                    if (!deleteAllUsers) {
17707                        returnCode = deletePackageX(internalPackageName, versionCode,
17708                                userId, deleteFlags);
17709                    } else {
17710                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17711                                internalPackageName, users);
17712                        // If nobody is blocking uninstall, proceed with delete for all users
17713                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17714                            returnCode = deletePackageX(internalPackageName, versionCode,
17715                                    userId, deleteFlags);
17716                        } else {
17717                            // Otherwise uninstall individually for users with blockUninstalls=false
17718                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17719                            for (int userId : users) {
17720                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17721                                    returnCode = deletePackageX(internalPackageName, versionCode,
17722                                            userId, userFlags);
17723                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17724                                        Slog.w(TAG, "Package delete failed for user " + userId
17725                                                + ", returnCode " + returnCode);
17726                                    }
17727                                }
17728                            }
17729                            // The app has only been marked uninstalled for certain users.
17730                            // We still need to report that delete was blocked
17731                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17732                        }
17733                    }
17734                } else {
17735                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17736                }
17737                try {
17738                    observer.onPackageDeleted(packageName, returnCode, null);
17739                } catch (RemoteException e) {
17740                    Log.i(TAG, "Observer no longer exists.");
17741                } //end catch
17742            } //end run
17743        });
17744    }
17745
17746    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17747        if (pkg.staticSharedLibName != null) {
17748            return pkg.manifestPackageName;
17749        }
17750        return pkg.packageName;
17751    }
17752
17753    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17754        // Handle renamed packages
17755        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17756        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17757
17758        // Is this a static library?
17759        LongSparseArray<SharedLibraryEntry> versionedLib =
17760                mStaticLibsByDeclaringPackage.get(packageName);
17761        if (versionedLib == null || versionedLib.size() <= 0) {
17762            return packageName;
17763        }
17764
17765        // Figure out which lib versions the caller can see
17766        LongSparseLongArray versionsCallerCanSee = null;
17767        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17768        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17769                && callingAppId != Process.ROOT_UID) {
17770            versionsCallerCanSee = new LongSparseLongArray();
17771            String libName = versionedLib.valueAt(0).info.getName();
17772            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17773            if (uidPackages != null) {
17774                for (String uidPackage : uidPackages) {
17775                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17776                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17777                    if (libIdx >= 0) {
17778                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17779                        versionsCallerCanSee.append(libVersion, libVersion);
17780                    }
17781                }
17782            }
17783        }
17784
17785        // Caller can see nothing - done
17786        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17787            return packageName;
17788        }
17789
17790        // Find the version the caller can see and the app version code
17791        SharedLibraryEntry highestVersion = null;
17792        final int versionCount = versionedLib.size();
17793        for (int i = 0; i < versionCount; i++) {
17794            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17795            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17796                    libEntry.info.getLongVersion()) < 0) {
17797                continue;
17798            }
17799            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17800            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17801                if (libVersionCode == versionCode) {
17802                    return libEntry.apk;
17803                }
17804            } else if (highestVersion == null) {
17805                highestVersion = libEntry;
17806            } else if (libVersionCode  > highestVersion.info
17807                    .getDeclaringPackage().getLongVersionCode()) {
17808                highestVersion = libEntry;
17809            }
17810        }
17811
17812        if (highestVersion != null) {
17813            return highestVersion.apk;
17814        }
17815
17816        return packageName;
17817    }
17818
17819    boolean isCallerVerifier(int callingUid) {
17820        final int callingUserId = UserHandle.getUserId(callingUid);
17821        return mRequiredVerifierPackage != null &&
17822                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17823    }
17824
17825    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17826        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17827              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17828            return true;
17829        }
17830        final int callingUserId = UserHandle.getUserId(callingUid);
17831        // If the caller installed the pkgName, then allow it to silently uninstall.
17832        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17833            return true;
17834        }
17835
17836        // Allow package verifier to silently uninstall.
17837        if (mRequiredVerifierPackage != null &&
17838                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17839            return true;
17840        }
17841
17842        // Allow package uninstaller to silently uninstall.
17843        if (mRequiredUninstallerPackage != null &&
17844                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17845            return true;
17846        }
17847
17848        // Allow storage manager to silently uninstall.
17849        if (mStorageManagerPackage != null &&
17850                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17851            return true;
17852        }
17853
17854        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17855        // uninstall for device owner provisioning.
17856        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17857                == PERMISSION_GRANTED) {
17858            return true;
17859        }
17860
17861        return false;
17862    }
17863
17864    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17865        int[] result = EMPTY_INT_ARRAY;
17866        for (int userId : userIds) {
17867            if (getBlockUninstallForUser(packageName, userId)) {
17868                result = ArrayUtils.appendInt(result, userId);
17869            }
17870        }
17871        return result;
17872    }
17873
17874    @Override
17875    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17876        final int callingUid = Binder.getCallingUid();
17877        if (getInstantAppPackageName(callingUid) != null
17878                && !isCallerSameApp(packageName, callingUid)) {
17879            return false;
17880        }
17881        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17882    }
17883
17884    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17885        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17886                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17887        try {
17888            if (dpm != null) {
17889                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17890                        /* callingUserOnly =*/ false);
17891                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17892                        : deviceOwnerComponentName.getPackageName();
17893                // Does the package contains the device owner?
17894                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17895                // this check is probably not needed, since DO should be registered as a device
17896                // admin on some user too. (Original bug for this: b/17657954)
17897                if (packageName.equals(deviceOwnerPackageName)) {
17898                    return true;
17899                }
17900                // Does it contain a device admin for any user?
17901                int[] users;
17902                if (userId == UserHandle.USER_ALL) {
17903                    users = sUserManager.getUserIds();
17904                } else {
17905                    users = new int[]{userId};
17906                }
17907                for (int i = 0; i < users.length; ++i) {
17908                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17909                        return true;
17910                    }
17911                }
17912            }
17913        } catch (RemoteException e) {
17914        }
17915        return false;
17916    }
17917
17918    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17919        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17920    }
17921
17922    /**
17923     *  This method is an internal method that could be get invoked either
17924     *  to delete an installed package or to clean up a failed installation.
17925     *  After deleting an installed package, a broadcast is sent to notify any
17926     *  listeners that the package has been removed. For cleaning up a failed
17927     *  installation, the broadcast is not necessary since the package's
17928     *  installation wouldn't have sent the initial broadcast either
17929     *  The key steps in deleting a package are
17930     *  deleting the package information in internal structures like mPackages,
17931     *  deleting the packages base directories through installd
17932     *  updating mSettings to reflect current status
17933     *  persisting settings for later use
17934     *  sending a broadcast if necessary
17935     */
17936    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17937        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17938        final boolean res;
17939
17940        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17941                ? UserHandle.USER_ALL : userId;
17942
17943        if (isPackageDeviceAdmin(packageName, removeUser)) {
17944            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17945            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17946        }
17947
17948        PackageSetting uninstalledPs = null;
17949        PackageParser.Package pkg = null;
17950
17951        // for the uninstall-updates case and restricted profiles, remember the per-
17952        // user handle installed state
17953        int[] allUsers;
17954        synchronized (mPackages) {
17955            uninstalledPs = mSettings.mPackages.get(packageName);
17956            if (uninstalledPs == null) {
17957                Slog.w(TAG, "Not removing non-existent package " + packageName);
17958                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17959            }
17960
17961            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17962                    && uninstalledPs.versionCode != versionCode) {
17963                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17964                        + uninstalledPs.versionCode + " != " + versionCode);
17965                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17966            }
17967
17968            // Static shared libs can be declared by any package, so let us not
17969            // allow removing a package if it provides a lib others depend on.
17970            pkg = mPackages.get(packageName);
17971
17972            allUsers = sUserManager.getUserIds();
17973
17974            if (pkg != null && pkg.staticSharedLibName != null) {
17975                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17976                        pkg.staticSharedLibVersion);
17977                if (libEntry != null) {
17978                    for (int currUserId : allUsers) {
17979                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17980                            continue;
17981                        }
17982                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17983                                libEntry.info, 0, currUserId);
17984                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17985                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17986                                    + " hosting lib " + libEntry.info.getName() + " version "
17987                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17988                                    + " for user " + currUserId);
17989                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17990                        }
17991                    }
17992                }
17993            }
17994
17995            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17996        }
17997
17998        final int freezeUser;
17999        if (isUpdatedSystemApp(uninstalledPs)
18000                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18001            // We're downgrading a system app, which will apply to all users, so
18002            // freeze them all during the downgrade
18003            freezeUser = UserHandle.USER_ALL;
18004        } else {
18005            freezeUser = removeUser;
18006        }
18007
18008        synchronized (mInstallLock) {
18009            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18010            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18011                    deleteFlags, "deletePackageX")) {
18012                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18013                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18014            }
18015            synchronized (mPackages) {
18016                if (res) {
18017                    if (pkg != null) {
18018                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18019                    }
18020                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18021                    updateInstantAppInstallerLocked(packageName);
18022                }
18023            }
18024        }
18025
18026        if (res) {
18027            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18028            info.sendPackageRemovedBroadcasts(killApp);
18029            info.sendSystemPackageUpdatedBroadcasts();
18030            info.sendSystemPackageAppearedBroadcasts();
18031        }
18032        // Force a gc here.
18033        Runtime.getRuntime().gc();
18034        // Delete the resources here after sending the broadcast to let
18035        // other processes clean up before deleting resources.
18036        if (info.args != null) {
18037            synchronized (mInstallLock) {
18038                info.args.doPostDeleteLI(true);
18039            }
18040        }
18041
18042        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18043    }
18044
18045    static class PackageRemovedInfo {
18046        final PackageSender packageSender;
18047        String removedPackage;
18048        String installerPackageName;
18049        int uid = -1;
18050        int removedAppId = -1;
18051        int[] origUsers;
18052        int[] removedUsers = null;
18053        int[] broadcastUsers = null;
18054        int[] instantUserIds = null;
18055        SparseArray<Integer> installReasons;
18056        boolean isRemovedPackageSystemUpdate = false;
18057        boolean isUpdate;
18058        boolean dataRemoved;
18059        boolean removedForAllUsers;
18060        boolean isStaticSharedLib;
18061        // Clean up resources deleted packages.
18062        InstallArgs args = null;
18063        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18064        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18065
18066        PackageRemovedInfo(PackageSender packageSender) {
18067            this.packageSender = packageSender;
18068        }
18069
18070        void sendPackageRemovedBroadcasts(boolean killApp) {
18071            sendPackageRemovedBroadcastInternal(killApp);
18072            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18073            for (int i = 0; i < childCount; i++) {
18074                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18075                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18076            }
18077        }
18078
18079        void sendSystemPackageUpdatedBroadcasts() {
18080            if (isRemovedPackageSystemUpdate) {
18081                sendSystemPackageUpdatedBroadcastsInternal();
18082                final int childCount = (removedChildPackages != null)
18083                        ? removedChildPackages.size() : 0;
18084                for (int i = 0; i < childCount; i++) {
18085                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18086                    if (childInfo.isRemovedPackageSystemUpdate) {
18087                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18088                    }
18089                }
18090            }
18091        }
18092
18093        void sendSystemPackageAppearedBroadcasts() {
18094            final int packageCount = (appearedChildPackages != null)
18095                    ? appearedChildPackages.size() : 0;
18096            for (int i = 0; i < packageCount; i++) {
18097                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18098                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18099                    true /*sendBootCompleted*/, false /*startReceiver*/,
18100                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18101            }
18102        }
18103
18104        private void sendSystemPackageUpdatedBroadcastsInternal() {
18105            Bundle extras = new Bundle(2);
18106            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18107            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18108            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18109                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18110            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18111                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18112            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18113                null, null, 0, removedPackage, null, null, null);
18114            if (installerPackageName != null) {
18115                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18116                        removedPackage, extras, 0 /*flags*/,
18117                        installerPackageName, null, null, null);
18118                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18119                        removedPackage, extras, 0 /*flags*/,
18120                        installerPackageName, null, null, null);
18121            }
18122        }
18123
18124        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18125            // Don't send static shared library removal broadcasts as these
18126            // libs are visible only the the apps that depend on them an one
18127            // cannot remove the library if it has a dependency.
18128            if (isStaticSharedLib) {
18129                return;
18130            }
18131            Bundle extras = new Bundle(2);
18132            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18133            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18134            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18135            if (isUpdate || isRemovedPackageSystemUpdate) {
18136                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18137            }
18138            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18139            if (removedPackage != null) {
18140                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18141                    removedPackage, extras, 0, null /*targetPackage*/, null,
18142                    broadcastUsers, instantUserIds);
18143                if (installerPackageName != null) {
18144                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18145                            removedPackage, extras, 0 /*flags*/,
18146                            installerPackageName, null, broadcastUsers, instantUserIds);
18147                }
18148                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18149                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18150                        removedPackage, extras,
18151                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18152                        null, null, broadcastUsers, instantUserIds);
18153                    packageSender.notifyPackageRemoved(removedPackage);
18154                }
18155            }
18156            if (removedAppId >= 0) {
18157                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18158                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18159                    null, null, broadcastUsers, instantUserIds);
18160            }
18161        }
18162
18163        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18164            removedUsers = userIds;
18165            if (removedUsers == null) {
18166                broadcastUsers = null;
18167                return;
18168            }
18169
18170            broadcastUsers = EMPTY_INT_ARRAY;
18171            instantUserIds = EMPTY_INT_ARRAY;
18172            for (int i = userIds.length - 1; i >= 0; --i) {
18173                final int userId = userIds[i];
18174                if (deletedPackageSetting.getInstantApp(userId)) {
18175                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18176                } else {
18177                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18178                }
18179            }
18180        }
18181    }
18182
18183    /*
18184     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18185     * flag is not set, the data directory is removed as well.
18186     * make sure this flag is set for partially installed apps. If not its meaningless to
18187     * delete a partially installed application.
18188     */
18189    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18190            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18191        String packageName = ps.name;
18192        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18193        // Retrieve object to delete permissions for shared user later on
18194        final PackageParser.Package deletedPkg;
18195        final PackageSetting deletedPs;
18196        // reader
18197        synchronized (mPackages) {
18198            deletedPkg = mPackages.get(packageName);
18199            deletedPs = mSettings.mPackages.get(packageName);
18200            if (outInfo != null) {
18201                outInfo.removedPackage = packageName;
18202                outInfo.installerPackageName = ps.installerPackageName;
18203                outInfo.isStaticSharedLib = deletedPkg != null
18204                        && deletedPkg.staticSharedLibName != null;
18205                outInfo.populateUsers(deletedPs == null ? null
18206                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18207            }
18208        }
18209
18210        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18211
18212        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18213            final PackageParser.Package resolvedPkg;
18214            if (deletedPkg != null) {
18215                resolvedPkg = deletedPkg;
18216            } else {
18217                // We don't have a parsed package when it lives on an ejected
18218                // adopted storage device, so fake something together
18219                resolvedPkg = new PackageParser.Package(ps.name);
18220                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18221            }
18222            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18223                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18224            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18225            if (outInfo != null) {
18226                outInfo.dataRemoved = true;
18227            }
18228            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18229        }
18230
18231        int removedAppId = -1;
18232
18233        // writer
18234        synchronized (mPackages) {
18235            boolean installedStateChanged = false;
18236            if (deletedPs != null) {
18237                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18238                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18239                    clearDefaultBrowserIfNeeded(packageName);
18240                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18241                    removedAppId = mSettings.removePackageLPw(packageName);
18242                    if (outInfo != null) {
18243                        outInfo.removedAppId = removedAppId;
18244                    }
18245                    mPermissionManager.updatePermissions(
18246                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18247                    if (deletedPs.sharedUser != null) {
18248                        // Remove permissions associated with package. Since runtime
18249                        // permissions are per user we have to kill the removed package
18250                        // or packages running under the shared user of the removed
18251                        // package if revoking the permissions requested only by the removed
18252                        // package is successful and this causes a change in gids.
18253                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18254                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18255                                    userId);
18256                            if (userIdToKill == UserHandle.USER_ALL
18257                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18258                                // If gids changed for this user, kill all affected packages.
18259                                mHandler.post(new Runnable() {
18260                                    @Override
18261                                    public void run() {
18262                                        // This has to happen with no lock held.
18263                                        killApplication(deletedPs.name, deletedPs.appId,
18264                                                KILL_APP_REASON_GIDS_CHANGED);
18265                                    }
18266                                });
18267                                break;
18268                            }
18269                        }
18270                    }
18271                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18272                }
18273                // make sure to preserve per-user disabled state if this removal was just
18274                // a downgrade of a system app to the factory package
18275                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18276                    if (DEBUG_REMOVE) {
18277                        Slog.d(TAG, "Propagating install state across downgrade");
18278                    }
18279                    for (int userId : allUserHandles) {
18280                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18281                        if (DEBUG_REMOVE) {
18282                            Slog.d(TAG, "    user " + userId + " => " + installed);
18283                        }
18284                        if (installed != ps.getInstalled(userId)) {
18285                            installedStateChanged = true;
18286                        }
18287                        ps.setInstalled(installed, userId);
18288                    }
18289                }
18290            }
18291            // can downgrade to reader
18292            if (writeSettings) {
18293                // Save settings now
18294                mSettings.writeLPr();
18295            }
18296            if (installedStateChanged) {
18297                mSettings.writeKernelMappingLPr(ps);
18298            }
18299        }
18300        if (removedAppId != -1) {
18301            // A user ID was deleted here. Go through all users and remove it
18302            // from KeyStore.
18303            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18304        }
18305    }
18306
18307    static boolean locationIsPrivileged(String path) {
18308        try {
18309            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18310            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18311            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18312            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18313            return path.startsWith(privilegedAppDir.getCanonicalPath())
18314                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18315                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18316                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18317        } catch (IOException e) {
18318            Slog.e(TAG, "Unable to access code path " + path);
18319        }
18320        return false;
18321    }
18322
18323    static boolean locationIsOem(String path) {
18324        try {
18325            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18326        } catch (IOException e) {
18327            Slog.e(TAG, "Unable to access code path " + path);
18328        }
18329        return false;
18330    }
18331
18332    static boolean locationIsVendor(String path) {
18333        try {
18334            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18335                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18336        } catch (IOException e) {
18337            Slog.e(TAG, "Unable to access code path " + path);
18338        }
18339        return false;
18340    }
18341
18342    static boolean locationIsProduct(String path) {
18343        try {
18344            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18345        } catch (IOException e) {
18346            Slog.e(TAG, "Unable to access code path " + path);
18347        }
18348        return false;
18349    }
18350
18351    /*
18352     * Tries to delete system package.
18353     */
18354    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18355            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18356            boolean writeSettings) {
18357        if (deletedPs.parentPackageName != null) {
18358            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18359            return false;
18360        }
18361
18362        final boolean applyUserRestrictions
18363                = (allUserHandles != null) && (outInfo.origUsers != null);
18364        final PackageSetting disabledPs;
18365        // Confirm if the system package has been updated
18366        // An updated system app can be deleted. This will also have to restore
18367        // the system pkg from system partition
18368        // reader
18369        synchronized (mPackages) {
18370            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18371        }
18372
18373        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18374                + " disabledPs=" + disabledPs);
18375
18376        if (disabledPs == null) {
18377            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18378            return false;
18379        } else if (DEBUG_REMOVE) {
18380            Slog.d(TAG, "Deleting system pkg from data partition");
18381        }
18382
18383        if (DEBUG_REMOVE) {
18384            if (applyUserRestrictions) {
18385                Slog.d(TAG, "Remembering install states:");
18386                for (int userId : allUserHandles) {
18387                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18388                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18389                }
18390            }
18391        }
18392
18393        // Delete the updated package
18394        outInfo.isRemovedPackageSystemUpdate = true;
18395        if (outInfo.removedChildPackages != null) {
18396            final int childCount = (deletedPs.childPackageNames != null)
18397                    ? deletedPs.childPackageNames.size() : 0;
18398            for (int i = 0; i < childCount; i++) {
18399                String childPackageName = deletedPs.childPackageNames.get(i);
18400                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18401                        .contains(childPackageName)) {
18402                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18403                            childPackageName);
18404                    if (childInfo != null) {
18405                        childInfo.isRemovedPackageSystemUpdate = true;
18406                    }
18407                }
18408            }
18409        }
18410
18411        if (disabledPs.versionCode < deletedPs.versionCode) {
18412            // Delete data for downgrades
18413            flags &= ~PackageManager.DELETE_KEEP_DATA;
18414        } else {
18415            // Preserve data by setting flag
18416            flags |= PackageManager.DELETE_KEEP_DATA;
18417        }
18418
18419        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18420                outInfo, writeSettings, disabledPs.pkg);
18421        if (!ret) {
18422            return false;
18423        }
18424
18425        // writer
18426        synchronized (mPackages) {
18427            // NOTE: The system package always needs to be enabled; even if it's for
18428            // a compressed stub. If we don't, installing the system package fails
18429            // during scan [scanning checks the disabled packages]. We will reverse
18430            // this later, after we've "installed" the stub.
18431            // Reinstate the old system package
18432            enableSystemPackageLPw(disabledPs.pkg);
18433            // Remove any native libraries from the upgraded package.
18434            removeNativeBinariesLI(deletedPs);
18435        }
18436
18437        // Install the system package
18438        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18439        try {
18440            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18441                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18442        } catch (PackageManagerException e) {
18443            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18444                    + e.getMessage());
18445            return false;
18446        } finally {
18447            if (disabledPs.pkg.isStub) {
18448                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18449            }
18450        }
18451        return true;
18452    }
18453
18454    /**
18455     * Installs a package that's already on the system partition.
18456     */
18457    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18458            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18459            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18460                    throws PackageManagerException {
18461        @ParseFlags int parseFlags =
18462                mDefParseFlags
18463                | PackageParser.PARSE_MUST_BE_APK
18464                | PackageParser.PARSE_IS_SYSTEM_DIR;
18465        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18466        if (isPrivileged || locationIsPrivileged(codePathString)) {
18467            scanFlags |= SCAN_AS_PRIVILEGED;
18468        }
18469        if (locationIsOem(codePathString)) {
18470            scanFlags |= SCAN_AS_OEM;
18471        }
18472        if (locationIsVendor(codePathString)) {
18473            scanFlags |= SCAN_AS_VENDOR;
18474        }
18475        if (locationIsProduct(codePathString)) {
18476            scanFlags |= SCAN_AS_PRODUCT;
18477        }
18478
18479        final File codePath = new File(codePathString);
18480        final PackageParser.Package pkg =
18481                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18482
18483        try {
18484            // update shared libraries for the newly re-installed system package
18485            updateSharedLibrariesLPr(pkg, null);
18486        } catch (PackageManagerException e) {
18487            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18488        }
18489
18490        prepareAppDataAfterInstallLIF(pkg);
18491
18492        // writer
18493        synchronized (mPackages) {
18494            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18495
18496            // Propagate the permissions state as we do not want to drop on the floor
18497            // runtime permissions. The update permissions method below will take
18498            // care of removing obsolete permissions and grant install permissions.
18499            if (origPermissionState != null) {
18500                ps.getPermissionsState().copyFrom(origPermissionState);
18501            }
18502            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18503                    mPermissionCallback);
18504
18505            final boolean applyUserRestrictions
18506                    = (allUserHandles != null) && (origUserHandles != null);
18507            if (applyUserRestrictions) {
18508                boolean installedStateChanged = false;
18509                if (DEBUG_REMOVE) {
18510                    Slog.d(TAG, "Propagating install state across reinstall");
18511                }
18512                for (int userId : allUserHandles) {
18513                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18514                    if (DEBUG_REMOVE) {
18515                        Slog.d(TAG, "    user " + userId + " => " + installed);
18516                    }
18517                    if (installed != ps.getInstalled(userId)) {
18518                        installedStateChanged = true;
18519                    }
18520                    ps.setInstalled(installed, userId);
18521
18522                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18523                }
18524                // Regardless of writeSettings we need to ensure that this restriction
18525                // state propagation is persisted
18526                mSettings.writeAllUsersPackageRestrictionsLPr();
18527                if (installedStateChanged) {
18528                    mSettings.writeKernelMappingLPr(ps);
18529                }
18530            }
18531            // can downgrade to reader here
18532            if (writeSettings) {
18533                mSettings.writeLPr();
18534            }
18535        }
18536        return pkg;
18537    }
18538
18539    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18540            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18541            PackageRemovedInfo outInfo, boolean writeSettings,
18542            PackageParser.Package replacingPackage) {
18543        synchronized (mPackages) {
18544            if (outInfo != null) {
18545                outInfo.uid = ps.appId;
18546            }
18547
18548            if (outInfo != null && outInfo.removedChildPackages != null) {
18549                final int childCount = (ps.childPackageNames != null)
18550                        ? ps.childPackageNames.size() : 0;
18551                for (int i = 0; i < childCount; i++) {
18552                    String childPackageName = ps.childPackageNames.get(i);
18553                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18554                    if (childPs == null) {
18555                        return false;
18556                    }
18557                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18558                            childPackageName);
18559                    if (childInfo != null) {
18560                        childInfo.uid = childPs.appId;
18561                    }
18562                }
18563            }
18564        }
18565
18566        // Delete package data from internal structures and also remove data if flag is set
18567        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18568
18569        // Delete the child packages data
18570        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18571        for (int i = 0; i < childCount; i++) {
18572            PackageSetting childPs;
18573            synchronized (mPackages) {
18574                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18575            }
18576            if (childPs != null) {
18577                PackageRemovedInfo childOutInfo = (outInfo != null
18578                        && outInfo.removedChildPackages != null)
18579                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18580                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18581                        && (replacingPackage != null
18582                        && !replacingPackage.hasChildPackage(childPs.name))
18583                        ? flags & ~DELETE_KEEP_DATA : flags;
18584                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18585                        deleteFlags, writeSettings);
18586            }
18587        }
18588
18589        // Delete application code and resources only for parent packages
18590        if (ps.parentPackageName == null) {
18591            if (deleteCodeAndResources && (outInfo != null)) {
18592                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18593                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18594                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18595            }
18596        }
18597
18598        return true;
18599    }
18600
18601    @Override
18602    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18603            int userId) {
18604        mContext.enforceCallingOrSelfPermission(
18605                android.Manifest.permission.DELETE_PACKAGES, null);
18606        synchronized (mPackages) {
18607            // Cannot block uninstall of static shared libs as they are
18608            // considered a part of the using app (emulating static linking).
18609            // Also static libs are installed always on internal storage.
18610            PackageParser.Package pkg = mPackages.get(packageName);
18611            if (pkg != null && pkg.staticSharedLibName != null) {
18612                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18613                        + " providing static shared library: " + pkg.staticSharedLibName);
18614                return false;
18615            }
18616            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18617            mSettings.writePackageRestrictionsLPr(userId);
18618        }
18619        return true;
18620    }
18621
18622    @Override
18623    public boolean getBlockUninstallForUser(String packageName, int userId) {
18624        synchronized (mPackages) {
18625            final PackageSetting ps = mSettings.mPackages.get(packageName);
18626            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18627                return false;
18628            }
18629            return mSettings.getBlockUninstallLPr(userId, packageName);
18630        }
18631    }
18632
18633    @Override
18634    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18635        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18636        synchronized (mPackages) {
18637            PackageSetting ps = mSettings.mPackages.get(packageName);
18638            if (ps == null) {
18639                Log.w(TAG, "Package doesn't exist: " + packageName);
18640                return false;
18641            }
18642            if (systemUserApp) {
18643                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18644            } else {
18645                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18646            }
18647            mSettings.writeLPr();
18648        }
18649        return true;
18650    }
18651
18652    /*
18653     * This method handles package deletion in general
18654     */
18655    private boolean deletePackageLIF(String packageName, UserHandle user,
18656            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18657            PackageRemovedInfo outInfo, boolean writeSettings,
18658            PackageParser.Package replacingPackage) {
18659        if (packageName == null) {
18660            Slog.w(TAG, "Attempt to delete null packageName.");
18661            return false;
18662        }
18663
18664        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18665
18666        PackageSetting ps;
18667        synchronized (mPackages) {
18668            ps = mSettings.mPackages.get(packageName);
18669            if (ps == null) {
18670                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18671                return false;
18672            }
18673
18674            if (ps.parentPackageName != null && (!isSystemApp(ps)
18675                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18676                if (DEBUG_REMOVE) {
18677                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18678                            + ((user == null) ? UserHandle.USER_ALL : user));
18679                }
18680                final int removedUserId = (user != null) ? user.getIdentifier()
18681                        : UserHandle.USER_ALL;
18682
18683                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18684                    return false;
18685                }
18686                markPackageUninstalledForUserLPw(ps, user);
18687                scheduleWritePackageRestrictionsLocked(user);
18688                return true;
18689            }
18690        }
18691
18692        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18693        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18694            onSuspendingPackageRemoved(packageName, userId);
18695        }
18696
18697
18698        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18699                && user.getIdentifier() != UserHandle.USER_ALL)) {
18700            // The caller is asking that the package only be deleted for a single
18701            // user.  To do this, we just mark its uninstalled state and delete
18702            // its data. If this is a system app, we only allow this to happen if
18703            // they have set the special DELETE_SYSTEM_APP which requests different
18704            // semantics than normal for uninstalling system apps.
18705            markPackageUninstalledForUserLPw(ps, user);
18706
18707            if (!isSystemApp(ps)) {
18708                // Do not uninstall the APK if an app should be cached
18709                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18710                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18711                    // Other user still have this package installed, so all
18712                    // we need to do is clear this user's data and save that
18713                    // it is uninstalled.
18714                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18715                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18716                        return false;
18717                    }
18718                    scheduleWritePackageRestrictionsLocked(user);
18719                    return true;
18720                } else {
18721                    // We need to set it back to 'installed' so the uninstall
18722                    // broadcasts will be sent correctly.
18723                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18724                    ps.setInstalled(true, user.getIdentifier());
18725                    mSettings.writeKernelMappingLPr(ps);
18726                }
18727            } else {
18728                // This is a system app, so we assume that the
18729                // other users still have this package installed, so all
18730                // we need to do is clear this user's data and save that
18731                // it is uninstalled.
18732                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18733                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18734                    return false;
18735                }
18736                scheduleWritePackageRestrictionsLocked(user);
18737                return true;
18738            }
18739        }
18740
18741        // If we are deleting a composite package for all users, keep track
18742        // of result for each child.
18743        if (ps.childPackageNames != null && outInfo != null) {
18744            synchronized (mPackages) {
18745                final int childCount = ps.childPackageNames.size();
18746                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18747                for (int i = 0; i < childCount; i++) {
18748                    String childPackageName = ps.childPackageNames.get(i);
18749                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18750                    childInfo.removedPackage = childPackageName;
18751                    childInfo.installerPackageName = ps.installerPackageName;
18752                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18753                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18754                    if (childPs != null) {
18755                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18756                    }
18757                }
18758            }
18759        }
18760
18761        boolean ret = false;
18762        if (isSystemApp(ps)) {
18763            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18764            // When an updated system application is deleted we delete the existing resources
18765            // as well and fall back to existing code in system partition
18766            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18767        } else {
18768            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18769            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18770                    outInfo, writeSettings, replacingPackage);
18771        }
18772
18773        // Take a note whether we deleted the package for all users
18774        if (outInfo != null) {
18775            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18776            if (outInfo.removedChildPackages != null) {
18777                synchronized (mPackages) {
18778                    final int childCount = outInfo.removedChildPackages.size();
18779                    for (int i = 0; i < childCount; i++) {
18780                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18781                        if (childInfo != null) {
18782                            childInfo.removedForAllUsers = mPackages.get(
18783                                    childInfo.removedPackage) == null;
18784                        }
18785                    }
18786                }
18787            }
18788            // If we uninstalled an update to a system app there may be some
18789            // child packages that appeared as they are declared in the system
18790            // app but were not declared in the update.
18791            if (isSystemApp(ps)) {
18792                synchronized (mPackages) {
18793                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18794                    final int childCount = (updatedPs.childPackageNames != null)
18795                            ? updatedPs.childPackageNames.size() : 0;
18796                    for (int i = 0; i < childCount; i++) {
18797                        String childPackageName = updatedPs.childPackageNames.get(i);
18798                        if (outInfo.removedChildPackages == null
18799                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18800                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18801                            if (childPs == null) {
18802                                continue;
18803                            }
18804                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18805                            installRes.name = childPackageName;
18806                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18807                            installRes.pkg = mPackages.get(childPackageName);
18808                            installRes.uid = childPs.pkg.applicationInfo.uid;
18809                            if (outInfo.appearedChildPackages == null) {
18810                                outInfo.appearedChildPackages = new ArrayMap<>();
18811                            }
18812                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18813                        }
18814                    }
18815                }
18816            }
18817        }
18818
18819        return ret;
18820    }
18821
18822    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18823        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18824                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18825        for (int nextUserId : userIds) {
18826            if (DEBUG_REMOVE) {
18827                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18828            }
18829            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18830                    false /*installed*/,
18831                    true /*stopped*/,
18832                    true /*notLaunched*/,
18833                    false /*hidden*/,
18834                    false /*suspended*/,
18835                    null, /*suspendingPackage*/
18836                    null, /*suspendedAppExtras*/
18837                    null, /*suspendedLauncherExtras*/
18838                    false /*instantApp*/,
18839                    false /*virtualPreload*/,
18840                    null /*lastDisableAppCaller*/,
18841                    null /*enabledComponents*/,
18842                    null /*disabledComponents*/,
18843                    ps.readUserState(nextUserId).domainVerificationStatus,
18844                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18845                    null /*harmfulAppWarning*/);
18846        }
18847        mSettings.writeKernelMappingLPr(ps);
18848    }
18849
18850    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18851            PackageRemovedInfo outInfo) {
18852        final PackageParser.Package pkg;
18853        synchronized (mPackages) {
18854            pkg = mPackages.get(ps.name);
18855        }
18856
18857        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18858                : new int[] {userId};
18859        for (int nextUserId : userIds) {
18860            if (DEBUG_REMOVE) {
18861                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18862                        + nextUserId);
18863            }
18864
18865            destroyAppDataLIF(pkg, userId,
18866                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18867            destroyAppProfilesLIF(pkg, userId);
18868            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18869            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18870            schedulePackageCleaning(ps.name, nextUserId, false);
18871            synchronized (mPackages) {
18872                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18873                    scheduleWritePackageRestrictionsLocked(nextUserId);
18874                }
18875                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18876            }
18877        }
18878
18879        if (outInfo != null) {
18880            outInfo.removedPackage = ps.name;
18881            outInfo.installerPackageName = ps.installerPackageName;
18882            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18883            outInfo.removedAppId = ps.appId;
18884            outInfo.removedUsers = userIds;
18885            outInfo.broadcastUsers = userIds;
18886        }
18887
18888        return true;
18889    }
18890
18891    private static final class ClearStorageConnection implements ServiceConnection {
18892        IMediaContainerService mContainerService;
18893
18894        @Override
18895        public void onServiceConnected(ComponentName name, IBinder service) {
18896            synchronized (this) {
18897                mContainerService = IMediaContainerService.Stub
18898                        .asInterface(Binder.allowBlocking(service));
18899                notifyAll();
18900            }
18901        }
18902
18903        @Override
18904        public void onServiceDisconnected(ComponentName name) {
18905        }
18906    }
18907
18908    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18909        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18910
18911        final boolean mounted;
18912        if (Environment.isExternalStorageEmulated()) {
18913            mounted = true;
18914        } else {
18915            final String status = Environment.getExternalStorageState();
18916
18917            mounted = status.equals(Environment.MEDIA_MOUNTED)
18918                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18919        }
18920
18921        if (!mounted) {
18922            return;
18923        }
18924
18925        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18926        int[] users;
18927        if (userId == UserHandle.USER_ALL) {
18928            users = sUserManager.getUserIds();
18929        } else {
18930            users = new int[] { userId };
18931        }
18932        final ClearStorageConnection conn = new ClearStorageConnection();
18933        if (mContext.bindServiceAsUser(
18934                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18935            try {
18936                for (int curUser : users) {
18937                    long timeout = SystemClock.uptimeMillis() + 5000;
18938                    synchronized (conn) {
18939                        long now;
18940                        while (conn.mContainerService == null &&
18941                                (now = SystemClock.uptimeMillis()) < timeout) {
18942                            try {
18943                                conn.wait(timeout - now);
18944                            } catch (InterruptedException e) {
18945                            }
18946                        }
18947                    }
18948                    if (conn.mContainerService == null) {
18949                        return;
18950                    }
18951
18952                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18953                    clearDirectory(conn.mContainerService,
18954                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18955                    if (allData) {
18956                        clearDirectory(conn.mContainerService,
18957                                userEnv.buildExternalStorageAppDataDirs(packageName));
18958                        clearDirectory(conn.mContainerService,
18959                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18960                    }
18961                }
18962            } finally {
18963                mContext.unbindService(conn);
18964            }
18965        }
18966    }
18967
18968    @Override
18969    public void clearApplicationProfileData(String packageName) {
18970        enforceSystemOrRoot("Only the system can clear all profile data");
18971
18972        final PackageParser.Package pkg;
18973        synchronized (mPackages) {
18974            pkg = mPackages.get(packageName);
18975        }
18976
18977        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18978            synchronized (mInstallLock) {
18979                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18980            }
18981        }
18982    }
18983
18984    @Override
18985    public void clearApplicationUserData(final String packageName,
18986            final IPackageDataObserver observer, final int userId) {
18987        mContext.enforceCallingOrSelfPermission(
18988                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18989
18990        final int callingUid = Binder.getCallingUid();
18991        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18992                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18993
18994        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18995        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18996        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18997            throw new SecurityException("Cannot clear data for a protected package: "
18998                    + packageName);
18999        }
19000        // Queue up an async operation since the package deletion may take a little while.
19001        mHandler.post(new Runnable() {
19002            public void run() {
19003                mHandler.removeCallbacks(this);
19004                final boolean succeeded;
19005                if (!filterApp) {
19006                    try (PackageFreezer freezer = freezePackage(packageName,
19007                            "clearApplicationUserData")) {
19008                        synchronized (mInstallLock) {
19009                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19010                        }
19011                        clearExternalStorageDataSync(packageName, userId, true);
19012                        synchronized (mPackages) {
19013                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19014                                    packageName, userId);
19015                        }
19016                    }
19017                    if (succeeded) {
19018                        // invoke DeviceStorageMonitor's update method to clear any notifications
19019                        DeviceStorageMonitorInternal dsm = LocalServices
19020                                .getService(DeviceStorageMonitorInternal.class);
19021                        if (dsm != null) {
19022                            dsm.checkMemory();
19023                        }
19024                    }
19025                } else {
19026                    succeeded = false;
19027                }
19028                if (observer != null) {
19029                    try {
19030                        observer.onRemoveCompleted(packageName, succeeded);
19031                    } catch (RemoteException e) {
19032                        Log.i(TAG, "Observer no longer exists.");
19033                    }
19034                } //end if observer
19035            } //end run
19036        });
19037    }
19038
19039    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19040        if (packageName == null) {
19041            Slog.w(TAG, "Attempt to delete null packageName.");
19042            return false;
19043        }
19044
19045        // Try finding details about the requested package
19046        PackageParser.Package pkg;
19047        synchronized (mPackages) {
19048            pkg = mPackages.get(packageName);
19049            if (pkg == null) {
19050                final PackageSetting ps = mSettings.mPackages.get(packageName);
19051                if (ps != null) {
19052                    pkg = ps.pkg;
19053                }
19054            }
19055
19056            if (pkg == null) {
19057                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19058                return false;
19059            }
19060
19061            PackageSetting ps = (PackageSetting) pkg.mExtras;
19062            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19063        }
19064
19065        clearAppDataLIF(pkg, userId,
19066                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19067
19068        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19069        removeKeystoreDataIfNeeded(userId, appId);
19070
19071        UserManagerInternal umInternal = getUserManagerInternal();
19072        final int flags;
19073        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19074            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19075        } else if (umInternal.isUserRunning(userId)) {
19076            flags = StorageManager.FLAG_STORAGE_DE;
19077        } else {
19078            flags = 0;
19079        }
19080        prepareAppDataContentsLIF(pkg, userId, flags);
19081
19082        return true;
19083    }
19084
19085    /**
19086     * Reverts user permission state changes (permissions and flags) in
19087     * all packages for a given user.
19088     *
19089     * @param userId The device user for which to do a reset.
19090     */
19091    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19092        final int packageCount = mPackages.size();
19093        for (int i = 0; i < packageCount; i++) {
19094            PackageParser.Package pkg = mPackages.valueAt(i);
19095            PackageSetting ps = (PackageSetting) pkg.mExtras;
19096            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19097        }
19098    }
19099
19100    private void resetNetworkPolicies(int userId) {
19101        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19102    }
19103
19104    /**
19105     * Reverts user permission state changes (permissions and flags).
19106     *
19107     * @param ps The package for which to reset.
19108     * @param userId The device user for which to do a reset.
19109     */
19110    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19111            final PackageSetting ps, final int userId) {
19112        if (ps.pkg == null) {
19113            return;
19114        }
19115
19116        // These are flags that can change base on user actions.
19117        final int userSettableMask = FLAG_PERMISSION_USER_SET
19118                | FLAG_PERMISSION_USER_FIXED
19119                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19120                | FLAG_PERMISSION_REVIEW_REQUIRED;
19121
19122        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19123                | FLAG_PERMISSION_POLICY_FIXED;
19124
19125        boolean writeInstallPermissions = false;
19126        boolean writeRuntimePermissions = false;
19127
19128        final int permissionCount = ps.pkg.requestedPermissions.size();
19129        for (int i = 0; i < permissionCount; i++) {
19130            final String permName = ps.pkg.requestedPermissions.get(i);
19131            final BasePermission bp =
19132                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19133            if (bp == null) {
19134                continue;
19135            }
19136
19137            // If shared user we just reset the state to which only this app contributed.
19138            if (ps.sharedUser != null) {
19139                boolean used = false;
19140                final int packageCount = ps.sharedUser.packages.size();
19141                for (int j = 0; j < packageCount; j++) {
19142                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19143                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19144                            && pkg.pkg.requestedPermissions.contains(permName)) {
19145                        used = true;
19146                        break;
19147                    }
19148                }
19149                if (used) {
19150                    continue;
19151                }
19152            }
19153
19154            final PermissionsState permissionsState = ps.getPermissionsState();
19155
19156            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19157
19158            // Always clear the user settable flags.
19159            final boolean hasInstallState =
19160                    permissionsState.getInstallPermissionState(permName) != null;
19161            // If permission review is enabled and this is a legacy app, mark the
19162            // permission as requiring a review as this is the initial state.
19163            int flags = 0;
19164            if (mSettings.mPermissions.mPermissionReviewRequired
19165                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19166                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19167            }
19168            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19169                if (hasInstallState) {
19170                    writeInstallPermissions = true;
19171                } else {
19172                    writeRuntimePermissions = true;
19173                }
19174            }
19175
19176            // Below is only runtime permission handling.
19177            if (!bp.isRuntime()) {
19178                continue;
19179            }
19180
19181            // Never clobber system or policy.
19182            if ((oldFlags & policyOrSystemFlags) != 0) {
19183                continue;
19184            }
19185
19186            // If this permission was granted by default, make sure it is.
19187            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19188                if (permissionsState.grantRuntimePermission(bp, userId)
19189                        != PERMISSION_OPERATION_FAILURE) {
19190                    writeRuntimePermissions = true;
19191                }
19192            // If permission review is enabled the permissions for a legacy apps
19193            // are represented as constantly granted runtime ones, so don't revoke.
19194            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19195                // Otherwise, reset the permission.
19196                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19197                switch (revokeResult) {
19198                    case PERMISSION_OPERATION_SUCCESS:
19199                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19200                        writeRuntimePermissions = true;
19201                        final int appId = ps.appId;
19202                        mHandler.post(new Runnable() {
19203                            @Override
19204                            public void run() {
19205                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19206                            }
19207                        });
19208                    } break;
19209                }
19210            }
19211        }
19212
19213        // Synchronously write as we are taking permissions away.
19214        if (writeRuntimePermissions) {
19215            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19216        }
19217
19218        // Synchronously write as we are taking permissions away.
19219        if (writeInstallPermissions) {
19220            mSettings.writeLPr();
19221        }
19222    }
19223
19224    /**
19225     * Remove entries from the keystore daemon. Will only remove it if the
19226     * {@code appId} is valid.
19227     */
19228    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19229        if (appId < 0) {
19230            return;
19231        }
19232
19233        final KeyStore keyStore = KeyStore.getInstance();
19234        if (keyStore != null) {
19235            if (userId == UserHandle.USER_ALL) {
19236                for (final int individual : sUserManager.getUserIds()) {
19237                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19238                }
19239            } else {
19240                keyStore.clearUid(UserHandle.getUid(userId, appId));
19241            }
19242        } else {
19243            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19244        }
19245    }
19246
19247    @Override
19248    public void deleteApplicationCacheFiles(final String packageName,
19249            final IPackageDataObserver observer) {
19250        final int userId = UserHandle.getCallingUserId();
19251        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19252    }
19253
19254    @Override
19255    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19256            final IPackageDataObserver observer) {
19257        final int callingUid = Binder.getCallingUid();
19258        if (mContext.checkCallingOrSelfPermission(
19259                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19260                != PackageManager.PERMISSION_GRANTED) {
19261            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19262            if (mContext.checkCallingOrSelfPermission(
19263                    android.Manifest.permission.DELETE_CACHE_FILES)
19264                    == PackageManager.PERMISSION_GRANTED) {
19265                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19266                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19267                        ", silently ignoring");
19268                return;
19269            }
19270            mContext.enforceCallingOrSelfPermission(
19271                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19272        }
19273        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19274                /* requireFullPermission= */ true, /* checkShell= */ false,
19275                "delete application cache files");
19276        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19277                android.Manifest.permission.ACCESS_INSTANT_APPS);
19278
19279        final PackageParser.Package pkg;
19280        synchronized (mPackages) {
19281            pkg = mPackages.get(packageName);
19282        }
19283
19284        // Queue up an async operation since the package deletion may take a little while.
19285        mHandler.post(new Runnable() {
19286            public void run() {
19287                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19288                boolean doClearData = true;
19289                if (ps != null) {
19290                    final boolean targetIsInstantApp =
19291                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19292                    doClearData = !targetIsInstantApp
19293                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19294                }
19295                if (doClearData) {
19296                    synchronized (mInstallLock) {
19297                        final int flags = StorageManager.FLAG_STORAGE_DE
19298                                | StorageManager.FLAG_STORAGE_CE;
19299                        // We're only clearing cache files, so we don't care if the
19300                        // app is unfrozen and still able to run
19301                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19302                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19303                    }
19304                    clearExternalStorageDataSync(packageName, userId, false);
19305                }
19306                if (observer != null) {
19307                    try {
19308                        observer.onRemoveCompleted(packageName, true);
19309                    } catch (RemoteException e) {
19310                        Log.i(TAG, "Observer no longer exists.");
19311                    }
19312                }
19313            }
19314        });
19315    }
19316
19317    @Override
19318    public void getPackageSizeInfo(final String packageName, int userHandle,
19319            final IPackageStatsObserver observer) {
19320        throw new UnsupportedOperationException(
19321                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19322    }
19323
19324    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19325        final PackageSetting ps;
19326        synchronized (mPackages) {
19327            ps = mSettings.mPackages.get(packageName);
19328            if (ps == null) {
19329                Slog.w(TAG, "Failed to find settings for " + packageName);
19330                return false;
19331            }
19332        }
19333
19334        final String[] packageNames = { packageName };
19335        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19336        final String[] codePaths = { ps.codePathString };
19337
19338        try {
19339            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19340                    ps.appId, ceDataInodes, codePaths, stats);
19341
19342            // For now, ignore code size of packages on system partition
19343            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19344                stats.codeSize = 0;
19345            }
19346
19347            // External clients expect these to be tracked separately
19348            stats.dataSize -= stats.cacheSize;
19349
19350        } catch (InstallerException e) {
19351            Slog.w(TAG, String.valueOf(e));
19352            return false;
19353        }
19354
19355        return true;
19356    }
19357
19358    private int getUidTargetSdkVersionLockedLPr(int uid) {
19359        Object obj = mSettings.getUserIdLPr(uid);
19360        if (obj instanceof SharedUserSetting) {
19361            final SharedUserSetting sus = (SharedUserSetting) obj;
19362            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19363            final Iterator<PackageSetting> it = sus.packages.iterator();
19364            while (it.hasNext()) {
19365                final PackageSetting ps = it.next();
19366                if (ps.pkg != null) {
19367                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19368                    if (v < vers) vers = v;
19369                }
19370            }
19371            return vers;
19372        } else if (obj instanceof PackageSetting) {
19373            final PackageSetting ps = (PackageSetting) obj;
19374            if (ps.pkg != null) {
19375                return ps.pkg.applicationInfo.targetSdkVersion;
19376            }
19377        }
19378        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19379    }
19380
19381    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19382        final PackageParser.Package p = mPackages.get(packageName);
19383        if (p != null) {
19384            return p.applicationInfo.targetSdkVersion;
19385        }
19386        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19387    }
19388
19389    @Override
19390    public void addPreferredActivity(IntentFilter filter, int match,
19391            ComponentName[] set, ComponentName activity, int userId) {
19392        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19393                "Adding preferred");
19394    }
19395
19396    private void addPreferredActivityInternal(IntentFilter filter, int match,
19397            ComponentName[] set, ComponentName activity, boolean always, int userId,
19398            String opname) {
19399        // writer
19400        int callingUid = Binder.getCallingUid();
19401        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19402                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19403        if (filter.countActions() == 0) {
19404            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19405            return;
19406        }
19407        synchronized (mPackages) {
19408            if (mContext.checkCallingOrSelfPermission(
19409                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19410                    != PackageManager.PERMISSION_GRANTED) {
19411                if (getUidTargetSdkVersionLockedLPr(callingUid)
19412                        < Build.VERSION_CODES.FROYO) {
19413                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19414                            + callingUid);
19415                    return;
19416                }
19417                mContext.enforceCallingOrSelfPermission(
19418                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19419            }
19420
19421            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19422            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19423                    + userId + ":");
19424            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19425            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19426            scheduleWritePackageRestrictionsLocked(userId);
19427            postPreferredActivityChangedBroadcast(userId);
19428        }
19429    }
19430
19431    private void postPreferredActivityChangedBroadcast(int userId) {
19432        mHandler.post(() -> {
19433            final IActivityManager am = ActivityManager.getService();
19434            if (am == null) {
19435                return;
19436            }
19437
19438            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19439            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19440            try {
19441                am.broadcastIntent(null, intent, null, null,
19442                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19443                        null, false, false, userId);
19444            } catch (RemoteException e) {
19445            }
19446        });
19447    }
19448
19449    @Override
19450    public void replacePreferredActivity(IntentFilter filter, int match,
19451            ComponentName[] set, ComponentName activity, int userId) {
19452        if (filter.countActions() != 1) {
19453            throw new IllegalArgumentException(
19454                    "replacePreferredActivity expects filter to have only 1 action.");
19455        }
19456        if (filter.countDataAuthorities() != 0
19457                || filter.countDataPaths() != 0
19458                || filter.countDataSchemes() > 1
19459                || filter.countDataTypes() != 0) {
19460            throw new IllegalArgumentException(
19461                    "replacePreferredActivity expects filter to have no data authorities, " +
19462                    "paths, or types; and at most one scheme.");
19463        }
19464
19465        final int callingUid = Binder.getCallingUid();
19466        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19467                true /* requireFullPermission */, false /* checkShell */,
19468                "replace preferred activity");
19469        synchronized (mPackages) {
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 replacePreferredActivity() from uid "
19476                            + Binder.getCallingUid());
19477                    return;
19478                }
19479                mContext.enforceCallingOrSelfPermission(
19480                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19481            }
19482
19483            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19484            if (pir != null) {
19485                // Get all of the existing entries that exactly match this filter.
19486                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19487                if (existing != null && existing.size() == 1) {
19488                    PreferredActivity cur = existing.get(0);
19489                    if (DEBUG_PREFERRED) {
19490                        Slog.i(TAG, "Checking replace of preferred:");
19491                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19492                        if (!cur.mPref.mAlways) {
19493                            Slog.i(TAG, "  -- CUR; not mAlways!");
19494                        } else {
19495                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19496                            Slog.i(TAG, "  -- CUR: mSet="
19497                                    + Arrays.toString(cur.mPref.mSetComponents));
19498                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19499                            Slog.i(TAG, "  -- NEW: mMatch="
19500                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19501                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19502                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19503                        }
19504                    }
19505                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19506                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19507                            && cur.mPref.sameSet(set)) {
19508                        // Setting the preferred activity to what it happens to be already
19509                        if (DEBUG_PREFERRED) {
19510                            Slog.i(TAG, "Replacing with same preferred activity "
19511                                    + cur.mPref.mShortComponent + " for user "
19512                                    + userId + ":");
19513                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19514                        }
19515                        return;
19516                    }
19517                }
19518
19519                if (existing != null) {
19520                    if (DEBUG_PREFERRED) {
19521                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19522                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19523                    }
19524                    for (int i = 0; i < existing.size(); i++) {
19525                        PreferredActivity pa = existing.get(i);
19526                        if (DEBUG_PREFERRED) {
19527                            Slog.i(TAG, "Removing existing preferred activity "
19528                                    + pa.mPref.mComponent + ":");
19529                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19530                        }
19531                        pir.removeFilter(pa);
19532                    }
19533                }
19534            }
19535            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19536                    "Replacing preferred");
19537        }
19538    }
19539
19540    @Override
19541    public void clearPackagePreferredActivities(String packageName) {
19542        final int callingUid = Binder.getCallingUid();
19543        if (getInstantAppPackageName(callingUid) != null) {
19544            return;
19545        }
19546        // writer
19547        synchronized (mPackages) {
19548            PackageParser.Package pkg = mPackages.get(packageName);
19549            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19550                if (mContext.checkCallingOrSelfPermission(
19551                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19552                        != PackageManager.PERMISSION_GRANTED) {
19553                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19554                            < Build.VERSION_CODES.FROYO) {
19555                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19556                                + callingUid);
19557                        return;
19558                    }
19559                    mContext.enforceCallingOrSelfPermission(
19560                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19561                }
19562            }
19563            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19564            if (ps != null
19565                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19566                return;
19567            }
19568            int user = UserHandle.getCallingUserId();
19569            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19570                scheduleWritePackageRestrictionsLocked(user);
19571            }
19572        }
19573    }
19574
19575    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19576    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19577        ArrayList<PreferredActivity> removed = null;
19578        boolean changed = false;
19579        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19580            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19581            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19582            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19583                continue;
19584            }
19585            Iterator<PreferredActivity> it = pir.filterIterator();
19586            while (it.hasNext()) {
19587                PreferredActivity pa = it.next();
19588                // Mark entry for removal only if it matches the package name
19589                // and the entry is of type "always".
19590                if (packageName == null ||
19591                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19592                                && pa.mPref.mAlways)) {
19593                    if (removed == null) {
19594                        removed = new ArrayList<PreferredActivity>();
19595                    }
19596                    removed.add(pa);
19597                }
19598            }
19599            if (removed != null) {
19600                for (int j=0; j<removed.size(); j++) {
19601                    PreferredActivity pa = removed.get(j);
19602                    pir.removeFilter(pa);
19603                }
19604                changed = true;
19605            }
19606        }
19607        if (changed) {
19608            postPreferredActivityChangedBroadcast(userId);
19609        }
19610        return changed;
19611    }
19612
19613    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19614    private void clearIntentFilterVerificationsLPw(int userId) {
19615        final int packageCount = mPackages.size();
19616        for (int i = 0; i < packageCount; i++) {
19617            PackageParser.Package pkg = mPackages.valueAt(i);
19618            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19619        }
19620    }
19621
19622    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19623    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19624        if (userId == UserHandle.USER_ALL) {
19625            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19626                    sUserManager.getUserIds())) {
19627                for (int oneUserId : sUserManager.getUserIds()) {
19628                    scheduleWritePackageRestrictionsLocked(oneUserId);
19629                }
19630            }
19631        } else {
19632            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19633                scheduleWritePackageRestrictionsLocked(userId);
19634            }
19635        }
19636    }
19637
19638    /** Clears state for all users, and touches intent filter verification policy */
19639    void clearDefaultBrowserIfNeeded(String packageName) {
19640        for (int oneUserId : sUserManager.getUserIds()) {
19641            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19642        }
19643    }
19644
19645    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19646        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19647        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19648            if (packageName.equals(defaultBrowserPackageName)) {
19649                setDefaultBrowserPackageName(null, userId);
19650            }
19651        }
19652    }
19653
19654    @Override
19655    public void resetApplicationPreferences(int userId) {
19656        mContext.enforceCallingOrSelfPermission(
19657                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19658        final long identity = Binder.clearCallingIdentity();
19659        // writer
19660        try {
19661            synchronized (mPackages) {
19662                clearPackagePreferredActivitiesLPw(null, userId);
19663                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19664                // TODO: We have to reset the default SMS and Phone. This requires
19665                // significant refactoring to keep all default apps in the package
19666                // manager (cleaner but more work) or have the services provide
19667                // callbacks to the package manager to request a default app reset.
19668                applyFactoryDefaultBrowserLPw(userId);
19669                clearIntentFilterVerificationsLPw(userId);
19670                primeDomainVerificationsLPw(userId);
19671                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19672                scheduleWritePackageRestrictionsLocked(userId);
19673            }
19674            resetNetworkPolicies(userId);
19675        } finally {
19676            Binder.restoreCallingIdentity(identity);
19677        }
19678    }
19679
19680    @Override
19681    public int getPreferredActivities(List<IntentFilter> outFilters,
19682            List<ComponentName> outActivities, String packageName) {
19683        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19684            return 0;
19685        }
19686        int num = 0;
19687        final int userId = UserHandle.getCallingUserId();
19688        // reader
19689        synchronized (mPackages) {
19690            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19691            if (pir != null) {
19692                final Iterator<PreferredActivity> it = pir.filterIterator();
19693                while (it.hasNext()) {
19694                    final PreferredActivity pa = it.next();
19695                    if (packageName == null
19696                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19697                                    && pa.mPref.mAlways)) {
19698                        if (outFilters != null) {
19699                            outFilters.add(new IntentFilter(pa));
19700                        }
19701                        if (outActivities != null) {
19702                            outActivities.add(pa.mPref.mComponent);
19703                        }
19704                    }
19705                }
19706            }
19707        }
19708
19709        return num;
19710    }
19711
19712    @Override
19713    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19714            int userId) {
19715        int callingUid = Binder.getCallingUid();
19716        if (callingUid != Process.SYSTEM_UID) {
19717            throw new SecurityException(
19718                    "addPersistentPreferredActivity can only be run by the system");
19719        }
19720        if (filter.countActions() == 0) {
19721            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19722            return;
19723        }
19724        synchronized (mPackages) {
19725            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19726                    ":");
19727            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19728            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19729                    new PersistentPreferredActivity(filter, activity));
19730            scheduleWritePackageRestrictionsLocked(userId);
19731            postPreferredActivityChangedBroadcast(userId);
19732        }
19733    }
19734
19735    @Override
19736    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19737        int callingUid = Binder.getCallingUid();
19738        if (callingUid != Process.SYSTEM_UID) {
19739            throw new SecurityException(
19740                    "clearPackagePersistentPreferredActivities can only be run by the system");
19741        }
19742        ArrayList<PersistentPreferredActivity> removed = null;
19743        boolean changed = false;
19744        synchronized (mPackages) {
19745            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19746                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19747                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19748                        .valueAt(i);
19749                if (userId != thisUserId) {
19750                    continue;
19751                }
19752                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19753                while (it.hasNext()) {
19754                    PersistentPreferredActivity ppa = it.next();
19755                    // Mark entry for removal only if it matches the package name.
19756                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19757                        if (removed == null) {
19758                            removed = new ArrayList<PersistentPreferredActivity>();
19759                        }
19760                        removed.add(ppa);
19761                    }
19762                }
19763                if (removed != null) {
19764                    for (int j=0; j<removed.size(); j++) {
19765                        PersistentPreferredActivity ppa = removed.get(j);
19766                        ppir.removeFilter(ppa);
19767                    }
19768                    changed = true;
19769                }
19770            }
19771
19772            if (changed) {
19773                scheduleWritePackageRestrictionsLocked(userId);
19774                postPreferredActivityChangedBroadcast(userId);
19775            }
19776        }
19777    }
19778
19779    /**
19780     * Common machinery for picking apart a restored XML blob and passing
19781     * it to a caller-supplied functor to be applied to the running system.
19782     */
19783    private void restoreFromXml(XmlPullParser parser, int userId,
19784            String expectedStartTag, BlobXmlRestorer functor)
19785            throws IOException, XmlPullParserException {
19786        int type;
19787        while ((type = parser.next()) != XmlPullParser.START_TAG
19788                && type != XmlPullParser.END_DOCUMENT) {
19789        }
19790        if (type != XmlPullParser.START_TAG) {
19791            // oops didn't find a start tag?!
19792            if (DEBUG_BACKUP) {
19793                Slog.e(TAG, "Didn't find start tag during restore");
19794            }
19795            return;
19796        }
19797Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19798        // this is supposed to be TAG_PREFERRED_BACKUP
19799        if (!expectedStartTag.equals(parser.getName())) {
19800            if (DEBUG_BACKUP) {
19801                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19802            }
19803            return;
19804        }
19805
19806        // skip interfering stuff, then we're aligned with the backing implementation
19807        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19808Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19809        functor.apply(parser, userId);
19810    }
19811
19812    private interface BlobXmlRestorer {
19813        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19814    }
19815
19816    /**
19817     * Non-Binder method, support for the backup/restore mechanism: write the
19818     * full set of preferred activities in its canonical XML format.  Returns the
19819     * XML output as a byte array, or null if there is none.
19820     */
19821    @Override
19822    public byte[] getPreferredActivityBackup(int userId) {
19823        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19824            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19825        }
19826
19827        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19828        try {
19829            final XmlSerializer serializer = new FastXmlSerializer();
19830            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19831            serializer.startDocument(null, true);
19832            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19833
19834            synchronized (mPackages) {
19835                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19836            }
19837
19838            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19839            serializer.endDocument();
19840            serializer.flush();
19841        } catch (Exception e) {
19842            if (DEBUG_BACKUP) {
19843                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19844            }
19845            return null;
19846        }
19847
19848        return dataStream.toByteArray();
19849    }
19850
19851    @Override
19852    public void restorePreferredActivities(byte[] backup, int userId) {
19853        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19854            throw new SecurityException("Only the system may call restorePreferredActivities()");
19855        }
19856
19857        try {
19858            final XmlPullParser parser = Xml.newPullParser();
19859            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19860            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19861                    new BlobXmlRestorer() {
19862                        @Override
19863                        public void apply(XmlPullParser parser, int userId)
19864                                throws XmlPullParserException, IOException {
19865                            synchronized (mPackages) {
19866                                mSettings.readPreferredActivitiesLPw(parser, userId);
19867                            }
19868                        }
19869                    } );
19870        } catch (Exception e) {
19871            if (DEBUG_BACKUP) {
19872                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19873            }
19874        }
19875    }
19876
19877    /**
19878     * Non-Binder method, support for the backup/restore mechanism: write the
19879     * default browser (etc) settings in its canonical XML format.  Returns the default
19880     * browser XML representation as a byte array, or null if there is none.
19881     */
19882    @Override
19883    public byte[] getDefaultAppsBackup(int userId) {
19884        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19885            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19886        }
19887
19888        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19889        try {
19890            final XmlSerializer serializer = new FastXmlSerializer();
19891            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19892            serializer.startDocument(null, true);
19893            serializer.startTag(null, TAG_DEFAULT_APPS);
19894
19895            synchronized (mPackages) {
19896                mSettings.writeDefaultAppsLPr(serializer, userId);
19897            }
19898
19899            serializer.endTag(null, TAG_DEFAULT_APPS);
19900            serializer.endDocument();
19901            serializer.flush();
19902        } catch (Exception e) {
19903            if (DEBUG_BACKUP) {
19904                Slog.e(TAG, "Unable to write default apps for backup", e);
19905            }
19906            return null;
19907        }
19908
19909        return dataStream.toByteArray();
19910    }
19911
19912    @Override
19913    public void restoreDefaultApps(byte[] backup, int userId) {
19914        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19915            throw new SecurityException("Only the system may call restoreDefaultApps()");
19916        }
19917
19918        try {
19919            final XmlPullParser parser = Xml.newPullParser();
19920            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19921            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19922                    new BlobXmlRestorer() {
19923                        @Override
19924                        public void apply(XmlPullParser parser, int userId)
19925                                throws XmlPullParserException, IOException {
19926                            synchronized (mPackages) {
19927                                mSettings.readDefaultAppsLPw(parser, userId);
19928                            }
19929                        }
19930                    } );
19931        } catch (Exception e) {
19932            if (DEBUG_BACKUP) {
19933                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19934            }
19935        }
19936    }
19937
19938    @Override
19939    public byte[] getIntentFilterVerificationBackup(int userId) {
19940        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19941            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19942        }
19943
19944        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19945        try {
19946            final XmlSerializer serializer = new FastXmlSerializer();
19947            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19948            serializer.startDocument(null, true);
19949            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19950
19951            synchronized (mPackages) {
19952                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19953            }
19954
19955            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19956            serializer.endDocument();
19957            serializer.flush();
19958        } catch (Exception e) {
19959            if (DEBUG_BACKUP) {
19960                Slog.e(TAG, "Unable to write default apps for backup", e);
19961            }
19962            return null;
19963        }
19964
19965        return dataStream.toByteArray();
19966    }
19967
19968    @Override
19969    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19970        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19971            throw new SecurityException("Only the system may call restorePreferredActivities()");
19972        }
19973
19974        try {
19975            final XmlPullParser parser = Xml.newPullParser();
19976            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19977            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19978                    new BlobXmlRestorer() {
19979                        @Override
19980                        public void apply(XmlPullParser parser, int userId)
19981                                throws XmlPullParserException, IOException {
19982                            synchronized (mPackages) {
19983                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19984                                mSettings.writeLPr();
19985                            }
19986                        }
19987                    } );
19988        } catch (Exception e) {
19989            if (DEBUG_BACKUP) {
19990                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19991            }
19992        }
19993    }
19994
19995    @Override
19996    public byte[] getPermissionGrantBackup(int userId) {
19997        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19998            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19999        }
20000
20001        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20002        try {
20003            final XmlSerializer serializer = new FastXmlSerializer();
20004            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20005            serializer.startDocument(null, true);
20006            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20007
20008            synchronized (mPackages) {
20009                serializeRuntimePermissionGrantsLPr(serializer, userId);
20010            }
20011
20012            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20013            serializer.endDocument();
20014            serializer.flush();
20015        } catch (Exception e) {
20016            if (DEBUG_BACKUP) {
20017                Slog.e(TAG, "Unable to write default apps for backup", e);
20018            }
20019            return null;
20020        }
20021
20022        return dataStream.toByteArray();
20023    }
20024
20025    @Override
20026    public void restorePermissionGrants(byte[] backup, int userId) {
20027        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20028            throw new SecurityException("Only the system may call restorePermissionGrants()");
20029        }
20030
20031        try {
20032            final XmlPullParser parser = Xml.newPullParser();
20033            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20034            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20035                    new BlobXmlRestorer() {
20036                        @Override
20037                        public void apply(XmlPullParser parser, int userId)
20038                                throws XmlPullParserException, IOException {
20039                            synchronized (mPackages) {
20040                                processRestoredPermissionGrantsLPr(parser, userId);
20041                            }
20042                        }
20043                    } );
20044        } catch (Exception e) {
20045            if (DEBUG_BACKUP) {
20046                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20047            }
20048        }
20049    }
20050
20051    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20052            throws IOException {
20053        serializer.startTag(null, TAG_ALL_GRANTS);
20054
20055        final int N = mSettings.mPackages.size();
20056        for (int i = 0; i < N; i++) {
20057            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20058            boolean pkgGrantsKnown = false;
20059
20060            PermissionsState packagePerms = ps.getPermissionsState();
20061
20062            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20063                final int grantFlags = state.getFlags();
20064                // only look at grants that are not system/policy fixed
20065                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20066                    final boolean isGranted = state.isGranted();
20067                    // And only back up the user-twiddled state bits
20068                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20069                        final String packageName = mSettings.mPackages.keyAt(i);
20070                        if (!pkgGrantsKnown) {
20071                            serializer.startTag(null, TAG_GRANT);
20072                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20073                            pkgGrantsKnown = true;
20074                        }
20075
20076                        final boolean userSet =
20077                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20078                        final boolean userFixed =
20079                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20080                        final boolean revoke =
20081                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20082
20083                        serializer.startTag(null, TAG_PERMISSION);
20084                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20085                        if (isGranted) {
20086                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20087                        }
20088                        if (userSet) {
20089                            serializer.attribute(null, ATTR_USER_SET, "true");
20090                        }
20091                        if (userFixed) {
20092                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20093                        }
20094                        if (revoke) {
20095                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20096                        }
20097                        serializer.endTag(null, TAG_PERMISSION);
20098                    }
20099                }
20100            }
20101
20102            if (pkgGrantsKnown) {
20103                serializer.endTag(null, TAG_GRANT);
20104            }
20105        }
20106
20107        serializer.endTag(null, TAG_ALL_GRANTS);
20108    }
20109
20110    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20111            throws XmlPullParserException, IOException {
20112        String pkgName = null;
20113        int outerDepth = parser.getDepth();
20114        int type;
20115        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20116                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20117            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20118                continue;
20119            }
20120
20121            final String tagName = parser.getName();
20122            if (tagName.equals(TAG_GRANT)) {
20123                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20124                if (DEBUG_BACKUP) {
20125                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20126                }
20127            } else if (tagName.equals(TAG_PERMISSION)) {
20128
20129                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20130                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20131
20132                int newFlagSet = 0;
20133                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20134                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20135                }
20136                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20137                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20138                }
20139                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20140                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20141                }
20142                if (DEBUG_BACKUP) {
20143                    Slog.v(TAG, "  + Restoring grant:"
20144                            + " pkg=" + pkgName
20145                            + " perm=" + permName
20146                            + " granted=" + isGranted
20147                            + " bits=0x" + Integer.toHexString(newFlagSet));
20148                }
20149                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20150                if (ps != null) {
20151                    // Already installed so we apply the grant immediately
20152                    if (DEBUG_BACKUP) {
20153                        Slog.v(TAG, "        + already installed; applying");
20154                    }
20155                    PermissionsState perms = ps.getPermissionsState();
20156                    BasePermission bp =
20157                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20158                    if (bp != null) {
20159                        if (isGranted) {
20160                            perms.grantRuntimePermission(bp, userId);
20161                        }
20162                        if (newFlagSet != 0) {
20163                            perms.updatePermissionFlags(
20164                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20165                        }
20166                    }
20167                } else {
20168                    // Need to wait for post-restore install to apply the grant
20169                    if (DEBUG_BACKUP) {
20170                        Slog.v(TAG, "        - not yet installed; saving for later");
20171                    }
20172                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20173                            isGranted, newFlagSet, userId);
20174                }
20175            } else {
20176                PackageManagerService.reportSettingsProblem(Log.WARN,
20177                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20178                XmlUtils.skipCurrentTag(parser);
20179            }
20180        }
20181
20182        scheduleWriteSettingsLocked();
20183        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20184    }
20185
20186    @Override
20187    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20188            int sourceUserId, int targetUserId, int flags) {
20189        mContext.enforceCallingOrSelfPermission(
20190                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20191        int callingUid = Binder.getCallingUid();
20192        enforceOwnerRights(ownerPackage, callingUid);
20193        PackageManagerServiceUtils.enforceShellRestriction(
20194                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20195        if (intentFilter.countActions() == 0) {
20196            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20197            return;
20198        }
20199        synchronized (mPackages) {
20200            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20201                    ownerPackage, targetUserId, flags);
20202            CrossProfileIntentResolver resolver =
20203                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20204            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20205            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20206            if (existing != null) {
20207                int size = existing.size();
20208                for (int i = 0; i < size; i++) {
20209                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20210                        return;
20211                    }
20212                }
20213            }
20214            resolver.addFilter(newFilter);
20215            scheduleWritePackageRestrictionsLocked(sourceUserId);
20216        }
20217    }
20218
20219    @Override
20220    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20221        mContext.enforceCallingOrSelfPermission(
20222                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20223        final int callingUid = Binder.getCallingUid();
20224        enforceOwnerRights(ownerPackage, callingUid);
20225        PackageManagerServiceUtils.enforceShellRestriction(
20226                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20227        synchronized (mPackages) {
20228            CrossProfileIntentResolver resolver =
20229                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20230            ArraySet<CrossProfileIntentFilter> set =
20231                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20232            for (CrossProfileIntentFilter filter : set) {
20233                if (filter.getOwnerPackage().equals(ownerPackage)) {
20234                    resolver.removeFilter(filter);
20235                }
20236            }
20237            scheduleWritePackageRestrictionsLocked(sourceUserId);
20238        }
20239    }
20240
20241    // Enforcing that callingUid is owning pkg on userId
20242    private void enforceOwnerRights(String pkg, int callingUid) {
20243        // The system owns everything.
20244        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20245            return;
20246        }
20247        final int callingUserId = UserHandle.getUserId(callingUid);
20248        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20249        if (pi == null) {
20250            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20251                    + callingUserId);
20252        }
20253        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20254            throw new SecurityException("Calling uid " + callingUid
20255                    + " does not own package " + pkg);
20256        }
20257    }
20258
20259    @Override
20260    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20261        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20262            return null;
20263        }
20264        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20265    }
20266
20267    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20268        UserManagerService ums = UserManagerService.getInstance();
20269        if (ums != null) {
20270            final UserInfo parent = ums.getProfileParent(userId);
20271            final int launcherUid = (parent != null) ? parent.id : userId;
20272            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20273            if (launcherComponent != null) {
20274                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20275                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20276                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20277                        .setPackage(launcherComponent.getPackageName());
20278                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20279            }
20280        }
20281    }
20282
20283    /**
20284     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20285     * then reports the most likely home activity or null if there are more than one.
20286     */
20287    private ComponentName getDefaultHomeActivity(int userId) {
20288        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20289        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20290        if (cn != null) {
20291            return cn;
20292        }
20293
20294        // Find the launcher with the highest priority and return that component if there are no
20295        // other home activity with the same priority.
20296        int lastPriority = Integer.MIN_VALUE;
20297        ComponentName lastComponent = null;
20298        final int size = allHomeCandidates.size();
20299        for (int i = 0; i < size; i++) {
20300            final ResolveInfo ri = allHomeCandidates.get(i);
20301            if (ri.priority > lastPriority) {
20302                lastComponent = ri.activityInfo.getComponentName();
20303                lastPriority = ri.priority;
20304            } else if (ri.priority == lastPriority) {
20305                // Two components found with same priority.
20306                lastComponent = null;
20307            }
20308        }
20309        return lastComponent;
20310    }
20311
20312    private Intent getHomeIntent() {
20313        Intent intent = new Intent(Intent.ACTION_MAIN);
20314        intent.addCategory(Intent.CATEGORY_HOME);
20315        intent.addCategory(Intent.CATEGORY_DEFAULT);
20316        return intent;
20317    }
20318
20319    private IntentFilter getHomeFilter() {
20320        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20321        filter.addCategory(Intent.CATEGORY_HOME);
20322        filter.addCategory(Intent.CATEGORY_DEFAULT);
20323        return filter;
20324    }
20325
20326    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20327            int userId) {
20328        Intent intent  = getHomeIntent();
20329        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20330                PackageManager.GET_META_DATA, userId);
20331        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20332                true, false, false, userId);
20333
20334        allHomeCandidates.clear();
20335        if (list != null) {
20336            for (ResolveInfo ri : list) {
20337                allHomeCandidates.add(ri);
20338            }
20339        }
20340        return (preferred == null || preferred.activityInfo == null)
20341                ? null
20342                : new ComponentName(preferred.activityInfo.packageName,
20343                        preferred.activityInfo.name);
20344    }
20345
20346    @Override
20347    public void setHomeActivity(ComponentName comp, int userId) {
20348        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20349            return;
20350        }
20351        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20352        getHomeActivitiesAsUser(homeActivities, userId);
20353
20354        boolean found = false;
20355
20356        final int size = homeActivities.size();
20357        final ComponentName[] set = new ComponentName[size];
20358        for (int i = 0; i < size; i++) {
20359            final ResolveInfo candidate = homeActivities.get(i);
20360            final ActivityInfo info = candidate.activityInfo;
20361            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20362            set[i] = activityName;
20363            if (!found && activityName.equals(comp)) {
20364                found = true;
20365            }
20366        }
20367        if (!found) {
20368            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20369                    + userId);
20370        }
20371        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20372                set, comp, userId);
20373    }
20374
20375    private @Nullable String getSetupWizardPackageName() {
20376        final Intent intent = new Intent(Intent.ACTION_MAIN);
20377        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20378
20379        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20380                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20381                        | MATCH_DISABLED_COMPONENTS,
20382                UserHandle.myUserId());
20383        if (matches.size() == 1) {
20384            return matches.get(0).getComponentInfo().packageName;
20385        } else {
20386            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20387                    + ": matches=" + matches);
20388            return null;
20389        }
20390    }
20391
20392    private @Nullable String getStorageManagerPackageName() {
20393        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20394
20395        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20396                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20397                        | MATCH_DISABLED_COMPONENTS,
20398                UserHandle.myUserId());
20399        if (matches.size() == 1) {
20400            return matches.get(0).getComponentInfo().packageName;
20401        } else {
20402            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20403                    + matches.size() + ": matches=" + matches);
20404            return null;
20405        }
20406    }
20407
20408    @Override
20409    public String getSystemTextClassifierPackageName() {
20410        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20411    }
20412
20413    @Override
20414    public void setApplicationEnabledSetting(String appPackageName,
20415            int newState, int flags, int userId, String callingPackage) {
20416        if (!sUserManager.exists(userId)) return;
20417        if (callingPackage == null) {
20418            callingPackage = Integer.toString(Binder.getCallingUid());
20419        }
20420        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20421    }
20422
20423    @Override
20424    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20425        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20426        synchronized (mPackages) {
20427            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20428            if (pkgSetting != null) {
20429                pkgSetting.setUpdateAvailable(updateAvailable);
20430            }
20431        }
20432    }
20433
20434    @Override
20435    public void setComponentEnabledSetting(ComponentName componentName,
20436            int newState, int flags, int userId) {
20437        if (!sUserManager.exists(userId)) return;
20438        setEnabledSetting(componentName.getPackageName(),
20439                componentName.getClassName(), newState, flags, userId, null);
20440    }
20441
20442    private void setEnabledSetting(final String packageName, String className, int newState,
20443            final int flags, int userId, String callingPackage) {
20444        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20445              || newState == COMPONENT_ENABLED_STATE_ENABLED
20446              || newState == COMPONENT_ENABLED_STATE_DISABLED
20447              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20448              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20449            throw new IllegalArgumentException("Invalid new component state: "
20450                    + newState);
20451        }
20452        PackageSetting pkgSetting;
20453        final int callingUid = Binder.getCallingUid();
20454        final int permission;
20455        if (callingUid == Process.SYSTEM_UID) {
20456            permission = PackageManager.PERMISSION_GRANTED;
20457        } else {
20458            permission = mContext.checkCallingOrSelfPermission(
20459                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20460        }
20461        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20462                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20463        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20464        boolean sendNow = false;
20465        boolean isApp = (className == null);
20466        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20467        String componentName = isApp ? packageName : className;
20468        int packageUid = -1;
20469        ArrayList<String> components;
20470
20471        // reader
20472        synchronized (mPackages) {
20473            pkgSetting = mSettings.mPackages.get(packageName);
20474            if (pkgSetting == null) {
20475                if (!isCallerInstantApp) {
20476                    if (className == null) {
20477                        throw new IllegalArgumentException("Unknown package: " + packageName);
20478                    }
20479                    throw new IllegalArgumentException(
20480                            "Unknown component: " + packageName + "/" + className);
20481                } else {
20482                    // throw SecurityException to prevent leaking package information
20483                    throw new SecurityException(
20484                            "Attempt to change component state; "
20485                            + "pid=" + Binder.getCallingPid()
20486                            + ", uid=" + callingUid
20487                            + (className == null
20488                                    ? ", package=" + packageName
20489                                    : ", component=" + packageName + "/" + className));
20490                }
20491            }
20492        }
20493
20494        // Limit who can change which apps
20495        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20496            // Don't allow apps that don't have permission to modify other apps
20497            if (!allowedByPermission
20498                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20499                throw new SecurityException(
20500                        "Attempt to change component state; "
20501                        + "pid=" + Binder.getCallingPid()
20502                        + ", uid=" + callingUid
20503                        + (className == null
20504                                ? ", package=" + packageName
20505                                : ", component=" + packageName + "/" + className));
20506            }
20507            // Don't allow changing protected packages.
20508            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20509                throw new SecurityException("Cannot disable a protected package: " + packageName);
20510            }
20511        }
20512
20513        synchronized (mPackages) {
20514            if (callingUid == Process.SHELL_UID
20515                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20516                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20517                // unless it is a test package.
20518                int oldState = pkgSetting.getEnabled(userId);
20519                if (className == null
20520                        &&
20521                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20522                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20523                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20524                        &&
20525                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20526                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20527                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20528                    // ok
20529                } else {
20530                    throw new SecurityException(
20531                            "Shell cannot change component state for " + packageName + "/"
20532                                    + className + " to " + newState);
20533                }
20534            }
20535        }
20536        if (className == null) {
20537            // We're dealing with an application/package level state change
20538            synchronized (mPackages) {
20539                if (pkgSetting.getEnabled(userId) == newState) {
20540                    // Nothing to do
20541                    return;
20542                }
20543            }
20544            // If we're enabling a system stub, there's a little more work to do.
20545            // Prior to enabling the package, we need to decompress the APK(s) to the
20546            // data partition and then replace the version on the system partition.
20547            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20548            final boolean isSystemStub = deletedPkg.isStub
20549                    && deletedPkg.isSystem();
20550            if (isSystemStub
20551                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20552                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20553                final File codePath = decompressPackage(deletedPkg);
20554                if (codePath == null) {
20555                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20556                    return;
20557                }
20558                // TODO remove direct parsing of the package object during internal cleanup
20559                // of scan package
20560                // We need to call parse directly here for no other reason than we need
20561                // the new package in order to disable the old one [we use the information
20562                // for some internal optimization to optionally create a new package setting
20563                // object on replace]. However, we can't get the package from the scan
20564                // because the scan modifies live structures and we need to remove the
20565                // old [system] package from the system before a scan can be attempted.
20566                // Once scan is indempotent we can remove this parse and use the package
20567                // object we scanned, prior to adding it to package settings.
20568                final PackageParser pp = new PackageParser();
20569                pp.setSeparateProcesses(mSeparateProcesses);
20570                pp.setDisplayMetrics(mMetrics);
20571                pp.setCallback(mPackageParserCallback);
20572                final PackageParser.Package tmpPkg;
20573                try {
20574                    final @ParseFlags int parseFlags = mDefParseFlags
20575                            | PackageParser.PARSE_MUST_BE_APK
20576                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20577                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20578                } catch (PackageParserException e) {
20579                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20580                    return;
20581                }
20582                synchronized (mInstallLock) {
20583                    // Disable the stub and remove any package entries
20584                    removePackageLI(deletedPkg, true);
20585                    synchronized (mPackages) {
20586                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20587                    }
20588                    final PackageParser.Package pkg;
20589                    try (PackageFreezer freezer =
20590                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20591                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20592                                | PackageParser.PARSE_ENFORCE_CODE;
20593                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20594                                0 /*currentTime*/, null /*user*/);
20595                        prepareAppDataAfterInstallLIF(pkg);
20596                        synchronized (mPackages) {
20597                            try {
20598                                updateSharedLibrariesLPr(pkg, null);
20599                            } catch (PackageManagerException e) {
20600                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20601                            }
20602                            mPermissionManager.updatePermissions(
20603                                    pkg.packageName, pkg, true, mPackages.values(),
20604                                    mPermissionCallback);
20605                            mSettings.writeLPr();
20606                        }
20607                    } catch (PackageManagerException e) {
20608                        // Whoops! Something went wrong; try to roll back to the stub
20609                        Slog.w(TAG, "Failed to install compressed system package:"
20610                                + pkgSetting.name, e);
20611                        // Remove the failed install
20612                        removeCodePathLI(codePath);
20613
20614                        // Install the system package
20615                        try (PackageFreezer freezer =
20616                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20617                            synchronized (mPackages) {
20618                                // NOTE: The system package always needs to be enabled; even
20619                                // if it's for a compressed stub. If we don't, installing the
20620                                // system package fails during scan [scanning checks the disabled
20621                                // packages]. We will reverse this later, after we've "installed"
20622                                // the stub.
20623                                // This leaves us in a fragile state; the stub should never be
20624                                // enabled, so, cross your fingers and hope nothing goes wrong
20625                                // until we can disable the package later.
20626                                enableSystemPackageLPw(deletedPkg);
20627                            }
20628                            installPackageFromSystemLIF(deletedPkg.codePath,
20629                                    false /*isPrivileged*/, null /*allUserHandles*/,
20630                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20631                                    true /*writeSettings*/);
20632                        } catch (PackageManagerException pme) {
20633                            Slog.w(TAG, "Failed to restore system package:"
20634                                    + deletedPkg.packageName, pme);
20635                        } finally {
20636                            synchronized (mPackages) {
20637                                mSettings.disableSystemPackageLPw(
20638                                        deletedPkg.packageName, true /*replaced*/);
20639                                mSettings.writeLPr();
20640                            }
20641                        }
20642                        return;
20643                    }
20644                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20645                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20646                    mDexManager.notifyPackageUpdated(pkg.packageName,
20647                            pkg.baseCodePath, pkg.splitCodePaths);
20648                }
20649            }
20650            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20651                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20652                // Don't care about who enables an app.
20653                callingPackage = null;
20654            }
20655            synchronized (mPackages) {
20656                pkgSetting.setEnabled(newState, userId, callingPackage);
20657            }
20658        } else {
20659            synchronized (mPackages) {
20660                // We're dealing with a component level state change
20661                // First, verify that this is a valid class name.
20662                PackageParser.Package pkg = pkgSetting.pkg;
20663                if (pkg == null || !pkg.hasComponentClassName(className)) {
20664                    if (pkg != null &&
20665                            pkg.applicationInfo.targetSdkVersion >=
20666                                    Build.VERSION_CODES.JELLY_BEAN) {
20667                        throw new IllegalArgumentException("Component class " + className
20668                                + " does not exist in " + packageName);
20669                    } else {
20670                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20671                                + className + " does not exist in " + packageName);
20672                    }
20673                }
20674                switch (newState) {
20675                    case COMPONENT_ENABLED_STATE_ENABLED:
20676                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20677                            return;
20678                        }
20679                        break;
20680                    case COMPONENT_ENABLED_STATE_DISABLED:
20681                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20682                            return;
20683                        }
20684                        break;
20685                    case COMPONENT_ENABLED_STATE_DEFAULT:
20686                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20687                            return;
20688                        }
20689                        break;
20690                    default:
20691                        Slog.e(TAG, "Invalid new component state: " + newState);
20692                        return;
20693                }
20694            }
20695        }
20696        synchronized (mPackages) {
20697            scheduleWritePackageRestrictionsLocked(userId);
20698            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20699            final long callingId = Binder.clearCallingIdentity();
20700            try {
20701                updateInstantAppInstallerLocked(packageName);
20702            } finally {
20703                Binder.restoreCallingIdentity(callingId);
20704            }
20705            components = mPendingBroadcasts.get(userId, packageName);
20706            final boolean newPackage = components == null;
20707            if (newPackage) {
20708                components = new ArrayList<String>();
20709            }
20710            if (!components.contains(componentName)) {
20711                components.add(componentName);
20712            }
20713            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20714                sendNow = true;
20715                // Purge entry from pending broadcast list if another one exists already
20716                // since we are sending one right away.
20717                mPendingBroadcasts.remove(userId, packageName);
20718            } else {
20719                if (newPackage) {
20720                    mPendingBroadcasts.put(userId, packageName, components);
20721                }
20722                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20723                    // Schedule a message
20724                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20725                }
20726            }
20727        }
20728
20729        long callingId = Binder.clearCallingIdentity();
20730        try {
20731            if (sendNow) {
20732                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20733                sendPackageChangedBroadcast(packageName,
20734                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20735            }
20736        } finally {
20737            Binder.restoreCallingIdentity(callingId);
20738        }
20739    }
20740
20741    @Override
20742    public void flushPackageRestrictionsAsUser(int userId) {
20743        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20744            return;
20745        }
20746        if (!sUserManager.exists(userId)) {
20747            return;
20748        }
20749        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20750                false /* checkShell */, "flushPackageRestrictions");
20751        synchronized (mPackages) {
20752            mSettings.writePackageRestrictionsLPr(userId);
20753            mDirtyUsers.remove(userId);
20754            if (mDirtyUsers.isEmpty()) {
20755                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20756            }
20757        }
20758    }
20759
20760    private void sendPackageChangedBroadcast(String packageName,
20761            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20762        if (DEBUG_INSTALL)
20763            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20764                    + componentNames);
20765        Bundle extras = new Bundle(4);
20766        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20767        String nameList[] = new String[componentNames.size()];
20768        componentNames.toArray(nameList);
20769        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20770        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20771        extras.putInt(Intent.EXTRA_UID, packageUid);
20772        // If this is not reporting a change of the overall package, then only send it
20773        // to registered receivers.  We don't want to launch a swath of apps for every
20774        // little component state change.
20775        final int flags = !componentNames.contains(packageName)
20776                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20777        final int userId = UserHandle.getUserId(packageUid);
20778        final boolean isInstantApp = isInstantApp(packageName, userId);
20779        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20780        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20781        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20782                userIds, instantUserIds);
20783    }
20784
20785    @Override
20786    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20787        if (!sUserManager.exists(userId)) return;
20788        final int callingUid = Binder.getCallingUid();
20789        if (getInstantAppPackageName(callingUid) != null) {
20790            return;
20791        }
20792        final int permission = mContext.checkCallingOrSelfPermission(
20793                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20794        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20795        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20796                true /* requireFullPermission */, true /* checkShell */, "stop package");
20797        // writer
20798        synchronized (mPackages) {
20799            final PackageSetting ps = mSettings.mPackages.get(packageName);
20800            if (!filterAppAccessLPr(ps, callingUid, userId)
20801                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20802                            allowedByPermission, callingUid, userId)) {
20803                scheduleWritePackageRestrictionsLocked(userId);
20804            }
20805        }
20806    }
20807
20808    @Override
20809    public String getInstallerPackageName(String packageName) {
20810        final int callingUid = Binder.getCallingUid();
20811        synchronized (mPackages) {
20812            final PackageSetting ps = mSettings.mPackages.get(packageName);
20813            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20814                return null;
20815            }
20816            return mSettings.getInstallerPackageNameLPr(packageName);
20817        }
20818    }
20819
20820    public boolean isOrphaned(String packageName) {
20821        // reader
20822        synchronized (mPackages) {
20823            return mSettings.isOrphaned(packageName);
20824        }
20825    }
20826
20827    @Override
20828    public int getApplicationEnabledSetting(String packageName, int userId) {
20829        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20830        int callingUid = Binder.getCallingUid();
20831        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20832                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20833        // reader
20834        synchronized (mPackages) {
20835            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20836                return COMPONENT_ENABLED_STATE_DISABLED;
20837            }
20838            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20839        }
20840    }
20841
20842    @Override
20843    public int getComponentEnabledSetting(ComponentName component, int userId) {
20844        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20845        int callingUid = Binder.getCallingUid();
20846        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20847                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20848        synchronized (mPackages) {
20849            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20850                    component, TYPE_UNKNOWN, userId)) {
20851                return COMPONENT_ENABLED_STATE_DISABLED;
20852            }
20853            return mSettings.getComponentEnabledSettingLPr(component, userId);
20854        }
20855    }
20856
20857    @Override
20858    public void enterSafeMode() {
20859        enforceSystemOrRoot("Only the system can request entering safe mode");
20860
20861        if (!mSystemReady) {
20862            mSafeMode = true;
20863        }
20864    }
20865
20866    @Override
20867    public void systemReady() {
20868        enforceSystemOrRoot("Only the system can claim the system is ready");
20869
20870        mSystemReady = true;
20871        final ContentResolver resolver = mContext.getContentResolver();
20872        ContentObserver co = new ContentObserver(mHandler) {
20873            @Override
20874            public void onChange(boolean selfChange) {
20875                mWebInstantAppsDisabled =
20876                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20877                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20878            }
20879        };
20880        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20881                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20882                false, co, UserHandle.USER_SYSTEM);
20883        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20884                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20885        co.onChange(true);
20886
20887        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20888        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20889        // it is done.
20890        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20891            @Override
20892            public void onChange(boolean selfChange) {
20893                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20894                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20895                        oobEnabled == 1 ? "true" : "false");
20896            }
20897        };
20898        mContext.getContentResolver().registerContentObserver(
20899                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20900                UserHandle.USER_SYSTEM);
20901        // At boot, restore the value from the setting, which persists across reboot.
20902        privAppOobObserver.onChange(true);
20903
20904        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20905        // disabled after already being started.
20906        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20907                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20908
20909        // Read the compatibilty setting when the system is ready.
20910        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20911                mContext.getContentResolver(),
20912                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20913        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20914        if (DEBUG_SETTINGS) {
20915            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20916        }
20917
20918        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20919
20920        synchronized (mPackages) {
20921            // Verify that all of the preferred activity components actually
20922            // exist.  It is possible for applications to be updated and at
20923            // that point remove a previously declared activity component that
20924            // had been set as a preferred activity.  We try to clean this up
20925            // the next time we encounter that preferred activity, but it is
20926            // possible for the user flow to never be able to return to that
20927            // situation so here we do a sanity check to make sure we haven't
20928            // left any junk around.
20929            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20930            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20931                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20932                removed.clear();
20933                for (PreferredActivity pa : pir.filterSet()) {
20934                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20935                        removed.add(pa);
20936                    }
20937                }
20938                if (removed.size() > 0) {
20939                    for (int r=0; r<removed.size(); r++) {
20940                        PreferredActivity pa = removed.get(r);
20941                        Slog.w(TAG, "Removing dangling preferred activity: "
20942                                + pa.mPref.mComponent);
20943                        pir.removeFilter(pa);
20944                    }
20945                    mSettings.writePackageRestrictionsLPr(
20946                            mSettings.mPreferredActivities.keyAt(i));
20947                }
20948            }
20949
20950            for (int userId : UserManagerService.getInstance().getUserIds()) {
20951                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20952                    grantPermissionsUserIds = ArrayUtils.appendInt(
20953                            grantPermissionsUserIds, userId);
20954                }
20955            }
20956        }
20957        sUserManager.systemReady();
20958        // If we upgraded grant all default permissions before kicking off.
20959        for (int userId : grantPermissionsUserIds) {
20960            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20961        }
20962
20963        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20964            // If we did not grant default permissions, we preload from this the
20965            // default permission exceptions lazily to ensure we don't hit the
20966            // disk on a new user creation.
20967            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20968        }
20969
20970        // Now that we've scanned all packages, and granted any default
20971        // permissions, ensure permissions are updated. Beware of dragons if you
20972        // try optimizing this.
20973        synchronized (mPackages) {
20974            mPermissionManager.updateAllPermissions(
20975                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20976                    mPermissionCallback);
20977        }
20978
20979        // Kick off any messages waiting for system ready
20980        if (mPostSystemReadyMessages != null) {
20981            for (Message msg : mPostSystemReadyMessages) {
20982                msg.sendToTarget();
20983            }
20984            mPostSystemReadyMessages = null;
20985        }
20986
20987        // Watch for external volumes that come and go over time
20988        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20989        storage.registerListener(mStorageListener);
20990
20991        mInstallerService.systemReady();
20992        mPackageDexOptimizer.systemReady();
20993
20994        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20995                StorageManagerInternal.class);
20996        StorageManagerInternal.addExternalStoragePolicy(
20997                new StorageManagerInternal.ExternalStorageMountPolicy() {
20998            @Override
20999            public int getMountMode(int uid, String packageName) {
21000                if (Process.isIsolated(uid)) {
21001                    return Zygote.MOUNT_EXTERNAL_NONE;
21002                }
21003                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21004                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21005                }
21006                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21007                    return Zygote.MOUNT_EXTERNAL_READ;
21008                }
21009                return Zygote.MOUNT_EXTERNAL_WRITE;
21010            }
21011
21012            @Override
21013            public boolean hasExternalStorage(int uid, String packageName) {
21014                return true;
21015            }
21016        });
21017
21018        // Now that we're mostly running, clean up stale users and apps
21019        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21020        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21021
21022        mPermissionManager.systemReady();
21023
21024        if (mInstantAppResolverConnection != null) {
21025            mContext.registerReceiver(new BroadcastReceiver() {
21026                @Override
21027                public void onReceive(Context context, Intent intent) {
21028                    mInstantAppResolverConnection.optimisticBind();
21029                    mContext.unregisterReceiver(this);
21030                }
21031            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21032        }
21033    }
21034
21035    public void waitForAppDataPrepared() {
21036        if (mPrepareAppDataFuture == null) {
21037            return;
21038        }
21039        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21040        mPrepareAppDataFuture = null;
21041    }
21042
21043    @Override
21044    public boolean isSafeMode() {
21045        // allow instant applications
21046        return mSafeMode;
21047    }
21048
21049    @Override
21050    public boolean hasSystemUidErrors() {
21051        // allow instant applications
21052        return mHasSystemUidErrors;
21053    }
21054
21055    static String arrayToString(int[] array) {
21056        StringBuffer buf = new StringBuffer(128);
21057        buf.append('[');
21058        if (array != null) {
21059            for (int i=0; i<array.length; i++) {
21060                if (i > 0) buf.append(", ");
21061                buf.append(array[i]);
21062            }
21063        }
21064        buf.append(']');
21065        return buf.toString();
21066    }
21067
21068    @Override
21069    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21070            FileDescriptor err, String[] args, ShellCallback callback,
21071            ResultReceiver resultReceiver) {
21072        (new PackageManagerShellCommand(this)).exec(
21073                this, in, out, err, args, callback, resultReceiver);
21074    }
21075
21076    @Override
21077    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21078        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21079
21080        DumpState dumpState = new DumpState();
21081        boolean fullPreferred = false;
21082        boolean checkin = false;
21083
21084        String packageName = null;
21085        ArraySet<String> permissionNames = null;
21086
21087        int opti = 0;
21088        while (opti < args.length) {
21089            String opt = args[opti];
21090            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21091                break;
21092            }
21093            opti++;
21094
21095            if ("-a".equals(opt)) {
21096                // Right now we only know how to print all.
21097            } else if ("-h".equals(opt)) {
21098                pw.println("Package manager dump options:");
21099                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21100                pw.println("    --checkin: dump for a checkin");
21101                pw.println("    -f: print details of intent filters");
21102                pw.println("    -h: print this help");
21103                pw.println("  cmd may be one of:");
21104                pw.println("    l[ibraries]: list known shared libraries");
21105                pw.println("    f[eatures]: list device features");
21106                pw.println("    k[eysets]: print known keysets");
21107                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21108                pw.println("    perm[issions]: dump permissions");
21109                pw.println("    permission [name ...]: dump declaration and use of given permission");
21110                pw.println("    pref[erred]: print preferred package settings");
21111                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21112                pw.println("    prov[iders]: dump content providers");
21113                pw.println("    p[ackages]: dump installed packages");
21114                pw.println("    s[hared-users]: dump shared user IDs");
21115                pw.println("    m[essages]: print collected runtime messages");
21116                pw.println("    v[erifiers]: print package verifier info");
21117                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21118                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21119                pw.println("    version: print database version info");
21120                pw.println("    write: write current settings now");
21121                pw.println("    installs: details about install sessions");
21122                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21123                pw.println("    dexopt: dump dexopt state");
21124                pw.println("    compiler-stats: dump compiler statistics");
21125                pw.println("    service-permissions: dump permissions required by services");
21126                pw.println("    <package.name>: info about given package");
21127                return;
21128            } else if ("--checkin".equals(opt)) {
21129                checkin = true;
21130            } else if ("-f".equals(opt)) {
21131                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21132            } else if ("--proto".equals(opt)) {
21133                dumpProto(fd);
21134                return;
21135            } else {
21136                pw.println("Unknown argument: " + opt + "; use -h for help");
21137            }
21138        }
21139
21140        // Is the caller requesting to dump a particular piece of data?
21141        if (opti < args.length) {
21142            String cmd = args[opti];
21143            opti++;
21144            // Is this a package name?
21145            if ("android".equals(cmd) || cmd.contains(".")) {
21146                packageName = cmd;
21147                // When dumping a single package, we always dump all of its
21148                // filter information since the amount of data will be reasonable.
21149                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21150            } else if ("check-permission".equals(cmd)) {
21151                if (opti >= args.length) {
21152                    pw.println("Error: check-permission missing permission argument");
21153                    return;
21154                }
21155                String perm = args[opti];
21156                opti++;
21157                if (opti >= args.length) {
21158                    pw.println("Error: check-permission missing package argument");
21159                    return;
21160                }
21161
21162                String pkg = args[opti];
21163                opti++;
21164                int user = UserHandle.getUserId(Binder.getCallingUid());
21165                if (opti < args.length) {
21166                    try {
21167                        user = Integer.parseInt(args[opti]);
21168                    } catch (NumberFormatException e) {
21169                        pw.println("Error: check-permission user argument is not a number: "
21170                                + args[opti]);
21171                        return;
21172                    }
21173                }
21174
21175                // Normalize package name to handle renamed packages and static libs
21176                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21177
21178                pw.println(checkPermission(perm, pkg, user));
21179                return;
21180            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21181                dumpState.setDump(DumpState.DUMP_LIBS);
21182            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21183                dumpState.setDump(DumpState.DUMP_FEATURES);
21184            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21185                if (opti >= args.length) {
21186                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21187                            | DumpState.DUMP_SERVICE_RESOLVERS
21188                            | DumpState.DUMP_RECEIVER_RESOLVERS
21189                            | DumpState.DUMP_CONTENT_RESOLVERS);
21190                } else {
21191                    while (opti < args.length) {
21192                        String name = args[opti];
21193                        if ("a".equals(name) || "activity".equals(name)) {
21194                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21195                        } else if ("s".equals(name) || "service".equals(name)) {
21196                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21197                        } else if ("r".equals(name) || "receiver".equals(name)) {
21198                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21199                        } else if ("c".equals(name) || "content".equals(name)) {
21200                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21201                        } else {
21202                            pw.println("Error: unknown resolver table type: " + name);
21203                            return;
21204                        }
21205                        opti++;
21206                    }
21207                }
21208            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21209                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21210            } else if ("permission".equals(cmd)) {
21211                if (opti >= args.length) {
21212                    pw.println("Error: permission requires permission name");
21213                    return;
21214                }
21215                permissionNames = new ArraySet<>();
21216                while (opti < args.length) {
21217                    permissionNames.add(args[opti]);
21218                    opti++;
21219                }
21220                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21221                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21222            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21223                dumpState.setDump(DumpState.DUMP_PREFERRED);
21224            } else if ("preferred-xml".equals(cmd)) {
21225                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21226                if (opti < args.length && "--full".equals(args[opti])) {
21227                    fullPreferred = true;
21228                    opti++;
21229                }
21230            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21231                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21232            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21233                dumpState.setDump(DumpState.DUMP_PACKAGES);
21234            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21235                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21236            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21237                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21238            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21239                dumpState.setDump(DumpState.DUMP_MESSAGES);
21240            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21241                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21242            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21243                    || "intent-filter-verifiers".equals(cmd)) {
21244                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21245            } else if ("version".equals(cmd)) {
21246                dumpState.setDump(DumpState.DUMP_VERSION);
21247            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21248                dumpState.setDump(DumpState.DUMP_KEYSETS);
21249            } else if ("installs".equals(cmd)) {
21250                dumpState.setDump(DumpState.DUMP_INSTALLS);
21251            } else if ("frozen".equals(cmd)) {
21252                dumpState.setDump(DumpState.DUMP_FROZEN);
21253            } else if ("volumes".equals(cmd)) {
21254                dumpState.setDump(DumpState.DUMP_VOLUMES);
21255            } else if ("dexopt".equals(cmd)) {
21256                dumpState.setDump(DumpState.DUMP_DEXOPT);
21257            } else if ("compiler-stats".equals(cmd)) {
21258                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21259            } else if ("changes".equals(cmd)) {
21260                dumpState.setDump(DumpState.DUMP_CHANGES);
21261            } else if ("service-permissions".equals(cmd)) {
21262                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21263            } else if ("write".equals(cmd)) {
21264                synchronized (mPackages) {
21265                    mSettings.writeLPr();
21266                    pw.println("Settings written.");
21267                    return;
21268                }
21269            }
21270        }
21271
21272        if (checkin) {
21273            pw.println("vers,1");
21274        }
21275
21276        // reader
21277        synchronized (mPackages) {
21278            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21279                if (!checkin) {
21280                    if (dumpState.onTitlePrinted())
21281                        pw.println();
21282                    pw.println("Database versions:");
21283                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21284                }
21285            }
21286
21287            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21288                if (!checkin) {
21289                    if (dumpState.onTitlePrinted())
21290                        pw.println();
21291                    pw.println("Verifiers:");
21292                    pw.print("  Required: ");
21293                    pw.print(mRequiredVerifierPackage);
21294                    pw.print(" (uid=");
21295                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21296                            UserHandle.USER_SYSTEM));
21297                    pw.println(")");
21298                } else if (mRequiredVerifierPackage != null) {
21299                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21300                    pw.print(",");
21301                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21302                            UserHandle.USER_SYSTEM));
21303                }
21304            }
21305
21306            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21307                    packageName == null) {
21308                if (mIntentFilterVerifierComponent != null) {
21309                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21310                    if (!checkin) {
21311                        if (dumpState.onTitlePrinted())
21312                            pw.println();
21313                        pw.println("Intent Filter Verifier:");
21314                        pw.print("  Using: ");
21315                        pw.print(verifierPackageName);
21316                        pw.print(" (uid=");
21317                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21318                                UserHandle.USER_SYSTEM));
21319                        pw.println(")");
21320                    } else if (verifierPackageName != null) {
21321                        pw.print("ifv,"); pw.print(verifierPackageName);
21322                        pw.print(",");
21323                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21324                                UserHandle.USER_SYSTEM));
21325                    }
21326                } else {
21327                    pw.println();
21328                    pw.println("No Intent Filter Verifier available!");
21329                }
21330            }
21331
21332            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21333                boolean printedHeader = false;
21334                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21335                while (it.hasNext()) {
21336                    String libName = it.next();
21337                    LongSparseArray<SharedLibraryEntry> versionedLib
21338                            = mSharedLibraries.get(libName);
21339                    if (versionedLib == null) {
21340                        continue;
21341                    }
21342                    final int versionCount = versionedLib.size();
21343                    for (int i = 0; i < versionCount; i++) {
21344                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21345                        if (!checkin) {
21346                            if (!printedHeader) {
21347                                if (dumpState.onTitlePrinted())
21348                                    pw.println();
21349                                pw.println("Libraries:");
21350                                printedHeader = true;
21351                            }
21352                            pw.print("  ");
21353                        } else {
21354                            pw.print("lib,");
21355                        }
21356                        pw.print(libEntry.info.getName());
21357                        if (libEntry.info.isStatic()) {
21358                            pw.print(" version=" + libEntry.info.getLongVersion());
21359                        }
21360                        if (!checkin) {
21361                            pw.print(" -> ");
21362                        }
21363                        if (libEntry.path != null) {
21364                            pw.print(" (jar) ");
21365                            pw.print(libEntry.path);
21366                        } else {
21367                            pw.print(" (apk) ");
21368                            pw.print(libEntry.apk);
21369                        }
21370                        pw.println();
21371                    }
21372                }
21373            }
21374
21375            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21376                if (dumpState.onTitlePrinted())
21377                    pw.println();
21378                if (!checkin) {
21379                    pw.println("Features:");
21380                }
21381
21382                synchronized (mAvailableFeatures) {
21383                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21384                        if (checkin) {
21385                            pw.print("feat,");
21386                            pw.print(feat.name);
21387                            pw.print(",");
21388                            pw.println(feat.version);
21389                        } else {
21390                            pw.print("  ");
21391                            pw.print(feat.name);
21392                            if (feat.version > 0) {
21393                                pw.print(" version=");
21394                                pw.print(feat.version);
21395                            }
21396                            pw.println();
21397                        }
21398                    }
21399                }
21400            }
21401
21402            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21403                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21404                        : "Activity Resolver Table:", "  ", packageName,
21405                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21406                    dumpState.setTitlePrinted(true);
21407                }
21408            }
21409            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21410                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21411                        : "Receiver Resolver Table:", "  ", packageName,
21412                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21413                    dumpState.setTitlePrinted(true);
21414                }
21415            }
21416            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21417                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21418                        : "Service Resolver Table:", "  ", packageName,
21419                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21420                    dumpState.setTitlePrinted(true);
21421                }
21422            }
21423            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21424                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21425                        : "Provider Resolver Table:", "  ", packageName,
21426                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21427                    dumpState.setTitlePrinted(true);
21428                }
21429            }
21430
21431            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21432                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21433                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21434                    int user = mSettings.mPreferredActivities.keyAt(i);
21435                    if (pir.dump(pw,
21436                            dumpState.getTitlePrinted()
21437                                ? "\nPreferred Activities User " + user + ":"
21438                                : "Preferred Activities User " + user + ":", "  ",
21439                            packageName, true, false)) {
21440                        dumpState.setTitlePrinted(true);
21441                    }
21442                }
21443            }
21444
21445            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21446                pw.flush();
21447                FileOutputStream fout = new FileOutputStream(fd);
21448                BufferedOutputStream str = new BufferedOutputStream(fout);
21449                XmlSerializer serializer = new FastXmlSerializer();
21450                try {
21451                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21452                    serializer.startDocument(null, true);
21453                    serializer.setFeature(
21454                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21455                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21456                    serializer.endDocument();
21457                    serializer.flush();
21458                } catch (IllegalArgumentException e) {
21459                    pw.println("Failed writing: " + e);
21460                } catch (IllegalStateException e) {
21461                    pw.println("Failed writing: " + e);
21462                } catch (IOException e) {
21463                    pw.println("Failed writing: " + e);
21464                }
21465            }
21466
21467            if (!checkin
21468                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21469                    && packageName == null) {
21470                pw.println();
21471                int count = mSettings.mPackages.size();
21472                if (count == 0) {
21473                    pw.println("No applications!");
21474                    pw.println();
21475                } else {
21476                    final String prefix = "  ";
21477                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21478                    if (allPackageSettings.size() == 0) {
21479                        pw.println("No domain preferred apps!");
21480                        pw.println();
21481                    } else {
21482                        pw.println("App verification status:");
21483                        pw.println();
21484                        count = 0;
21485                        for (PackageSetting ps : allPackageSettings) {
21486                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21487                            if (ivi == null || ivi.getPackageName() == null) continue;
21488                            pw.println(prefix + "Package: " + ivi.getPackageName());
21489                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21490                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21491                            pw.println();
21492                            count++;
21493                        }
21494                        if (count == 0) {
21495                            pw.println(prefix + "No app verification established.");
21496                            pw.println();
21497                        }
21498                        for (int userId : sUserManager.getUserIds()) {
21499                            pw.println("App linkages for user " + userId + ":");
21500                            pw.println();
21501                            count = 0;
21502                            for (PackageSetting ps : allPackageSettings) {
21503                                final long status = ps.getDomainVerificationStatusForUser(userId);
21504                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21505                                        && !DEBUG_DOMAIN_VERIFICATION) {
21506                                    continue;
21507                                }
21508                                pw.println(prefix + "Package: " + ps.name);
21509                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21510                                String statusStr = IntentFilterVerificationInfo.
21511                                        getStatusStringFromValue(status);
21512                                pw.println(prefix + "Status:  " + statusStr);
21513                                pw.println();
21514                                count++;
21515                            }
21516                            if (count == 0) {
21517                                pw.println(prefix + "No configured app linkages.");
21518                                pw.println();
21519                            }
21520                        }
21521                    }
21522                }
21523            }
21524
21525            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21526                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21527            }
21528
21529            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21530                boolean printedSomething = false;
21531                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21532                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21533                        continue;
21534                    }
21535                    if (!printedSomething) {
21536                        if (dumpState.onTitlePrinted())
21537                            pw.println();
21538                        pw.println("Registered ContentProviders:");
21539                        printedSomething = true;
21540                    }
21541                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21542                    pw.print("    "); pw.println(p.toString());
21543                }
21544                printedSomething = false;
21545                for (Map.Entry<String, PackageParser.Provider> entry :
21546                        mProvidersByAuthority.entrySet()) {
21547                    PackageParser.Provider p = entry.getValue();
21548                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21549                        continue;
21550                    }
21551                    if (!printedSomething) {
21552                        if (dumpState.onTitlePrinted())
21553                            pw.println();
21554                        pw.println("ContentProvider Authorities:");
21555                        printedSomething = true;
21556                    }
21557                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21558                    pw.print("    "); pw.println(p.toString());
21559                    if (p.info != null && p.info.applicationInfo != null) {
21560                        final String appInfo = p.info.applicationInfo.toString();
21561                        pw.print("      applicationInfo="); pw.println(appInfo);
21562                    }
21563                }
21564            }
21565
21566            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21567                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21568            }
21569
21570            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21571                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21572            }
21573
21574            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21575                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21576            }
21577
21578            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21579                if (dumpState.onTitlePrinted()) pw.println();
21580                pw.println("Package Changes:");
21581                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21582                final int K = mChangedPackages.size();
21583                for (int i = 0; i < K; i++) {
21584                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21585                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21586                    final int N = changes.size();
21587                    if (N == 0) {
21588                        pw.print("    "); pw.println("No packages changed");
21589                    } else {
21590                        for (int j = 0; j < N; j++) {
21591                            final String pkgName = changes.valueAt(j);
21592                            final int sequenceNumber = changes.keyAt(j);
21593                            pw.print("    ");
21594                            pw.print("seq=");
21595                            pw.print(sequenceNumber);
21596                            pw.print(", package=");
21597                            pw.println(pkgName);
21598                        }
21599                    }
21600                }
21601            }
21602
21603            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21604                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21605            }
21606
21607            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21608                // XXX should handle packageName != null by dumping only install data that
21609                // the given package is involved with.
21610                if (dumpState.onTitlePrinted()) pw.println();
21611
21612                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21613                    ipw.println();
21614                    ipw.println("Frozen packages:");
21615                    ipw.increaseIndent();
21616                    if (mFrozenPackages.size() == 0) {
21617                        ipw.println("(none)");
21618                    } else {
21619                        for (int i = 0; i < mFrozenPackages.size(); i++) {
21620                            ipw.println(mFrozenPackages.valueAt(i));
21621                        }
21622                    }
21623                    ipw.decreaseIndent();
21624                }
21625            }
21626
21627            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21628                if (dumpState.onTitlePrinted()) pw.println();
21629
21630                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21631                    ipw.println();
21632                    ipw.println("Loaded volumes:");
21633                    ipw.increaseIndent();
21634                    if (mLoadedVolumes.size() == 0) {
21635                        ipw.println("(none)");
21636                    } else {
21637                        for (int i = 0; i < mLoadedVolumes.size(); i++) {
21638                            ipw.println(mLoadedVolumes.valueAt(i));
21639                        }
21640                    }
21641                    ipw.decreaseIndent();
21642                }
21643            }
21644
21645            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21646                    && packageName == null) {
21647                if (dumpState.onTitlePrinted()) pw.println();
21648                pw.println("Service permissions:");
21649
21650                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21651                while (filterIterator.hasNext()) {
21652                    final ServiceIntentInfo info = filterIterator.next();
21653                    final ServiceInfo serviceInfo = info.service.info;
21654                    final String permission = serviceInfo.permission;
21655                    if (permission != null) {
21656                        pw.print("    ");
21657                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21658                        pw.print(": ");
21659                        pw.println(permission);
21660                    }
21661                }
21662            }
21663
21664            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21665                if (dumpState.onTitlePrinted()) pw.println();
21666                dumpDexoptStateLPr(pw, packageName);
21667            }
21668
21669            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21670                if (dumpState.onTitlePrinted()) pw.println();
21671                dumpCompilerStatsLPr(pw, packageName);
21672            }
21673
21674            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21675                if (dumpState.onTitlePrinted()) pw.println();
21676                mSettings.dumpReadMessagesLPr(pw, dumpState);
21677
21678                pw.println();
21679                pw.println("Package warning messages:");
21680                dumpCriticalInfo(pw, null);
21681            }
21682
21683            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21684                dumpCriticalInfo(pw, "msg,");
21685            }
21686        }
21687
21688        // PackageInstaller should be called outside of mPackages lock
21689        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21690            // XXX should handle packageName != null by dumping only install data that
21691            // the given package is involved with.
21692            if (dumpState.onTitlePrinted()) pw.println();
21693            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21694        }
21695    }
21696
21697    private void dumpProto(FileDescriptor fd) {
21698        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21699
21700        synchronized (mPackages) {
21701            final long requiredVerifierPackageToken =
21702                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21703            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21704            proto.write(
21705                    PackageServiceDumpProto.PackageShortProto.UID,
21706                    getPackageUid(
21707                            mRequiredVerifierPackage,
21708                            MATCH_DEBUG_TRIAGED_MISSING,
21709                            UserHandle.USER_SYSTEM));
21710            proto.end(requiredVerifierPackageToken);
21711
21712            if (mIntentFilterVerifierComponent != null) {
21713                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21714                final long verifierPackageToken =
21715                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21716                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21717                proto.write(
21718                        PackageServiceDumpProto.PackageShortProto.UID,
21719                        getPackageUid(
21720                                verifierPackageName,
21721                                MATCH_DEBUG_TRIAGED_MISSING,
21722                                UserHandle.USER_SYSTEM));
21723                proto.end(verifierPackageToken);
21724            }
21725
21726            dumpSharedLibrariesProto(proto);
21727            dumpFeaturesProto(proto);
21728            mSettings.dumpPackagesProto(proto);
21729            mSettings.dumpSharedUsersProto(proto);
21730            dumpCriticalInfo(proto);
21731        }
21732        proto.flush();
21733    }
21734
21735    private void dumpFeaturesProto(ProtoOutputStream proto) {
21736        synchronized (mAvailableFeatures) {
21737            final int count = mAvailableFeatures.size();
21738            for (int i = 0; i < count; i++) {
21739                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21740            }
21741        }
21742    }
21743
21744    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21745        final int count = mSharedLibraries.size();
21746        for (int i = 0; i < count; i++) {
21747            final String libName = mSharedLibraries.keyAt(i);
21748            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21749            if (versionedLib == null) {
21750                continue;
21751            }
21752            final int versionCount = versionedLib.size();
21753            for (int j = 0; j < versionCount; j++) {
21754                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21755                final long sharedLibraryToken =
21756                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21757                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21758                final boolean isJar = (libEntry.path != null);
21759                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21760                if (isJar) {
21761                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21762                } else {
21763                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21764                }
21765                proto.end(sharedLibraryToken);
21766            }
21767        }
21768    }
21769
21770    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21771        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21772            ipw.println();
21773            ipw.println("Dexopt state:");
21774            ipw.increaseIndent();
21775            Collection<PackageParser.Package> packages = null;
21776            if (packageName != null) {
21777                PackageParser.Package targetPackage = mPackages.get(packageName);
21778                if (targetPackage != null) {
21779                    packages = Collections.singletonList(targetPackage);
21780                } else {
21781                    ipw.println("Unable to find package: " + packageName);
21782                    return;
21783                }
21784            } else {
21785                packages = mPackages.values();
21786            }
21787
21788            for (PackageParser.Package pkg : packages) {
21789                ipw.println("[" + pkg.packageName + "]");
21790                ipw.increaseIndent();
21791                mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21792                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21793                ipw.decreaseIndent();
21794            }
21795        }
21796    }
21797
21798    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21799        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21800            ipw.println();
21801            ipw.println("Compiler stats:");
21802            ipw.increaseIndent();
21803            Collection<PackageParser.Package> packages = null;
21804            if (packageName != null) {
21805                PackageParser.Package targetPackage = mPackages.get(packageName);
21806                if (targetPackage != null) {
21807                    packages = Collections.singletonList(targetPackage);
21808                } else {
21809                    ipw.println("Unable to find package: " + packageName);
21810                    return;
21811                }
21812            } else {
21813                packages = mPackages.values();
21814            }
21815
21816            for (PackageParser.Package pkg : packages) {
21817                ipw.println("[" + pkg.packageName + "]");
21818                ipw.increaseIndent();
21819
21820                CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21821                if (stats == null) {
21822                    ipw.println("(No recorded stats)");
21823                } else {
21824                    stats.dump(ipw);
21825                }
21826                ipw.decreaseIndent();
21827            }
21828        }
21829    }
21830
21831    private String dumpDomainString(String packageName) {
21832        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21833                .getList();
21834        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21835
21836        ArraySet<String> result = new ArraySet<>();
21837        if (iviList.size() > 0) {
21838            for (IntentFilterVerificationInfo ivi : iviList) {
21839                for (String host : ivi.getDomains()) {
21840                    result.add(host);
21841                }
21842            }
21843        }
21844        if (filters != null && filters.size() > 0) {
21845            for (IntentFilter filter : filters) {
21846                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21847                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21848                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21849                    result.addAll(filter.getHostsList());
21850                }
21851            }
21852        }
21853
21854        StringBuilder sb = new StringBuilder(result.size() * 16);
21855        for (String domain : result) {
21856            if (sb.length() > 0) sb.append(" ");
21857            sb.append(domain);
21858        }
21859        return sb.toString();
21860    }
21861
21862    // ------- apps on sdcard specific code -------
21863    static final boolean DEBUG_SD_INSTALL = false;
21864
21865    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21866
21867    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21868
21869    private boolean mMediaMounted = false;
21870
21871    static String getEncryptKey() {
21872        try {
21873            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21874                    SD_ENCRYPTION_KEYSTORE_NAME);
21875            if (sdEncKey == null) {
21876                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21877                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21878                if (sdEncKey == null) {
21879                    Slog.e(TAG, "Failed to create encryption keys");
21880                    return null;
21881                }
21882            }
21883            return sdEncKey;
21884        } catch (NoSuchAlgorithmException nsae) {
21885            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21886            return null;
21887        } catch (IOException ioe) {
21888            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21889            return null;
21890        }
21891    }
21892
21893    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21894            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21895        final int size = infos.size();
21896        final String[] packageNames = new String[size];
21897        final int[] packageUids = new int[size];
21898        for (int i = 0; i < size; i++) {
21899            final ApplicationInfo info = infos.get(i);
21900            packageNames[i] = info.packageName;
21901            packageUids[i] = info.uid;
21902        }
21903        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21904                finishedReceiver);
21905    }
21906
21907    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21908            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21909        sendResourcesChangedBroadcast(mediaStatus, replacing,
21910                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21911    }
21912
21913    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21914            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21915        int size = pkgList.length;
21916        if (size > 0) {
21917            // Send broadcasts here
21918            Bundle extras = new Bundle();
21919            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21920            if (uidArr != null) {
21921                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21922            }
21923            if (replacing) {
21924                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21925            }
21926            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21927                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21928            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21929        }
21930    }
21931
21932    private void loadPrivatePackages(final VolumeInfo vol) {
21933        mHandler.post(new Runnable() {
21934            @Override
21935            public void run() {
21936                loadPrivatePackagesInner(vol);
21937            }
21938        });
21939    }
21940
21941    private void loadPrivatePackagesInner(VolumeInfo vol) {
21942        final String volumeUuid = vol.fsUuid;
21943        if (TextUtils.isEmpty(volumeUuid)) {
21944            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21945            return;
21946        }
21947
21948        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21949        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21950        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21951
21952        final VersionInfo ver;
21953        final List<PackageSetting> packages;
21954        synchronized (mPackages) {
21955            ver = mSettings.findOrCreateVersion(volumeUuid);
21956            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21957        }
21958
21959        for (PackageSetting ps : packages) {
21960            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21961            synchronized (mInstallLock) {
21962                final PackageParser.Package pkg;
21963                try {
21964                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21965                    loaded.add(pkg.applicationInfo);
21966
21967                } catch (PackageManagerException e) {
21968                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21969                }
21970
21971                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21972                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21973                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21974                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21975                }
21976            }
21977        }
21978
21979        // Reconcile app data for all started/unlocked users
21980        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21981        final UserManager um = mContext.getSystemService(UserManager.class);
21982        UserManagerInternal umInternal = getUserManagerInternal();
21983        for (UserInfo user : um.getUsers()) {
21984            final int flags;
21985            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21986                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21987            } else if (umInternal.isUserRunning(user.id)) {
21988                flags = StorageManager.FLAG_STORAGE_DE;
21989            } else {
21990                continue;
21991            }
21992
21993            try {
21994                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21995                synchronized (mInstallLock) {
21996                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21997                }
21998            } catch (IllegalStateException e) {
21999                // Device was probably ejected, and we'll process that event momentarily
22000                Slog.w(TAG, "Failed to prepare storage: " + e);
22001            }
22002        }
22003
22004        synchronized (mPackages) {
22005            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22006            if (sdkUpdated) {
22007                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22008                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22009            }
22010            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22011                    mPermissionCallback);
22012
22013            // Yay, everything is now upgraded
22014            ver.forceCurrent();
22015
22016            mSettings.writeLPr();
22017        }
22018
22019        for (PackageFreezer freezer : freezers) {
22020            freezer.close();
22021        }
22022
22023        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22024        sendResourcesChangedBroadcast(true, false, loaded, null);
22025        mLoadedVolumes.add(vol.getId());
22026    }
22027
22028    private void unloadPrivatePackages(final VolumeInfo vol) {
22029        mHandler.post(new Runnable() {
22030            @Override
22031            public void run() {
22032                unloadPrivatePackagesInner(vol);
22033            }
22034        });
22035    }
22036
22037    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22038        final String volumeUuid = vol.fsUuid;
22039        if (TextUtils.isEmpty(volumeUuid)) {
22040            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22041            return;
22042        }
22043
22044        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22045        synchronized (mInstallLock) {
22046        synchronized (mPackages) {
22047            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22048            for (PackageSetting ps : packages) {
22049                if (ps.pkg == null) continue;
22050
22051                final ApplicationInfo info = ps.pkg.applicationInfo;
22052                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22053                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22054
22055                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22056                        "unloadPrivatePackagesInner")) {
22057                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22058                            false, null)) {
22059                        unloaded.add(info);
22060                    } else {
22061                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22062                    }
22063                }
22064
22065                // Try very hard to release any references to this package
22066                // so we don't risk the system server being killed due to
22067                // open FDs
22068                AttributeCache.instance().removePackage(ps.name);
22069            }
22070
22071            mSettings.writeLPr();
22072        }
22073        }
22074
22075        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22076        sendResourcesChangedBroadcast(false, false, unloaded, null);
22077        mLoadedVolumes.remove(vol.getId());
22078
22079        // Try very hard to release any references to this path so we don't risk
22080        // the system server being killed due to open FDs
22081        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22082
22083        for (int i = 0; i < 3; i++) {
22084            System.gc();
22085            System.runFinalization();
22086        }
22087    }
22088
22089    private void assertPackageKnown(String volumeUuid, String packageName)
22090            throws PackageManagerException {
22091        synchronized (mPackages) {
22092            // Normalize package name to handle renamed packages
22093            packageName = normalizePackageNameLPr(packageName);
22094
22095            final PackageSetting ps = mSettings.mPackages.get(packageName);
22096            if (ps == null) {
22097                throw new PackageManagerException("Package " + packageName + " is unknown");
22098            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22099                throw new PackageManagerException(
22100                        "Package " + packageName + " found on unknown volume " + volumeUuid
22101                                + "; expected volume " + ps.volumeUuid);
22102            }
22103        }
22104    }
22105
22106    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22107            throws PackageManagerException {
22108        synchronized (mPackages) {
22109            // Normalize package name to handle renamed packages
22110            packageName = normalizePackageNameLPr(packageName);
22111
22112            final PackageSetting ps = mSettings.mPackages.get(packageName);
22113            if (ps == null) {
22114                throw new PackageManagerException("Package " + packageName + " is unknown");
22115            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22116                throw new PackageManagerException(
22117                        "Package " + packageName + " found on unknown volume " + volumeUuid
22118                                + "; expected volume " + ps.volumeUuid);
22119            } else if (!ps.getInstalled(userId)) {
22120                throw new PackageManagerException(
22121                        "Package " + packageName + " not installed for user " + userId);
22122            }
22123        }
22124    }
22125
22126    private List<String> collectAbsoluteCodePaths() {
22127        synchronized (mPackages) {
22128            List<String> codePaths = new ArrayList<>();
22129            final int packageCount = mSettings.mPackages.size();
22130            for (int i = 0; i < packageCount; i++) {
22131                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22132                codePaths.add(ps.codePath.getAbsolutePath());
22133            }
22134            return codePaths;
22135        }
22136    }
22137
22138    /**
22139     * Examine all apps present on given mounted volume, and destroy apps that
22140     * aren't expected, either due to uninstallation or reinstallation on
22141     * another volume.
22142     */
22143    private void reconcileApps(String volumeUuid) {
22144        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22145        List<File> filesToDelete = null;
22146
22147        final File[] files = FileUtils.listFilesOrEmpty(
22148                Environment.getDataAppDirectory(volumeUuid));
22149        for (File file : files) {
22150            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22151                    && !PackageInstallerService.isStageName(file.getName());
22152            if (!isPackage) {
22153                // Ignore entries which are not packages
22154                continue;
22155            }
22156
22157            String absolutePath = file.getAbsolutePath();
22158
22159            boolean pathValid = false;
22160            final int absoluteCodePathCount = absoluteCodePaths.size();
22161            for (int i = 0; i < absoluteCodePathCount; i++) {
22162                String absoluteCodePath = absoluteCodePaths.get(i);
22163                if (absolutePath.startsWith(absoluteCodePath)) {
22164                    pathValid = true;
22165                    break;
22166                }
22167            }
22168
22169            if (!pathValid) {
22170                if (filesToDelete == null) {
22171                    filesToDelete = new ArrayList<>();
22172                }
22173                filesToDelete.add(file);
22174            }
22175        }
22176
22177        if (filesToDelete != null) {
22178            final int fileToDeleteCount = filesToDelete.size();
22179            for (int i = 0; i < fileToDeleteCount; i++) {
22180                File fileToDelete = filesToDelete.get(i);
22181                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22182                synchronized (mInstallLock) {
22183                    removeCodePathLI(fileToDelete);
22184                }
22185            }
22186        }
22187    }
22188
22189    /**
22190     * Reconcile all app data for the given user.
22191     * <p>
22192     * Verifies that directories exist and that ownership and labeling is
22193     * correct for all installed apps on all mounted volumes.
22194     */
22195    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22196        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22197        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22198            final String volumeUuid = vol.getFsUuid();
22199            synchronized (mInstallLock) {
22200                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22201            }
22202        }
22203    }
22204
22205    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22206            boolean migrateAppData) {
22207        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22208    }
22209
22210    /**
22211     * Reconcile all app data on given mounted volume.
22212     * <p>
22213     * Destroys app data that isn't expected, either due to uninstallation or
22214     * reinstallation on another volume.
22215     * <p>
22216     * Verifies that directories exist and that ownership and labeling is
22217     * correct for all installed apps.
22218     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22219     */
22220    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22221            boolean migrateAppData, boolean onlyCoreApps) {
22222        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22223                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22224        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22225
22226        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22227        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22228
22229        // First look for stale data that doesn't belong, and check if things
22230        // have changed since we did our last restorecon
22231        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22232            if (StorageManager.isFileEncryptedNativeOrEmulated()
22233                    && !StorageManager.isUserKeyUnlocked(userId)) {
22234                throw new RuntimeException(
22235                        "Yikes, someone asked us to reconcile CE storage while " + userId
22236                                + " was still locked; this would have caused massive data loss!");
22237            }
22238
22239            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22240            for (File file : files) {
22241                final String packageName = file.getName();
22242                try {
22243                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22244                } catch (PackageManagerException e) {
22245                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22246                    try {
22247                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22248                                StorageManager.FLAG_STORAGE_CE, 0);
22249                    } catch (InstallerException e2) {
22250                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22251                    }
22252                }
22253            }
22254        }
22255        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22256            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22257            for (File file : files) {
22258                final String packageName = file.getName();
22259                try {
22260                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22261                } catch (PackageManagerException e) {
22262                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22263                    try {
22264                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22265                                StorageManager.FLAG_STORAGE_DE, 0);
22266                    } catch (InstallerException e2) {
22267                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22268                    }
22269                }
22270            }
22271        }
22272
22273        // Ensure that data directories are ready to roll for all packages
22274        // installed for this volume and user
22275        final List<PackageSetting> packages;
22276        synchronized (mPackages) {
22277            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22278        }
22279        int preparedCount = 0;
22280        for (PackageSetting ps : packages) {
22281            final String packageName = ps.name;
22282            if (ps.pkg == null) {
22283                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22284                // TODO: might be due to legacy ASEC apps; we should circle back
22285                // and reconcile again once they're scanned
22286                continue;
22287            }
22288            // Skip non-core apps if requested
22289            if (onlyCoreApps && !ps.pkg.coreApp) {
22290                result.add(packageName);
22291                continue;
22292            }
22293
22294            if (ps.getInstalled(userId)) {
22295                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22296                preparedCount++;
22297            }
22298        }
22299
22300        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22301        return result;
22302    }
22303
22304    /**
22305     * Prepare app data for the given app just after it was installed or
22306     * upgraded. This method carefully only touches users that it's installed
22307     * for, and it forces a restorecon to handle any seinfo changes.
22308     * <p>
22309     * Verifies that directories exist and that ownership and labeling is
22310     * correct for all installed apps. If there is an ownership mismatch, it
22311     * will try recovering system apps by wiping data; third-party app data is
22312     * left intact.
22313     * <p>
22314     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22315     */
22316    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22317        final PackageSetting ps;
22318        synchronized (mPackages) {
22319            ps = mSettings.mPackages.get(pkg.packageName);
22320            mSettings.writeKernelMappingLPr(ps);
22321        }
22322
22323        final UserManager um = mContext.getSystemService(UserManager.class);
22324        UserManagerInternal umInternal = getUserManagerInternal();
22325        for (UserInfo user : um.getUsers()) {
22326            final int flags;
22327            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22328                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22329            } else if (umInternal.isUserRunning(user.id)) {
22330                flags = StorageManager.FLAG_STORAGE_DE;
22331            } else {
22332                continue;
22333            }
22334
22335            if (ps.getInstalled(user.id)) {
22336                // TODO: when user data is locked, mark that we're still dirty
22337                prepareAppDataLIF(pkg, user.id, flags);
22338            }
22339        }
22340    }
22341
22342    /**
22343     * Prepare app data for the given app.
22344     * <p>
22345     * Verifies that directories exist and that ownership and labeling is
22346     * correct for all installed apps. If there is an ownership mismatch, this
22347     * will try recovering system apps by wiping data; third-party app data is
22348     * left intact.
22349     */
22350    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22351        if (pkg == null) {
22352            Slog.wtf(TAG, "Package was null!", new Throwable());
22353            return;
22354        }
22355        prepareAppDataLeafLIF(pkg, userId, flags);
22356        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22357        for (int i = 0; i < childCount; i++) {
22358            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22359        }
22360    }
22361
22362    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22363            boolean maybeMigrateAppData) {
22364        prepareAppDataLIF(pkg, userId, flags);
22365
22366        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22367            // We may have just shuffled around app data directories, so
22368            // prepare them one more time
22369            prepareAppDataLIF(pkg, userId, flags);
22370        }
22371    }
22372
22373    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22374        if (DEBUG_APP_DATA) {
22375            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22376                    + Integer.toHexString(flags));
22377        }
22378
22379        final String volumeUuid = pkg.volumeUuid;
22380        final String packageName = pkg.packageName;
22381        final ApplicationInfo app = pkg.applicationInfo;
22382        final int appId = UserHandle.getAppId(app.uid);
22383
22384        Preconditions.checkNotNull(app.seInfo);
22385
22386        long ceDataInode = -1;
22387        try {
22388            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22389                    appId, app.seInfo, app.targetSdkVersion);
22390        } catch (InstallerException e) {
22391            if (app.isSystemApp()) {
22392                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22393                        + ", but trying to recover: " + e);
22394                destroyAppDataLeafLIF(pkg, userId, flags);
22395                try {
22396                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22397                            appId, app.seInfo, app.targetSdkVersion);
22398                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22399                } catch (InstallerException e2) {
22400                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22401                }
22402            } else {
22403                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22404            }
22405        }
22406        // Prepare the application profiles only for upgrades and first boot (so that we don't
22407        // repeat the same operation at each boot).
22408        // We only have to cover the upgrade and first boot here because for app installs we
22409        // prepare the profiles before invoking dexopt (in installPackageLI).
22410        //
22411        // We also have to cover non system users because we do not call the usual install package
22412        // methods for them.
22413        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22414            mArtManagerService.prepareAppProfiles(pkg, userId);
22415        }
22416
22417        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22418            // TODO: mark this structure as dirty so we persist it!
22419            synchronized (mPackages) {
22420                final PackageSetting ps = mSettings.mPackages.get(packageName);
22421                if (ps != null) {
22422                    ps.setCeDataInode(ceDataInode, userId);
22423                }
22424            }
22425        }
22426
22427        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22428    }
22429
22430    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22431        if (pkg == null) {
22432            Slog.wtf(TAG, "Package was null!", new Throwable());
22433            return;
22434        }
22435        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22436        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22437        for (int i = 0; i < childCount; i++) {
22438            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22439        }
22440    }
22441
22442    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22443        final String volumeUuid = pkg.volumeUuid;
22444        final String packageName = pkg.packageName;
22445        final ApplicationInfo app = pkg.applicationInfo;
22446
22447        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22448            // Create a native library symlink only if we have native libraries
22449            // and if the native libraries are 32 bit libraries. We do not provide
22450            // this symlink for 64 bit libraries.
22451            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22452                final String nativeLibPath = app.nativeLibraryDir;
22453                try {
22454                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22455                            nativeLibPath, userId);
22456                } catch (InstallerException e) {
22457                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22458                }
22459            }
22460        }
22461    }
22462
22463    /**
22464     * For system apps on non-FBE devices, this method migrates any existing
22465     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22466     * requested by the app.
22467     */
22468    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22469        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22470                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22471            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22472                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22473            try {
22474                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22475                        storageTarget);
22476            } catch (InstallerException e) {
22477                logCriticalInfo(Log.WARN,
22478                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22479            }
22480            return true;
22481        } else {
22482            return false;
22483        }
22484    }
22485
22486    public PackageFreezer freezePackage(String packageName, String killReason) {
22487        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22488    }
22489
22490    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22491        return new PackageFreezer(packageName, userId, killReason);
22492    }
22493
22494    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22495            String killReason) {
22496        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22497    }
22498
22499    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22500            String killReason) {
22501        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22502            return new PackageFreezer();
22503        } else {
22504            return freezePackage(packageName, userId, killReason);
22505        }
22506    }
22507
22508    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22509            String killReason) {
22510        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22511    }
22512
22513    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22514            String killReason) {
22515        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22516            return new PackageFreezer();
22517        } else {
22518            return freezePackage(packageName, userId, killReason);
22519        }
22520    }
22521
22522    /**
22523     * Class that freezes and kills the given package upon creation, and
22524     * unfreezes it upon closing. This is typically used when doing surgery on
22525     * app code/data to prevent the app from running while you're working.
22526     */
22527    private class PackageFreezer implements AutoCloseable {
22528        private final String mPackageName;
22529        private final PackageFreezer[] mChildren;
22530
22531        private final boolean mWeFroze;
22532
22533        private final AtomicBoolean mClosed = new AtomicBoolean();
22534        private final CloseGuard mCloseGuard = CloseGuard.get();
22535
22536        /**
22537         * Create and return a stub freezer that doesn't actually do anything,
22538         * typically used when someone requested
22539         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22540         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22541         */
22542        public PackageFreezer() {
22543            mPackageName = null;
22544            mChildren = null;
22545            mWeFroze = false;
22546            mCloseGuard.open("close");
22547        }
22548
22549        public PackageFreezer(String packageName, int userId, String killReason) {
22550            synchronized (mPackages) {
22551                mPackageName = packageName;
22552                mWeFroze = mFrozenPackages.add(mPackageName);
22553
22554                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22555                if (ps != null) {
22556                    killApplication(ps.name, ps.appId, userId, killReason);
22557                }
22558
22559                final PackageParser.Package p = mPackages.get(packageName);
22560                if (p != null && p.childPackages != null) {
22561                    final int N = p.childPackages.size();
22562                    mChildren = new PackageFreezer[N];
22563                    for (int i = 0; i < N; i++) {
22564                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22565                                userId, killReason);
22566                    }
22567                } else {
22568                    mChildren = null;
22569                }
22570            }
22571            mCloseGuard.open("close");
22572        }
22573
22574        @Override
22575        protected void finalize() throws Throwable {
22576            try {
22577                if (mCloseGuard != null) {
22578                    mCloseGuard.warnIfOpen();
22579                }
22580
22581                close();
22582            } finally {
22583                super.finalize();
22584            }
22585        }
22586
22587        @Override
22588        public void close() {
22589            mCloseGuard.close();
22590            if (mClosed.compareAndSet(false, true)) {
22591                synchronized (mPackages) {
22592                    if (mWeFroze) {
22593                        mFrozenPackages.remove(mPackageName);
22594                    }
22595
22596                    if (mChildren != null) {
22597                        for (PackageFreezer freezer : mChildren) {
22598                            freezer.close();
22599                        }
22600                    }
22601                }
22602            }
22603        }
22604    }
22605
22606    /**
22607     * Verify that given package is currently frozen.
22608     */
22609    private void checkPackageFrozen(String packageName) {
22610        synchronized (mPackages) {
22611            if (!mFrozenPackages.contains(packageName)) {
22612                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22613            }
22614        }
22615    }
22616
22617    @Override
22618    public int movePackage(final String packageName, final String volumeUuid) {
22619        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22620
22621        final int callingUid = Binder.getCallingUid();
22622        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22623        final int moveId = mNextMoveId.getAndIncrement();
22624        mHandler.post(new Runnable() {
22625            @Override
22626            public void run() {
22627                try {
22628                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22629                } catch (PackageManagerException e) {
22630                    Slog.w(TAG, "Failed to move " + packageName, e);
22631                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22632                }
22633            }
22634        });
22635        return moveId;
22636    }
22637
22638    private void movePackageInternal(final String packageName, final String volumeUuid,
22639            final int moveId, final int callingUid, UserHandle user)
22640                    throws PackageManagerException {
22641        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22642        final PackageManager pm = mContext.getPackageManager();
22643
22644        final boolean currentAsec;
22645        final String currentVolumeUuid;
22646        final File codeFile;
22647        final String installerPackageName;
22648        final String packageAbiOverride;
22649        final int appId;
22650        final String seinfo;
22651        final String label;
22652        final int targetSdkVersion;
22653        final PackageFreezer freezer;
22654        final int[] installedUserIds;
22655
22656        // reader
22657        synchronized (mPackages) {
22658            final PackageParser.Package pkg = mPackages.get(packageName);
22659            final PackageSetting ps = mSettings.mPackages.get(packageName);
22660            if (pkg == null
22661                    || ps == null
22662                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22663                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22664            }
22665            if (pkg.applicationInfo.isSystemApp()) {
22666                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22667                        "Cannot move system application");
22668            }
22669
22670            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22671            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22672                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22673            if (isInternalStorage && !allow3rdPartyOnInternal) {
22674                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22675                        "3rd party apps are not allowed on internal storage");
22676            }
22677
22678            if (pkg.applicationInfo.isExternalAsec()) {
22679                currentAsec = true;
22680                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22681            } else if (pkg.applicationInfo.isForwardLocked()) {
22682                currentAsec = true;
22683                currentVolumeUuid = "forward_locked";
22684            } else {
22685                currentAsec = false;
22686                currentVolumeUuid = ps.volumeUuid;
22687
22688                final File probe = new File(pkg.codePath);
22689                final File probeOat = new File(probe, "oat");
22690                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22691                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22692                            "Move only supported for modern cluster style installs");
22693                }
22694            }
22695
22696            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22697                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22698                        "Package already moved to " + volumeUuid);
22699            }
22700            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22701                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22702                        "Device admin cannot be moved");
22703            }
22704
22705            if (mFrozenPackages.contains(packageName)) {
22706                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22707                        "Failed to move already frozen package");
22708            }
22709
22710            codeFile = new File(pkg.codePath);
22711            installerPackageName = ps.installerPackageName;
22712            packageAbiOverride = ps.cpuAbiOverrideString;
22713            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22714            seinfo = pkg.applicationInfo.seInfo;
22715            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22716            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22717            freezer = freezePackage(packageName, "movePackageInternal");
22718            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22719        }
22720
22721        final Bundle extras = new Bundle();
22722        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22723        extras.putString(Intent.EXTRA_TITLE, label);
22724        mMoveCallbacks.notifyCreated(moveId, extras);
22725
22726        int installFlags;
22727        final boolean moveCompleteApp;
22728        final File measurePath;
22729
22730        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22731            installFlags = INSTALL_INTERNAL;
22732            moveCompleteApp = !currentAsec;
22733            measurePath = Environment.getDataAppDirectory(volumeUuid);
22734        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22735            installFlags = INSTALL_EXTERNAL;
22736            moveCompleteApp = false;
22737            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22738        } else {
22739            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22740            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22741                    || !volume.isMountedWritable()) {
22742                freezer.close();
22743                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22744                        "Move location not mounted private volume");
22745            }
22746
22747            Preconditions.checkState(!currentAsec);
22748
22749            installFlags = INSTALL_INTERNAL;
22750            moveCompleteApp = true;
22751            measurePath = Environment.getDataAppDirectory(volumeUuid);
22752        }
22753
22754        // If we're moving app data around, we need all the users unlocked
22755        if (moveCompleteApp) {
22756            for (int userId : installedUserIds) {
22757                if (StorageManager.isFileEncryptedNativeOrEmulated()
22758                        && !StorageManager.isUserKeyUnlocked(userId)) {
22759                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22760                            "User " + userId + " must be unlocked");
22761                }
22762            }
22763        }
22764
22765        final PackageStats stats = new PackageStats(null, -1);
22766        synchronized (mInstaller) {
22767            for (int userId : installedUserIds) {
22768                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22769                    freezer.close();
22770                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22771                            "Failed to measure package size");
22772                }
22773            }
22774        }
22775
22776        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22777                + stats.dataSize);
22778
22779        final long startFreeBytes = measurePath.getUsableSpace();
22780        final long sizeBytes;
22781        if (moveCompleteApp) {
22782            sizeBytes = stats.codeSize + stats.dataSize;
22783        } else {
22784            sizeBytes = stats.codeSize;
22785        }
22786
22787        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22788            freezer.close();
22789            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22790                    "Not enough free space to move");
22791        }
22792
22793        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22794
22795        final CountDownLatch installedLatch = new CountDownLatch(1);
22796        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22797            @Override
22798            public void onUserActionRequired(Intent intent) throws RemoteException {
22799                throw new IllegalStateException();
22800            }
22801
22802            @Override
22803            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22804                    Bundle extras) throws RemoteException {
22805                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22806                        + PackageManager.installStatusToString(returnCode, msg));
22807
22808                installedLatch.countDown();
22809                freezer.close();
22810
22811                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22812                switch (status) {
22813                    case PackageInstaller.STATUS_SUCCESS:
22814                        mMoveCallbacks.notifyStatusChanged(moveId,
22815                                PackageManager.MOVE_SUCCEEDED);
22816                        break;
22817                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22818                        mMoveCallbacks.notifyStatusChanged(moveId,
22819                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22820                        break;
22821                    default:
22822                        mMoveCallbacks.notifyStatusChanged(moveId,
22823                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22824                        break;
22825                }
22826            }
22827        };
22828
22829        final MoveInfo move;
22830        if (moveCompleteApp) {
22831            // Kick off a thread to report progress estimates
22832            new Thread() {
22833                @Override
22834                public void run() {
22835                    while (true) {
22836                        try {
22837                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22838                                break;
22839                            }
22840                        } catch (InterruptedException ignored) {
22841                        }
22842
22843                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22844                        final int progress = 10 + (int) MathUtils.constrain(
22845                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22846                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22847                    }
22848                }
22849            }.start();
22850
22851            final String dataAppName = codeFile.getName();
22852            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22853                    dataAppName, appId, seinfo, targetSdkVersion);
22854        } else {
22855            move = null;
22856        }
22857
22858        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22859
22860        final Message msg = mHandler.obtainMessage(INIT_COPY);
22861        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22862        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22863                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22864                packageAbiOverride, null /*grantedPermissions*/,
22865                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22866        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22867        msg.obj = params;
22868
22869        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22870                System.identityHashCode(msg.obj));
22871        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22872                System.identityHashCode(msg.obj));
22873
22874        mHandler.sendMessage(msg);
22875    }
22876
22877    @Override
22878    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22879        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22880
22881        final int realMoveId = mNextMoveId.getAndIncrement();
22882        final Bundle extras = new Bundle();
22883        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22884        mMoveCallbacks.notifyCreated(realMoveId, extras);
22885
22886        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22887            @Override
22888            public void onCreated(int moveId, Bundle extras) {
22889                // Ignored
22890            }
22891
22892            @Override
22893            public void onStatusChanged(int moveId, int status, long estMillis) {
22894                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22895            }
22896        };
22897
22898        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22899        storage.setPrimaryStorageUuid(volumeUuid, callback);
22900        return realMoveId;
22901    }
22902
22903    @Override
22904    public int getMoveStatus(int moveId) {
22905        mContext.enforceCallingOrSelfPermission(
22906                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22907        return mMoveCallbacks.mLastStatus.get(moveId);
22908    }
22909
22910    @Override
22911    public void registerMoveCallback(IPackageMoveObserver callback) {
22912        mContext.enforceCallingOrSelfPermission(
22913                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22914        mMoveCallbacks.register(callback);
22915    }
22916
22917    @Override
22918    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22919        mContext.enforceCallingOrSelfPermission(
22920                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22921        mMoveCallbacks.unregister(callback);
22922    }
22923
22924    @Override
22925    public boolean setInstallLocation(int loc) {
22926        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22927                null);
22928        if (getInstallLocation() == loc) {
22929            return true;
22930        }
22931        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22932                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22933            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22934                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22935            return true;
22936        }
22937        return false;
22938   }
22939
22940    @Override
22941    public int getInstallLocation() {
22942        // allow instant app access
22943        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22944                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22945                PackageHelper.APP_INSTALL_AUTO);
22946    }
22947
22948    /** Called by UserManagerService */
22949    void cleanUpUser(UserManagerService userManager, int userHandle) {
22950        synchronized (mPackages) {
22951            mDirtyUsers.remove(userHandle);
22952            mUserNeedsBadging.delete(userHandle);
22953            mSettings.removeUserLPw(userHandle);
22954            mPendingBroadcasts.remove(userHandle);
22955            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22956            removeUnusedPackagesLPw(userManager, userHandle);
22957        }
22958    }
22959
22960    /**
22961     * We're removing userHandle and would like to remove any downloaded packages
22962     * that are no longer in use by any other user.
22963     * @param userHandle the user being removed
22964     */
22965    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22966        final boolean DEBUG_CLEAN_APKS = false;
22967        int [] users = userManager.getUserIds();
22968        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22969        while (psit.hasNext()) {
22970            PackageSetting ps = psit.next();
22971            if (ps.pkg == null) {
22972                continue;
22973            }
22974            final String packageName = ps.pkg.packageName;
22975            // Skip over if system app
22976            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22977                continue;
22978            }
22979            if (DEBUG_CLEAN_APKS) {
22980                Slog.i(TAG, "Checking package " + packageName);
22981            }
22982            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22983            if (keep) {
22984                if (DEBUG_CLEAN_APKS) {
22985                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22986                }
22987            } else {
22988                for (int i = 0; i < users.length; i++) {
22989                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22990                        keep = true;
22991                        if (DEBUG_CLEAN_APKS) {
22992                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22993                                    + users[i]);
22994                        }
22995                        break;
22996                    }
22997                }
22998            }
22999            if (!keep) {
23000                if (DEBUG_CLEAN_APKS) {
23001                    Slog.i(TAG, "  Removing package " + packageName);
23002                }
23003                mHandler.post(new Runnable() {
23004                    public void run() {
23005                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23006                                userHandle, 0);
23007                    } //end run
23008                });
23009            }
23010        }
23011    }
23012
23013    /** Called by UserManagerService */
23014    void createNewUser(int userId, String[] disallowedPackages) {
23015        synchronized (mInstallLock) {
23016            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23017        }
23018        synchronized (mPackages) {
23019            scheduleWritePackageRestrictionsLocked(userId);
23020            scheduleWritePackageListLocked(userId);
23021            applyFactoryDefaultBrowserLPw(userId);
23022            primeDomainVerificationsLPw(userId);
23023        }
23024    }
23025
23026    void onNewUserCreated(final int userId) {
23027        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23028        synchronized(mPackages) {
23029            // If permission review for legacy apps is required, we represent
23030            // dagerous permissions for such apps as always granted runtime
23031            // permissions to keep per user flag state whether review is needed.
23032            // Hence, if a new user is added we have to propagate dangerous
23033            // permission grants for these legacy apps.
23034            if (mSettings.mPermissions.mPermissionReviewRequired) {
23035// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23036                mPermissionManager.updateAllPermissions(
23037                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23038                        mPermissionCallback);
23039            }
23040        }
23041    }
23042
23043    @Override
23044    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23045        mContext.enforceCallingOrSelfPermission(
23046                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23047                "Only package verification agents can read the verifier device identity");
23048
23049        synchronized (mPackages) {
23050            return mSettings.getVerifierDeviceIdentityLPw();
23051        }
23052    }
23053
23054    @Override
23055    public void setPermissionEnforced(String permission, boolean enforced) {
23056        // TODO: Now that we no longer change GID for storage, this should to away.
23057        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23058                "setPermissionEnforced");
23059        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23060            synchronized (mPackages) {
23061                if (mSettings.mReadExternalStorageEnforced == null
23062                        || mSettings.mReadExternalStorageEnforced != enforced) {
23063                    mSettings.mReadExternalStorageEnforced =
23064                            enforced ? Boolean.TRUE : Boolean.FALSE;
23065                    mSettings.writeLPr();
23066                }
23067            }
23068            // kill any non-foreground processes so we restart them and
23069            // grant/revoke the GID.
23070            final IActivityManager am = ActivityManager.getService();
23071            if (am != null) {
23072                final long token = Binder.clearCallingIdentity();
23073                try {
23074                    am.killProcessesBelowForeground("setPermissionEnforcement");
23075                } catch (RemoteException e) {
23076                } finally {
23077                    Binder.restoreCallingIdentity(token);
23078                }
23079            }
23080        } else {
23081            throw new IllegalArgumentException("No selective enforcement for " + permission);
23082        }
23083    }
23084
23085    @Override
23086    @Deprecated
23087    public boolean isPermissionEnforced(String permission) {
23088        // allow instant applications
23089        return true;
23090    }
23091
23092    @Override
23093    public boolean isStorageLow() {
23094        // allow instant applications
23095        final long token = Binder.clearCallingIdentity();
23096        try {
23097            final DeviceStorageMonitorInternal
23098                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23099            if (dsm != null) {
23100                return dsm.isMemoryLow();
23101            } else {
23102                return false;
23103            }
23104        } finally {
23105            Binder.restoreCallingIdentity(token);
23106        }
23107    }
23108
23109    @Override
23110    public IPackageInstaller getPackageInstaller() {
23111        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23112            return null;
23113        }
23114        return mInstallerService;
23115    }
23116
23117    @Override
23118    public IArtManager getArtManager() {
23119        return mArtManagerService;
23120    }
23121
23122    private boolean userNeedsBadging(int userId) {
23123        int index = mUserNeedsBadging.indexOfKey(userId);
23124        if (index < 0) {
23125            final UserInfo userInfo;
23126            final long token = Binder.clearCallingIdentity();
23127            try {
23128                userInfo = sUserManager.getUserInfo(userId);
23129            } finally {
23130                Binder.restoreCallingIdentity(token);
23131            }
23132            final boolean b;
23133            if (userInfo != null && userInfo.isManagedProfile()) {
23134                b = true;
23135            } else {
23136                b = false;
23137            }
23138            mUserNeedsBadging.put(userId, b);
23139            return b;
23140        }
23141        return mUserNeedsBadging.valueAt(index);
23142    }
23143
23144    @Override
23145    public KeySet getKeySetByAlias(String packageName, String alias) {
23146        if (packageName == null || alias == null) {
23147            return null;
23148        }
23149        synchronized(mPackages) {
23150            final PackageParser.Package pkg = mPackages.get(packageName);
23151            if (pkg == null) {
23152                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23153                throw new IllegalArgumentException("Unknown package: " + packageName);
23154            }
23155            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23156            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23157                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23158                throw new IllegalArgumentException("Unknown package: " + packageName);
23159            }
23160            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23161            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23162        }
23163    }
23164
23165    @Override
23166    public KeySet getSigningKeySet(String packageName) {
23167        if (packageName == null) {
23168            return null;
23169        }
23170        synchronized(mPackages) {
23171            final int callingUid = Binder.getCallingUid();
23172            final int callingUserId = UserHandle.getUserId(callingUid);
23173            final PackageParser.Package pkg = mPackages.get(packageName);
23174            if (pkg == null) {
23175                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23176                throw new IllegalArgumentException("Unknown package: " + packageName);
23177            }
23178            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23179            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23180                // filter and pretend the package doesn't exist
23181                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23182                        + ", uid:" + callingUid);
23183                throw new IllegalArgumentException("Unknown package: " + packageName);
23184            }
23185            if (pkg.applicationInfo.uid != callingUid
23186                    && Process.SYSTEM_UID != callingUid) {
23187                throw new SecurityException("May not access signing KeySet of other apps.");
23188            }
23189            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23190            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23191        }
23192    }
23193
23194    @Override
23195    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23196        final int callingUid = Binder.getCallingUid();
23197        if (getInstantAppPackageName(callingUid) != null) {
23198            return false;
23199        }
23200        if (packageName == null || ks == null) {
23201            return false;
23202        }
23203        synchronized(mPackages) {
23204            final PackageParser.Package pkg = mPackages.get(packageName);
23205            if (pkg == null
23206                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23207                            UserHandle.getUserId(callingUid))) {
23208                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23209                throw new IllegalArgumentException("Unknown package: " + packageName);
23210            }
23211            IBinder ksh = ks.getToken();
23212            if (ksh instanceof KeySetHandle) {
23213                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23214                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23215            }
23216            return false;
23217        }
23218    }
23219
23220    @Override
23221    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23222        final int callingUid = Binder.getCallingUid();
23223        if (getInstantAppPackageName(callingUid) != null) {
23224            return false;
23225        }
23226        if (packageName == null || ks == null) {
23227            return false;
23228        }
23229        synchronized(mPackages) {
23230            final PackageParser.Package pkg = mPackages.get(packageName);
23231            if (pkg == null
23232                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23233                            UserHandle.getUserId(callingUid))) {
23234                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23235                throw new IllegalArgumentException("Unknown package: " + packageName);
23236            }
23237            IBinder ksh = ks.getToken();
23238            if (ksh instanceof KeySetHandle) {
23239                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23240                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23241            }
23242            return false;
23243        }
23244    }
23245
23246    private void deletePackageIfUnusedLPr(final String packageName) {
23247        PackageSetting ps = mSettings.mPackages.get(packageName);
23248        if (ps == null) {
23249            return;
23250        }
23251        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23252            // TODO Implement atomic delete if package is unused
23253            // It is currently possible that the package will be deleted even if it is installed
23254            // after this method returns.
23255            mHandler.post(new Runnable() {
23256                public void run() {
23257                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23258                            0, PackageManager.DELETE_ALL_USERS);
23259                }
23260            });
23261        }
23262    }
23263
23264    /**
23265     * Check and throw if the given before/after packages would be considered a
23266     * downgrade.
23267     */
23268    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23269            throws PackageManagerException {
23270        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23271            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23272                    "Update version code " + after.versionCode + " is older than current "
23273                    + before.getLongVersionCode());
23274        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23275            if (after.baseRevisionCode < before.baseRevisionCode) {
23276                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23277                        "Update base revision code " + after.baseRevisionCode
23278                        + " is older than current " + before.baseRevisionCode);
23279            }
23280
23281            if (!ArrayUtils.isEmpty(after.splitNames)) {
23282                for (int i = 0; i < after.splitNames.length; i++) {
23283                    final String splitName = after.splitNames[i];
23284                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23285                    if (j != -1) {
23286                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23287                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23288                                    "Update split " + splitName + " revision code "
23289                                    + after.splitRevisionCodes[i] + " is older than current "
23290                                    + before.splitRevisionCodes[j]);
23291                        }
23292                    }
23293                }
23294            }
23295        }
23296    }
23297
23298    private static class MoveCallbacks extends Handler {
23299        private static final int MSG_CREATED = 1;
23300        private static final int MSG_STATUS_CHANGED = 2;
23301
23302        private final RemoteCallbackList<IPackageMoveObserver>
23303                mCallbacks = new RemoteCallbackList<>();
23304
23305        private final SparseIntArray mLastStatus = new SparseIntArray();
23306
23307        public MoveCallbacks(Looper looper) {
23308            super(looper);
23309        }
23310
23311        public void register(IPackageMoveObserver callback) {
23312            mCallbacks.register(callback);
23313        }
23314
23315        public void unregister(IPackageMoveObserver callback) {
23316            mCallbacks.unregister(callback);
23317        }
23318
23319        @Override
23320        public void handleMessage(Message msg) {
23321            final SomeArgs args = (SomeArgs) msg.obj;
23322            final int n = mCallbacks.beginBroadcast();
23323            for (int i = 0; i < n; i++) {
23324                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23325                try {
23326                    invokeCallback(callback, msg.what, args);
23327                } catch (RemoteException ignored) {
23328                }
23329            }
23330            mCallbacks.finishBroadcast();
23331            args.recycle();
23332        }
23333
23334        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23335                throws RemoteException {
23336            switch (what) {
23337                case MSG_CREATED: {
23338                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23339                    break;
23340                }
23341                case MSG_STATUS_CHANGED: {
23342                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23343                    break;
23344                }
23345            }
23346        }
23347
23348        private void notifyCreated(int moveId, Bundle extras) {
23349            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23350
23351            final SomeArgs args = SomeArgs.obtain();
23352            args.argi1 = moveId;
23353            args.arg2 = extras;
23354            obtainMessage(MSG_CREATED, args).sendToTarget();
23355        }
23356
23357        private void notifyStatusChanged(int moveId, int status) {
23358            notifyStatusChanged(moveId, status, -1);
23359        }
23360
23361        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23362            Slog.v(TAG, "Move " + moveId + " status " + status);
23363
23364            final SomeArgs args = SomeArgs.obtain();
23365            args.argi1 = moveId;
23366            args.argi2 = status;
23367            args.arg3 = estMillis;
23368            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23369
23370            synchronized (mLastStatus) {
23371                mLastStatus.put(moveId, status);
23372            }
23373        }
23374    }
23375
23376    private final static class OnPermissionChangeListeners extends Handler {
23377        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23378
23379        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23380                new RemoteCallbackList<>();
23381
23382        public OnPermissionChangeListeners(Looper looper) {
23383            super(looper);
23384        }
23385
23386        @Override
23387        public void handleMessage(Message msg) {
23388            switch (msg.what) {
23389                case MSG_ON_PERMISSIONS_CHANGED: {
23390                    final int uid = msg.arg1;
23391                    handleOnPermissionsChanged(uid);
23392                } break;
23393            }
23394        }
23395
23396        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23397            mPermissionListeners.register(listener);
23398
23399        }
23400
23401        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23402            mPermissionListeners.unregister(listener);
23403        }
23404
23405        public void onPermissionsChanged(int uid) {
23406            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23407                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23408            }
23409        }
23410
23411        private void handleOnPermissionsChanged(int uid) {
23412            final int count = mPermissionListeners.beginBroadcast();
23413            try {
23414                for (int i = 0; i < count; i++) {
23415                    IOnPermissionsChangeListener callback = mPermissionListeners
23416                            .getBroadcastItem(i);
23417                    try {
23418                        callback.onPermissionsChanged(uid);
23419                    } catch (RemoteException e) {
23420                        Log.e(TAG, "Permission listener is dead", e);
23421                    }
23422                }
23423            } finally {
23424                mPermissionListeners.finishBroadcast();
23425            }
23426        }
23427    }
23428
23429    private class PackageManagerNative extends IPackageManagerNative.Stub {
23430        @Override
23431        public String[] getNamesForUids(int[] uids) throws RemoteException {
23432            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23433            // massage results so they can be parsed by the native binder
23434            for (int i = results.length - 1; i >= 0; --i) {
23435                if (results[i] == null) {
23436                    results[i] = "";
23437                }
23438            }
23439            return results;
23440        }
23441
23442        // NB: this differentiates between preloads and sideloads
23443        @Override
23444        public String getInstallerForPackage(String packageName) throws RemoteException {
23445            final String installerName = getInstallerPackageName(packageName);
23446            if (!TextUtils.isEmpty(installerName)) {
23447                return installerName;
23448            }
23449            // differentiate between preload and sideload
23450            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23451            ApplicationInfo appInfo = getApplicationInfo(packageName,
23452                                    /*flags*/ 0,
23453                                    /*userId*/ callingUser);
23454            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23455                return "preload";
23456            }
23457            return "";
23458        }
23459
23460        @Override
23461        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23462            try {
23463                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23464                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23465                if (pInfo != null) {
23466                    return pInfo.getLongVersionCode();
23467                }
23468            } catch (Exception e) {
23469            }
23470            return 0;
23471        }
23472    }
23473
23474    private class PackageManagerInternalImpl extends PackageManagerInternal {
23475        @Override
23476        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23477                int flagValues, int userId) {
23478            PackageManagerService.this.updatePermissionFlags(
23479                    permName, packageName, flagMask, flagValues, userId);
23480        }
23481
23482        @Override
23483        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23484            SigningDetails sd = getSigningDetails(packageName);
23485            if (sd == null) {
23486                return false;
23487            }
23488            return sd.hasSha256Certificate(restoringFromSigHash,
23489                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23490        }
23491
23492        @Override
23493        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23494            SigningDetails sd = getSigningDetails(packageName);
23495            if (sd == null) {
23496                return false;
23497            }
23498            return sd.hasCertificate(restoringFromSig,
23499                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23500        }
23501
23502        private SigningDetails getSigningDetails(@NonNull String packageName) {
23503            synchronized (mPackages) {
23504                PackageParser.Package p = mPackages.get(packageName);
23505                if (p == null) {
23506                    return null;
23507                }
23508                return p.mSigningDetails;
23509            }
23510        }
23511
23512        @Override
23513        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23514            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23515        }
23516
23517        @Override
23518        public boolean isInstantApp(String packageName, int userId) {
23519            return PackageManagerService.this.isInstantApp(packageName, userId);
23520        }
23521
23522        @Override
23523        public String getInstantAppPackageName(int uid) {
23524            return PackageManagerService.this.getInstantAppPackageName(uid);
23525        }
23526
23527        @Override
23528        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23529            synchronized (mPackages) {
23530                return PackageManagerService.this.filterAppAccessLPr(
23531                        (PackageSetting) pkg.mExtras, callingUid, userId);
23532            }
23533        }
23534
23535        @Override
23536        public PackageParser.Package getPackage(String packageName) {
23537            synchronized (mPackages) {
23538                packageName = resolveInternalPackageNameLPr(
23539                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23540                return mPackages.get(packageName);
23541            }
23542        }
23543
23544        @Override
23545        public PackageList getPackageList(PackageListObserver observer) {
23546            synchronized (mPackages) {
23547                final int N = mPackages.size();
23548                final ArrayList<String> list = new ArrayList<>(N);
23549                for (int i = 0; i < N; i++) {
23550                    list.add(mPackages.keyAt(i));
23551                }
23552                final PackageList packageList = new PackageList(list, observer);
23553                if (observer != null) {
23554                    mPackageListObservers.add(packageList);
23555                }
23556                return packageList;
23557            }
23558        }
23559
23560        @Override
23561        public void removePackageListObserver(PackageListObserver observer) {
23562            synchronized (mPackages) {
23563                mPackageListObservers.remove(observer);
23564            }
23565        }
23566
23567        @Override
23568        public PackageParser.Package getDisabledPackage(String packageName) {
23569            synchronized (mPackages) {
23570                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23571                return (ps != null) ? ps.pkg : null;
23572            }
23573        }
23574
23575        @Override
23576        public String getKnownPackageName(int knownPackage, int userId) {
23577            switch(knownPackage) {
23578                case PackageManagerInternal.PACKAGE_BROWSER:
23579                    return getDefaultBrowserPackageName(userId);
23580                case PackageManagerInternal.PACKAGE_INSTALLER:
23581                    return mRequiredInstallerPackage;
23582                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23583                    return mSetupWizardPackage;
23584                case PackageManagerInternal.PACKAGE_SYSTEM:
23585                    return "android";
23586                case PackageManagerInternal.PACKAGE_VERIFIER:
23587                    return mRequiredVerifierPackage;
23588                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23589                    return mSystemTextClassifierPackage;
23590            }
23591            return null;
23592        }
23593
23594        @Override
23595        public boolean isResolveActivityComponent(ComponentInfo component) {
23596            return mResolveActivity.packageName.equals(component.packageName)
23597                    && mResolveActivity.name.equals(component.name);
23598        }
23599
23600        @Override
23601        public void setLocationPackagesProvider(PackagesProvider provider) {
23602            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23603        }
23604
23605        @Override
23606        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23607            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23608        }
23609
23610        @Override
23611        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23612            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23613        }
23614
23615        @Override
23616        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23617            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23618        }
23619
23620        @Override
23621        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23622            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23623        }
23624
23625        @Override
23626        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23627            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23628        }
23629
23630        @Override
23631        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23632            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23633        }
23634
23635        @Override
23636        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23637            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23638        }
23639
23640        @Override
23641        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23642            synchronized (mPackages) {
23643                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23644            }
23645            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23646        }
23647
23648        @Override
23649        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23650            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23651                    packageName, userId);
23652        }
23653
23654        @Override
23655        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23656            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23657                    packageName, userId);
23658        }
23659
23660        @Override
23661        public void setKeepUninstalledPackages(final List<String> packageList) {
23662            Preconditions.checkNotNull(packageList);
23663            List<String> removedFromList = null;
23664            synchronized (mPackages) {
23665                if (mKeepUninstalledPackages != null) {
23666                    final int packagesCount = mKeepUninstalledPackages.size();
23667                    for (int i = 0; i < packagesCount; i++) {
23668                        String oldPackage = mKeepUninstalledPackages.get(i);
23669                        if (packageList != null && packageList.contains(oldPackage)) {
23670                            continue;
23671                        }
23672                        if (removedFromList == null) {
23673                            removedFromList = new ArrayList<>();
23674                        }
23675                        removedFromList.add(oldPackage);
23676                    }
23677                }
23678                mKeepUninstalledPackages = new ArrayList<>(packageList);
23679                if (removedFromList != null) {
23680                    final int removedCount = removedFromList.size();
23681                    for (int i = 0; i < removedCount; i++) {
23682                        deletePackageIfUnusedLPr(removedFromList.get(i));
23683                    }
23684                }
23685            }
23686        }
23687
23688        @Override
23689        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23690            synchronized (mPackages) {
23691                return mPermissionManager.isPermissionsReviewRequired(
23692                        mPackages.get(packageName), userId);
23693            }
23694        }
23695
23696        @Override
23697        public PackageInfo getPackageInfo(
23698                String packageName, int flags, int filterCallingUid, int userId) {
23699            return PackageManagerService.this
23700                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23701                            flags, filterCallingUid, userId);
23702        }
23703
23704        @Override
23705        public int getPackageUid(String packageName, int flags, int userId) {
23706            return PackageManagerService.this
23707                    .getPackageUid(packageName, flags, userId);
23708        }
23709
23710        @Override
23711        public ApplicationInfo getApplicationInfo(
23712                String packageName, int flags, int filterCallingUid, int userId) {
23713            return PackageManagerService.this
23714                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23715        }
23716
23717        @Override
23718        public ActivityInfo getActivityInfo(
23719                ComponentName component, int flags, int filterCallingUid, int userId) {
23720            return PackageManagerService.this
23721                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23722        }
23723
23724        @Override
23725        public List<ResolveInfo> queryIntentActivities(
23726                Intent intent, int flags, int filterCallingUid, int userId) {
23727            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23728            return PackageManagerService.this
23729                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23730                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23731        }
23732
23733        @Override
23734        public List<ResolveInfo> queryIntentServices(
23735                Intent intent, int flags, int callingUid, int userId) {
23736            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23737            return PackageManagerService.this
23738                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23739                            false);
23740        }
23741
23742        @Override
23743        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23744                int userId) {
23745            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23746        }
23747
23748        @Override
23749        public ComponentName getDefaultHomeActivity(int userId) {
23750            return PackageManagerService.this.getDefaultHomeActivity(userId);
23751        }
23752
23753        @Override
23754        public void setDeviceAndProfileOwnerPackages(
23755                int deviceOwnerUserId, String deviceOwnerPackage,
23756                SparseArray<String> profileOwnerPackages) {
23757            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23758                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23759        }
23760
23761        @Override
23762        public boolean isPackageDataProtected(int userId, String packageName) {
23763            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23764        }
23765
23766        @Override
23767        public boolean isPackageEphemeral(int userId, String packageName) {
23768            synchronized (mPackages) {
23769                final PackageSetting ps = mSettings.mPackages.get(packageName);
23770                return ps != null ? ps.getInstantApp(userId) : false;
23771            }
23772        }
23773
23774        @Override
23775        public boolean wasPackageEverLaunched(String packageName, int userId) {
23776            synchronized (mPackages) {
23777                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23778            }
23779        }
23780
23781        @Override
23782        public void grantRuntimePermission(String packageName, String permName, int userId,
23783                boolean overridePolicy) {
23784            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23785                    permName, packageName, overridePolicy, getCallingUid(), userId,
23786                    mPermissionCallback);
23787        }
23788
23789        @Override
23790        public void revokeRuntimePermission(String packageName, String permName, int userId,
23791                boolean overridePolicy) {
23792            mPermissionManager.revokeRuntimePermission(
23793                    permName, packageName, overridePolicy, getCallingUid(), userId,
23794                    mPermissionCallback);
23795        }
23796
23797        @Override
23798        public String getNameForUid(int uid) {
23799            return PackageManagerService.this.getNameForUid(uid);
23800        }
23801
23802        @Override
23803        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23804                Intent origIntent, String resolvedType, String callingPackage,
23805                Bundle verificationBundle, int userId) {
23806            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23807                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23808                    userId);
23809        }
23810
23811        @Override
23812        public void grantEphemeralAccess(int userId, Intent intent,
23813                int targetAppId, int ephemeralAppId) {
23814            synchronized (mPackages) {
23815                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23816                        targetAppId, ephemeralAppId);
23817            }
23818        }
23819
23820        @Override
23821        public boolean isInstantAppInstallerComponent(ComponentName component) {
23822            synchronized (mPackages) {
23823                return mInstantAppInstallerActivity != null
23824                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23825            }
23826        }
23827
23828        @Override
23829        public void pruneInstantApps() {
23830            mInstantAppRegistry.pruneInstantApps();
23831        }
23832
23833        @Override
23834        public String getSetupWizardPackageName() {
23835            return mSetupWizardPackage;
23836        }
23837
23838        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23839            if (policy != null) {
23840                mExternalSourcesPolicy = policy;
23841            }
23842        }
23843
23844        @Override
23845        public boolean isPackagePersistent(String packageName) {
23846            synchronized (mPackages) {
23847                PackageParser.Package pkg = mPackages.get(packageName);
23848                return pkg != null
23849                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23850                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23851                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23852                        : false;
23853            }
23854        }
23855
23856        @Override
23857        public boolean isLegacySystemApp(Package pkg) {
23858            synchronized (mPackages) {
23859                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23860                return mPromoteSystemApps
23861                        && ps.isSystem()
23862                        && mExistingSystemPackages.contains(ps.name);
23863            }
23864        }
23865
23866        @Override
23867        public List<PackageInfo> getOverlayPackages(int userId) {
23868            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23869            synchronized (mPackages) {
23870                for (PackageParser.Package p : mPackages.values()) {
23871                    if (p.mOverlayTarget != null) {
23872                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23873                        if (pkg != null) {
23874                            overlayPackages.add(pkg);
23875                        }
23876                    }
23877                }
23878            }
23879            return overlayPackages;
23880        }
23881
23882        @Override
23883        public List<String> getTargetPackageNames(int userId) {
23884            List<String> targetPackages = new ArrayList<>();
23885            synchronized (mPackages) {
23886                for (PackageParser.Package p : mPackages.values()) {
23887                    if (p.mOverlayTarget == null) {
23888                        targetPackages.add(p.packageName);
23889                    }
23890                }
23891            }
23892            return targetPackages;
23893        }
23894
23895        @Override
23896        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23897                @Nullable List<String> overlayPackageNames) {
23898            synchronized (mPackages) {
23899                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23900                    Slog.e(TAG, "failed to find package " + targetPackageName);
23901                    return false;
23902                }
23903                ArrayList<String> overlayPaths = null;
23904                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23905                    final int N = overlayPackageNames.size();
23906                    overlayPaths = new ArrayList<>(N);
23907                    for (int i = 0; i < N; i++) {
23908                        final String packageName = overlayPackageNames.get(i);
23909                        final PackageParser.Package pkg = mPackages.get(packageName);
23910                        if (pkg == null) {
23911                            Slog.e(TAG, "failed to find package " + packageName);
23912                            return false;
23913                        }
23914                        overlayPaths.add(pkg.baseCodePath);
23915                    }
23916                }
23917
23918                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23919                ps.setOverlayPaths(overlayPaths, userId);
23920                return true;
23921            }
23922        }
23923
23924        @Override
23925        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23926                int flags, int userId, boolean resolveForStart) {
23927            return resolveIntentInternal(
23928                    intent, resolvedType, flags, userId, resolveForStart);
23929        }
23930
23931        @Override
23932        public ResolveInfo resolveService(Intent intent, String resolvedType,
23933                int flags, int userId, int callingUid) {
23934            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23935        }
23936
23937        @Override
23938        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23939            return PackageManagerService.this.resolveContentProviderInternal(
23940                    name, flags, userId);
23941        }
23942
23943        @Override
23944        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23945            synchronized (mPackages) {
23946                mIsolatedOwners.put(isolatedUid, ownerUid);
23947            }
23948        }
23949
23950        @Override
23951        public void removeIsolatedUid(int isolatedUid) {
23952            synchronized (mPackages) {
23953                mIsolatedOwners.delete(isolatedUid);
23954            }
23955        }
23956
23957        @Override
23958        public int getUidTargetSdkVersion(int uid) {
23959            synchronized (mPackages) {
23960                return getUidTargetSdkVersionLockedLPr(uid);
23961            }
23962        }
23963
23964        @Override
23965        public int getPackageTargetSdkVersion(String packageName) {
23966            synchronized (mPackages) {
23967                return getPackageTargetSdkVersionLockedLPr(packageName);
23968            }
23969        }
23970
23971        @Override
23972        public boolean canAccessInstantApps(int callingUid, int userId) {
23973            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23974        }
23975
23976        @Override
23977        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
23978            synchronized (mPackages) {
23979                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
23980                return !PackageManagerService.this.filterAppAccessLPr(
23981                        ps, callingUid, component, TYPE_UNKNOWN, userId);
23982            }
23983        }
23984
23985        @Override
23986        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23987            synchronized (mPackages) {
23988                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23989            }
23990        }
23991
23992        @Override
23993        public void notifyPackageUse(String packageName, int reason) {
23994            synchronized (mPackages) {
23995                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23996            }
23997        }
23998    }
23999
24000    @Override
24001    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24002        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24003        synchronized (mPackages) {
24004            final long identity = Binder.clearCallingIdentity();
24005            try {
24006                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24007                        packageNames, userId);
24008            } finally {
24009                Binder.restoreCallingIdentity(identity);
24010            }
24011        }
24012    }
24013
24014    @Override
24015    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24016        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24017        synchronized (mPackages) {
24018            final long identity = Binder.clearCallingIdentity();
24019            try {
24020                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24021                        packageNames, userId);
24022            } finally {
24023                Binder.restoreCallingIdentity(identity);
24024            }
24025        }
24026    }
24027
24028    private static void enforceSystemOrPhoneCaller(String tag) {
24029        int callingUid = Binder.getCallingUid();
24030        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24031            throw new SecurityException(
24032                    "Cannot call " + tag + " from UID " + callingUid);
24033        }
24034    }
24035
24036    boolean isHistoricalPackageUsageAvailable() {
24037        return mPackageUsage.isHistoricalPackageUsageAvailable();
24038    }
24039
24040    /**
24041     * Return a <b>copy</b> of the collection of packages known to the package manager.
24042     * @return A copy of the values of mPackages.
24043     */
24044    Collection<PackageParser.Package> getPackages() {
24045        synchronized (mPackages) {
24046            return new ArrayList<>(mPackages.values());
24047        }
24048    }
24049
24050    /**
24051     * Logs process start information (including base APK hash) to the security log.
24052     * @hide
24053     */
24054    @Override
24055    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24056            String apkFile, int pid) {
24057        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24058            return;
24059        }
24060        if (!SecurityLog.isLoggingEnabled()) {
24061            return;
24062        }
24063        Bundle data = new Bundle();
24064        data.putLong("startTimestamp", System.currentTimeMillis());
24065        data.putString("processName", processName);
24066        data.putInt("uid", uid);
24067        data.putString("seinfo", seinfo);
24068        data.putString("apkFile", apkFile);
24069        data.putInt("pid", pid);
24070        Message msg = mProcessLoggingHandler.obtainMessage(
24071                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24072        msg.setData(data);
24073        mProcessLoggingHandler.sendMessage(msg);
24074    }
24075
24076    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24077        return mCompilerStats.getPackageStats(pkgName);
24078    }
24079
24080    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24081        return getOrCreateCompilerPackageStats(pkg.packageName);
24082    }
24083
24084    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24085        return mCompilerStats.getOrCreatePackageStats(pkgName);
24086    }
24087
24088    public void deleteCompilerPackageStats(String pkgName) {
24089        mCompilerStats.deletePackageStats(pkgName);
24090    }
24091
24092    @Override
24093    public int getInstallReason(String packageName, int userId) {
24094        final int callingUid = Binder.getCallingUid();
24095        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24096                true /* requireFullPermission */, false /* checkShell */,
24097                "get install reason");
24098        synchronized (mPackages) {
24099            final PackageSetting ps = mSettings.mPackages.get(packageName);
24100            if (filterAppAccessLPr(ps, callingUid, userId)) {
24101                return PackageManager.INSTALL_REASON_UNKNOWN;
24102            }
24103            if (ps != null) {
24104                return ps.getInstallReason(userId);
24105            }
24106        }
24107        return PackageManager.INSTALL_REASON_UNKNOWN;
24108    }
24109
24110    @Override
24111    public boolean canRequestPackageInstalls(String packageName, int userId) {
24112        return canRequestPackageInstallsInternal(packageName, 0, userId,
24113                true /* throwIfPermNotDeclared*/);
24114    }
24115
24116    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24117            boolean throwIfPermNotDeclared) {
24118        int callingUid = Binder.getCallingUid();
24119        int uid = getPackageUid(packageName, 0, userId);
24120        if (callingUid != uid && callingUid != Process.ROOT_UID
24121                && callingUid != Process.SYSTEM_UID) {
24122            throw new SecurityException(
24123                    "Caller uid " + callingUid + " does not own package " + packageName);
24124        }
24125        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24126        if (info == null) {
24127            return false;
24128        }
24129        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24130            return false;
24131        }
24132        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24133        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24134        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24135            if (throwIfPermNotDeclared) {
24136                throw new SecurityException("Need to declare " + appOpPermission
24137                        + " to call this api");
24138            } else {
24139                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24140                return false;
24141            }
24142        }
24143        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24144            return false;
24145        }
24146        if (mExternalSourcesPolicy != null) {
24147            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24148            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24149                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24150            }
24151        }
24152        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24153    }
24154
24155    @Override
24156    public ComponentName getInstantAppResolverSettingsComponent() {
24157        return mInstantAppResolverSettingsComponent;
24158    }
24159
24160    @Override
24161    public ComponentName getInstantAppInstallerComponent() {
24162        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24163            return null;
24164        }
24165        return mInstantAppInstallerActivity == null
24166                ? null : mInstantAppInstallerActivity.getComponentName();
24167    }
24168
24169    @Override
24170    public String getInstantAppAndroidId(String packageName, int userId) {
24171        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24172                "getInstantAppAndroidId");
24173        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24174                true /* requireFullPermission */, false /* checkShell */,
24175                "getInstantAppAndroidId");
24176        // Make sure the target is an Instant App.
24177        if (!isInstantApp(packageName, userId)) {
24178            return null;
24179        }
24180        synchronized (mPackages) {
24181            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24182        }
24183    }
24184
24185    boolean canHaveOatDir(String packageName) {
24186        synchronized (mPackages) {
24187            PackageParser.Package p = mPackages.get(packageName);
24188            if (p == null) {
24189                return false;
24190            }
24191            return p.canHaveOatDir();
24192        }
24193    }
24194
24195    private String getOatDir(PackageParser.Package pkg) {
24196        if (!pkg.canHaveOatDir()) {
24197            return null;
24198        }
24199        File codePath = new File(pkg.codePath);
24200        if (codePath.isDirectory()) {
24201            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24202        }
24203        return null;
24204    }
24205
24206    void deleteOatArtifactsOfPackage(String packageName) {
24207        final String[] instructionSets;
24208        final List<String> codePaths;
24209        final String oatDir;
24210        final PackageParser.Package pkg;
24211        synchronized (mPackages) {
24212            pkg = mPackages.get(packageName);
24213        }
24214        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24215        codePaths = pkg.getAllCodePaths();
24216        oatDir = getOatDir(pkg);
24217
24218        for (String codePath : codePaths) {
24219            for (String isa : instructionSets) {
24220                try {
24221                    mInstaller.deleteOdex(codePath, isa, oatDir);
24222                } catch (InstallerException e) {
24223                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24224                }
24225            }
24226        }
24227    }
24228
24229    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24230        Set<String> unusedPackages = new HashSet<>();
24231        long currentTimeInMillis = System.currentTimeMillis();
24232        synchronized (mPackages) {
24233            for (PackageParser.Package pkg : mPackages.values()) {
24234                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24235                if (ps == null) {
24236                    continue;
24237                }
24238                PackageDexUsage.PackageUseInfo packageUseInfo =
24239                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24240                if (PackageManagerServiceUtils
24241                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24242                                downgradeTimeThresholdMillis, packageUseInfo,
24243                                pkg.getLatestPackageUseTimeInMills(),
24244                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24245                    unusedPackages.add(pkg.packageName);
24246                }
24247            }
24248        }
24249        return unusedPackages;
24250    }
24251
24252    @Override
24253    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24254            int userId) {
24255        final int callingUid = Binder.getCallingUid();
24256        final int callingAppId = UserHandle.getAppId(callingUid);
24257
24258        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24259                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24260
24261        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24262                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24263            throw new SecurityException("Caller must have the "
24264                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24265        }
24266
24267        synchronized(mPackages) {
24268            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24269            scheduleWritePackageRestrictionsLocked(userId);
24270        }
24271    }
24272
24273    @Nullable
24274    @Override
24275    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24276        final int callingUid = Binder.getCallingUid();
24277        final int callingAppId = UserHandle.getAppId(callingUid);
24278
24279        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24280                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24281
24282        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24283                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24284            throw new SecurityException("Caller must have the "
24285                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24286        }
24287
24288        synchronized(mPackages) {
24289            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24290        }
24291    }
24292}
24293
24294interface PackageSender {
24295    /**
24296     * @param userIds User IDs where the action occurred on a full application
24297     * @param instantUserIds User IDs where the action occurred on an instant application
24298     */
24299    void sendPackageBroadcast(final String action, final String pkg,
24300        final Bundle extras, final int flags, final String targetPkg,
24301        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24302    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24303        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24304    void notifyPackageAdded(String packageName);
24305    void notifyPackageRemoved(String packageName);
24306}
24307